├── LICENCE ├── tests ├── tse │ ├── 3iwilllogargs.ts │ ├── test.bat │ ├── 2iwillfork.ts │ ├── 1start.ts │ └── tsconfig.json └── grunt │ ├── fail │ ├── tsconfig.json │ ├── fail.js │ └── fail.ts │ └── pass │ ├── tsconfig.json │ ├── pass.ts │ └── pass.js ├── .npmignore ├── quick.sh ├── src ├── services │ ├── refactors │ │ └── refactors.ts │ ├── formatting │ │ ├── ruleFlag.ts │ │ ├── ruleAction.ts │ │ ├── formattingRequestKind.ts │ │ ├── references.ts │ │ ├── rule.ts │ │ ├── ruleOperation.ts │ │ ├── ruleOperationContext.ts │ │ ├── ruleDescriptor.ts │ │ ├── rulesProvider.ts │ │ ├── formattingContext.ts │ │ ├── tokenRange.ts │ │ └── rulesMap.ts │ ├── codefixes │ │ ├── fixes.ts │ │ ├── fixForgottenThisPropertyAccess.ts │ │ ├── fixConstructorForDerivedNeedSuperCall.ts │ │ ├── fixExtendsInterfaceBecomesImplements.ts │ │ ├── fixSpelling.ts │ │ ├── fixClassSuperMustPrecedeThisAccess.ts │ │ ├── fixClassDoesntImplementInheritedAbstractMember.ts │ │ ├── fixClassIncorrectlyImplementsInterface.ts │ │ └── disableJsDiagnostics.ts │ ├── transform.ts │ ├── codeFixProvider.ts │ ├── goToImplementation.ts │ ├── refactorProvider.ts │ ├── rename.ts │ ├── transpile.ts │ ├── outliningElementsCollector.ts │ └── navigateTo.ts ├── extensions.ts ├── tsconfig.json └── compiler │ ├── performance.ts │ └── transformers │ ├── es7.ts │ ├── es2016.ts │ ├── module │ ├── es2015.ts │ └── es6.ts │ ├── es5.ts │ └── utilities.ts ├── kicktravis ├── bin ├── tsc ├── lib.es2016.d.ts ├── lib.esnext.d.ts ├── lib.es2017.d.ts ├── lib.es2017.intl.d.ts ├── lib.es2015.d.ts ├── lib.esnext.asynciterable.d.ts ├── lib.es2015.reflect.d.ts ├── lib.es2015.symbol.d.ts ├── lib.es2015.proxy.d.ts ├── lib.es2017.object.d.ts ├── lib.es2015.generator.d.ts ├── lib.es2017.string.d.ts ├── lib.es2015.collection.d.ts ├── lib.dom.iterable.d.ts ├── lib.es2016.array.include.d.ts ├── lib.es2017.sharedmemory.d.ts ├── lib.scripthost.d.ts └── lib.scriptHost.d.ts ├── .gitmodules ├── typings └── tsd.d.ts ├── tsd.json ├── appveyor.yml ├── .gitignore ├── extensions ├── tsconfig.json ├── preBuild.ts ├── preBuild.js ├── addExtensions.js └── addExtensions.ts ├── Gruntfile.js ├── CONTRIBUTING.md ├── package.json ├── release.sh ├── tasks ├── ntypescript.js └── ntypescript.ts ├── prepare.sh ├── register.js ├── register.ts ├── .travis.yml ├── tsconfig.json └── README.md /LICENCE: -------------------------------------------------------------------------------- 1 | MIT 2 | -------------------------------------------------------------------------------- /tests/tse/3iwilllogargs.ts: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/grunt/fail/tsconfig.json: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /tests/grunt/pass/tsconfig.json: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /tests/tse/test.bat: -------------------------------------------------------------------------------- 1 | ntse 1start.ts -------------------------------------------------------------------------------- /tests/grunt/pass/pass.ts: -------------------------------------------------------------------------------- 1 | var foo = 123; -------------------------------------------------------------------------------- /tests/grunt/pass/pass.js: -------------------------------------------------------------------------------- 1 | var foo = 123; 2 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | TypeScript 2 | .gitmodules 3 | tests -------------------------------------------------------------------------------- /tests/grunt/fail/fail.js: -------------------------------------------------------------------------------- 1 | var foo = 123; 2 | var bar = foo; 3 | -------------------------------------------------------------------------------- /tests/grunt/fail/fail.ts: -------------------------------------------------------------------------------- 1 | var foo = 123; 2 | var bar: string = foo; -------------------------------------------------------------------------------- /quick.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -e 4 | 5 | ./prepare.sh 6 | 7 | ./release.sh 8 | 9 | npm publish -------------------------------------------------------------------------------- /src/services/refactors/refactors.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /kicktravis: -------------------------------------------------------------------------------- 1 | 2017-06-19 [ci skip] Version: 1.201706190042.1+a2776648cd48d4937b076fb8b3e935d3d5fb27e1 2 | -------------------------------------------------------------------------------- /bin/tsc: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | var ts = require('./ntypescript.js'); 3 | ts.executeCommandLine(ts.sys.args); 4 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "TypeScript"] 2 | path = TypeScript 3 | url = https://github.com/Microsoft/TypeScript.git 4 | -------------------------------------------------------------------------------- /typings/tsd.d.ts: -------------------------------------------------------------------------------- 1 | 2 | /// 3 | /// 4 | -------------------------------------------------------------------------------- /tests/tse/2iwillfork.ts: -------------------------------------------------------------------------------- 1 | declare var require; 2 | var cp = require('child_process'); 3 | export function fork() { 4 | console.log('forking'); 5 | // cp.fork("./3iwilllogargs") 6 | } -------------------------------------------------------------------------------- /tests/tse/1start.ts: -------------------------------------------------------------------------------- 1 | console.log('started'); 2 | console.log(process.cwd()) 3 | console.log(require.resolve('./2iwillfork')); 4 | 5 | 6 | import iwillfork = require('./2iwillfork'); 7 | iwillfork.fork(); 8 | 9 | -------------------------------------------------------------------------------- /src/services/formatting/ruleFlag.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | 4 | /* @internal */ 5 | namespace ts.formatting { 6 | export const enum RuleFlags { 7 | None, 8 | CanDeleteNewLines 9 | } 10 | } -------------------------------------------------------------------------------- /src/services/formatting/ruleAction.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | /* @internal */ 4 | namespace ts.formatting { 5 | export const enum RuleAction { 6 | Ignore = 0x00000001, 7 | Space = 0x00000002, 8 | NewLine = 0x00000004, 9 | Delete = 0x00000008 10 | } 11 | } -------------------------------------------------------------------------------- /src/services/formatting/formattingRequestKind.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | /* @internal */ 4 | namespace ts.formatting { 5 | export const enum FormattingRequestKind { 6 | FormatDocument, 7 | FormatSelection, 8 | FormatOnEnter, 9 | FormatOnSemicolon, 10 | FormatOnClosingCurlyBrace 11 | } 12 | } -------------------------------------------------------------------------------- /tsd.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "v4", 3 | "repo": "borisyankov/DefinitelyTyped", 4 | "ref": "master", 5 | "path": "typings", 6 | "bundle": "typings/tsd.d.ts", 7 | "installed": { 8 | "node/node.d.ts": { 9 | "commit": "c7b1128cc9a8f5797bade826e7632b36b06a856c" 10 | }, 11 | "gruntjs/gruntjs.d.ts": { 12 | "commit": "c7b1128cc9a8f5797bade826e7632b36b06a856c" 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | version: 1.0.{build} 2 | os: MinGW 3 | environment: 4 | access_token: 5 | secure: keMAbmi7iJ7xgQfIIv8IWFhu2h/ghgJc43OzQ2Fr554ZPQzhohZ9/+2TA3886VCo 6 | build_script: 7 | - prepare.sh 8 | on_success: 9 | - git config --global credential.helper store 10 | - ps: Add-Content "$env:USERPROFILE\.git-credentials" "https://$($env:access_token):x-oauth-basic@github.com`n" 11 | - release.sh 12 | -------------------------------------------------------------------------------- /src/services/formatting/references.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | /// 4 | /// 5 | /// 6 | /// 7 | /// 8 | /// 9 | /// 10 | /// 11 | /// 12 | /// -------------------------------------------------------------------------------- /src/services/formatting/rule.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | /* @internal */ 4 | namespace ts.formatting { 5 | export class Rule { 6 | constructor( 7 | public Descriptor: RuleDescriptor, 8 | public Operation: RuleOperation, 9 | public Flag: RuleFlags = RuleFlags.None) { 10 | } 11 | 12 | public toString() { 13 | return "[desc=" + this.Descriptor + "," + 14 | "operation=" + this.Operation + "," + 15 | "flag=" + this.Flag + "]"; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 17 | .grunt 18 | 19 | # node-waf configuration 20 | .lock-wscript 21 | 22 | # Compiled binary addons (http://nodejs.org/api/addons.html) 23 | build/Release 24 | 25 | # Dependency directory 26 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 27 | node_modules 28 | -------------------------------------------------------------------------------- /extensions/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.5.0-beta", 3 | "compilerOptions": { 4 | "target": "es5", 5 | "module": "commonjs", 6 | "isolatedModules": false, 7 | "jsx": "react", 8 | "experimentalDecorators": true, 9 | "emitDecoratorMetadata": true, 10 | "declaration": false, 11 | "noImplicitAny": false, 12 | "removeComments": true, 13 | "noLib": false, 14 | "preserveConstEnums": true, 15 | "suppressImplicitAnyIndexErrors": true 16 | }, 17 | "filesGlob": [ 18 | "./**/*.ts", 19 | "./**/*.tsx" 20 | ], 21 | "files": [ 22 | "./addExtensions.ts", 23 | "./preBuild.ts" 24 | ] 25 | } 26 | -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | module.exports = function(grunt) { 2 | 3 | grunt.initConfig({ 4 | ntypescript: { 5 | options: { 6 | project: '.' 7 | }, 8 | default: {}, 9 | pass: { 10 | options: { 11 | project: './tests/grunt/pass' 12 | } 13 | }, 14 | fail: { 15 | options: { 16 | project: './tests/grunt/fail' 17 | } 18 | }, 19 | }, 20 | }); 21 | 22 | grunt.loadTasks('tasks'); 23 | // They would do: 24 | // grunt.loadNpmTasks('ntypescript'); 25 | 26 | grunt.registerTask('default', ['ntypescript:default']); 27 | }; -------------------------------------------------------------------------------- /src/services/codefixes/fixes.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | /// 4 | /// 5 | /// 6 | /// 7 | /// 8 | /// 9 | /// 10 | /// 11 | /// 12 | /// 13 | -------------------------------------------------------------------------------- /src/services/formatting/ruleOperation.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | /* @internal */ 4 | namespace ts.formatting { 5 | export class RuleOperation { 6 | constructor(public Context: RuleOperationContext, public Action: RuleAction) {} 7 | 8 | public toString(): string { 9 | return "[context=" + this.Context + "," + 10 | "action=" + this.Action + "]"; 11 | } 12 | 13 | static create1(action: RuleAction) { 14 | return RuleOperation.create2(RuleOperationContext.Any, action); 15 | } 16 | 17 | static create2(context: RuleOperationContext, action: RuleAction) { 18 | return new RuleOperation(context, action); 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Release 2 | 3 | ## Quickly 4 | 5 | Quick workflow (runs `prepare` and `release`): 6 | 7 | ```sh 8 | quick.sh 9 | ``` 10 | 11 | ## Manually 12 | 13 | ```sh 14 | prepare.sh 15 | ``` 16 | 17 | Manual verification here ... then: 18 | 19 | ```sh 20 | release.sh 21 | npm publish 22 | ``` 23 | 24 | ## globals 25 | 26 | You can try the globals using: 27 | 28 | ``` 29 | npm link 30 | ``` 31 | 32 | # Inspiration 33 | https://github.com/Arnavion/typescript-github 34 | 35 | # Travis 36 | * NPM deploy setup by simply running `travis setup npm` (you get `travis` from `gem install travis`). Then setup the API key using https://github.com/npm/npm/issues/8970#issuecomment-122854271 37 | * Cron job setup using https://nightli.es/ (we also tried http://traviscron.pythonanywhere.com/ but it didn't work). 38 | -------------------------------------------------------------------------------- /tests/tse/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.5.0-beta", 3 | "compilerOptions": { 4 | "target": "es5", 5 | "module": "commonjs", 6 | "isolatedModules": true, 7 | "jsx": "react", 8 | "experimentalDecorators": true, 9 | "emitDecoratorMetadata": true, 10 | "declaration": false, 11 | "noImplicitAny": false, 12 | "removeComments": true, 13 | "noLib": false, 14 | "preserveConstEnums": true, 15 | "suppressImplicitAnyIndexErrors": true 16 | }, 17 | "filesGlob": [ 18 | "./**/*.ts", 19 | "./**/*.tsx", 20 | "!./node_modules/**/*" 21 | ], 22 | "files": [ 23 | "./1start.ts", 24 | "./2iwillfork.ts", 25 | "./3iwilllogargs.ts" 26 | ], 27 | "compileOnSave": false 28 | } 29 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ntypescript", 3 | "version": "1.201706190042.1+a2776648cd48d4937b076fb8b3e935d3d5fb27e1", 4 | "description": "A nicer version of microsoft/typescript packaged and released for API developers", 5 | "main": "./bin/ntypescript.js", 6 | "bin": { 7 | "ntsc": "./bin/tsc" 8 | }, 9 | "typescript": { 10 | "definition": "./bin/ntypescript.d.ts" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/basarat/ntypescript.git" 15 | }, 16 | "keywords": [ 17 | "typescript", 18 | "gruntplugin" 19 | ], 20 | "author": "basaratali@gmail.com", 21 | "license": "MIT", 22 | "bugs": { 23 | "url": "https://github.com/basarat/ntypescript/issues" 24 | }, 25 | "homepage": "https://github.com/basarat/ntypescript#readme", 26 | "devDependencies": { 27 | "grunt": "^0.4.5" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /release.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | 4 | # Get the git commit hash 5 | typeScriptDirectory='./TypeScript' 6 | cd $typeScriptDirectory 7 | commitHash=`git rev-parse HEAD` 8 | cd .. 9 | 10 | # Version of this script 11 | toolsVersion="1" 12 | 13 | commitVersion="1.$(date +%Y%m%d%H%M).$toolsVersion+$commitHash" 14 | commitName="$(date +%Y-%m-%d) [ci skip] Version: $commitVersion" 15 | 16 | # Kick travis 17 | echo $commitName > kicktravis 18 | 19 | # Update package.json 20 | < package.json > package.json.new sed -E "s/(\s+\"version\": \")[^\"]+(\",)/\1$commitVersion\2/" 21 | mv package.json.new package.json 22 | echo "Adding to git" 23 | git add -A 24 | git checkout master 25 | git status 26 | 27 | # Commit,tag,push,publish 28 | echo "Committing" 29 | git commit -m "$commitName" 30 | git merge HEAD@{1} 31 | echo "Pushing commit" 32 | git push 33 | 34 | echo "Tagging" 35 | git tag $commitVersion 36 | echo "Pushing tags" 37 | git push --tags 38 | -------------------------------------------------------------------------------- /src/services/codefixes/fixForgottenThisPropertyAccess.ts: -------------------------------------------------------------------------------- 1 | /* @internal */ 2 | namespace ts.codefix { 3 | registerCodeFix({ 4 | errorCodes: [Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0.code], 5 | getCodeActions: (context: CodeFixContext) => { 6 | const sourceFile = context.sourceFile; 7 | const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); 8 | if (token.kind !== SyntaxKind.Identifier) { 9 | return undefined; 10 | } 11 | const changeTracker = textChanges.ChangeTracker.fromCodeFixContext(context); 12 | changeTracker.replaceNode(sourceFile, token, createPropertyAccess(createThis(), token)); 13 | 14 | return [{ 15 | description: getLocaleSpecificMessage(Diagnostics.Add_this_to_unresolved_variable), 16 | changes: changeTracker.getChanges() 17 | }]; 18 | } 19 | }); 20 | } -------------------------------------------------------------------------------- /bin/lib.es2016.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | 17 | 18 | /// 19 | 20 | 21 | /// 22 | /// -------------------------------------------------------------------------------- /bin/lib.esnext.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | 17 | 18 | /// 19 | 20 | 21 | /// 22 | /// 23 | -------------------------------------------------------------------------------- /extensions/preBuild.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Make modifications to typescript source pre build 3 | */ 4 | 5 | // Utilities 6 | declare var require, __dirname; 7 | var fs = require('fs'); 8 | var EOL: string = require('os').EOL; 9 | export function readFile(filePath: string): string { 10 | return fs.readFileSync(__dirname + '/' + filePath, 'utf8'); 11 | } 12 | export function writeFile(filePath: string, content: string) { 13 | fs.writeFileSync(__dirname + '/' + filePath, content); 14 | } 15 | 16 | 17 | var lineFixes = [{ 18 | fileName: '../src/compiler/program.ts', 19 | orig: `export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModule {`, 20 | new: `export var resolveModuleName = (moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModule => {` 21 | }]; 22 | 23 | for (let fix of lineFixes) { 24 | writeFile(fix.fileName, readFile(fix.fileName).replace(fix.orig, fix.new)); 25 | } 26 | 27 | 28 | -------------------------------------------------------------------------------- /src/services/formatting/ruleOperationContext.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | /* @internal */ 4 | namespace ts.formatting { 5 | 6 | export class RuleOperationContext { 7 | private customContextChecks: { (context: FormattingContext): boolean; }[]; 8 | 9 | constructor(...funcs: { (context: FormattingContext): boolean; }[]) { 10 | this.customContextChecks = funcs; 11 | } 12 | 13 | static Any: RuleOperationContext = new RuleOperationContext(); 14 | 15 | public IsAny(): boolean { 16 | return this === RuleOperationContext.Any; 17 | } 18 | 19 | public InContext(context: FormattingContext): boolean { 20 | if (this.IsAny()) { 21 | return true; 22 | } 23 | 24 | for (const check of this.customContextChecks) { 25 | if (!check(context)) { 26 | return false; 27 | } 28 | } 29 | return true; 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /tasks/ntypescript.js: -------------------------------------------------------------------------------- 1 | /* 2 | * ntypescript 3 | * https://github.com/basarat/ntypescript 4 | * 5 | * Copyright (c) 2015 Basarat Syed 6 | * Licensed under the MIT license. 7 | */ 8 | var path = require("path"); 9 | function gruntPlugin(grunt) { 10 | grunt.registerMultiTask('ntypescript', 'TypeScript grunt plugin', function () { 11 | var options = { 12 | project: '.', 13 | }; 14 | options = this.options(options); 15 | if (!options.project) { 16 | console.error('tsconfig must be specified using options'); 17 | return false; 18 | } 19 | var project = path.resolve(options.project); 20 | var args = [__dirname + '/../bin/tsc', '-p', project]; 21 | var done = this.async(); 22 | grunt.util.spawn({ 23 | cmd: process.execPath, 24 | args: args 25 | }, function (error, result, code) { 26 | console.log(result.stdout || result.stderr); 27 | done(!code); 28 | }); 29 | }); 30 | } 31 | ; 32 | module.exports = gruntPlugin; 33 | -------------------------------------------------------------------------------- /src/services/transform.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | namespace ts { 4 | /** 5 | * Transform one or more nodes using the supplied transformers. 6 | * @param source A single `Node` or an array of `Node` objects. 7 | * @param transformers An array of `TransformerFactory` callbacks used to process the transformation. 8 | * @param compilerOptions Optional compiler options. 9 | */ 10 | export function transform(source: T | T[], transformers: TransformerFactory[], compilerOptions?: CompilerOptions) { 11 | const diagnostics: Diagnostic[] = []; 12 | compilerOptions = fixupCompilerOptions(compilerOptions, diagnostics); 13 | const nodes = isArray(source) ? source : [source]; 14 | const result = transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsFiles*/ true); 15 | result.diagnostics = concatenate(result.diagnostics, diagnostics); 16 | return result; 17 | } 18 | } -------------------------------------------------------------------------------- /extensions/preBuild.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | var fs = require('fs'); 4 | var EOL = require('os').EOL; 5 | function readFile(filePath) { 6 | return fs.readFileSync(__dirname + '/' + filePath, 'utf8'); 7 | } 8 | exports.readFile = readFile; 9 | function writeFile(filePath, content) { 10 | fs.writeFileSync(__dirname + '/' + filePath, content); 11 | } 12 | exports.writeFile = writeFile; 13 | var lineFixes = [{ 14 | fileName: '../src/compiler/program.ts', 15 | orig: "export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModule {", 16 | new: "export var resolveModuleName = (moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModule => {" 17 | }]; 18 | for (var _i = 0, lineFixes_1 = lineFixes; _i < lineFixes_1.length; _i++) { 19 | var fix = lineFixes_1[_i]; 20 | writeFile(fix.fileName, readFile(fix.fileName).replace(fix.orig, fix.new)); 21 | } 22 | -------------------------------------------------------------------------------- /extensions/addExtensions.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | var fs = require('fs'); 4 | var EOL = require('os').EOL; 5 | function readFile(filePath) { 6 | return fs.readFileSync(__dirname + '/' + filePath, 'utf8'); 7 | } 8 | exports.readFile = readFile; 9 | function writeFile(filePath, content) { 10 | fs.writeFileSync(__dirname + '/' + filePath, content); 11 | } 12 | exports.writeFile = writeFile; 13 | var dtsOriginal = readFile('../bin/typescript.d.ts'); 14 | var jsOriginal = readFile('../bin/typescript.js'); 15 | var finalDtsLocation = '../bin/ntypescript.d.ts'; 16 | var finalJsLocation = '../bin/ntypescript.js'; 17 | var finalDtsContent = dtsOriginal; 18 | var finalJsContent = jsOriginal; 19 | finalDtsContent = finalDtsContent + EOL + "\ndeclare module \"ntypescript\" {\n export = ts;\n}\n"; 20 | finalDtsContent = finalDtsContent.replace(/const enum /g, 'enum '); 21 | finalJsContent = finalJsContent.replace(/ts.executeCommandLine\(ts\.sys\.args\);/g, ''); 22 | writeFile(finalDtsLocation, finalDtsContent); 23 | writeFile(finalJsLocation, finalJsContent); 24 | -------------------------------------------------------------------------------- /bin/lib.es2017.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | 17 | 18 | /// 19 | 20 | 21 | /// 22 | /// 23 | /// 24 | /// 25 | /// 26 | -------------------------------------------------------------------------------- /src/services/codefixes/fixConstructorForDerivedNeedSuperCall.ts: -------------------------------------------------------------------------------- 1 | /* @internal */ 2 | namespace ts.codefix { 3 | registerCodeFix({ 4 | errorCodes: [Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], 5 | getCodeActions: (context: CodeFixContext) => { 6 | const sourceFile = context.sourceFile; 7 | const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); 8 | 9 | if (token.kind !== SyntaxKind.ConstructorKeyword) { 10 | return undefined; 11 | } 12 | 13 | const changeTracker = textChanges.ChangeTracker.fromCodeFixContext(context); 14 | const superCall = createStatement(createCall(createSuper(), /*typeArguments*/ undefined, /*argumentsArray*/ emptyArray)); 15 | changeTracker.insertNodeAfter(sourceFile, getOpenBrace(token.parent, sourceFile), superCall, { suffix: context.newLineCharacter }); 16 | 17 | return [{ 18 | description: getLocaleSpecificMessage(Diagnostics.Add_missing_super_call), 19 | changes: changeTracker.getChanges() 20 | }]; 21 | } 22 | }); 23 | } -------------------------------------------------------------------------------- /tasks/ntypescript.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * ntypescript 3 | * https://github.com/basarat/ntypescript 4 | * 5 | * Copyright (c) 2015 Basarat Syed 6 | * Licensed under the MIT license. 7 | */ 8 | 9 | import * as path from "path"; 10 | 11 | function gruntPlugin(grunt) { 12 | grunt.registerMultiTask('ntypescript', 'TypeScript grunt plugin', function() { 13 | // Merge task-specific and/or target-specific options with these defaults. 14 | var options = { 15 | project: '.', 16 | }; 17 | options = this.options(options); 18 | 19 | if (!options.project) { 20 | console.error('tsconfig must be specified using options'); 21 | return false; 22 | } 23 | 24 | const project: string = path.resolve(options.project); 25 | const args = [__dirname + '/../bin/tsc', '-p', project]; 26 | // console.log(args); // Debug 27 | 28 | var done = this.async(); 29 | grunt.util.spawn({ 30 | cmd: process.execPath, 31 | args: args 32 | }, (error, result, code: number) => { 33 | console.log(result.stdout || result.stderr); 34 | done(!code); 35 | }); 36 | }); 37 | }; 38 | 39 | export = gruntPlugin; -------------------------------------------------------------------------------- /prepare.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | 4 | git submodule update --recursive --init 5 | 6 | # Official Microsoft/TypeScript clone 7 | cd ./TypeScript 8 | 9 | git clean -xfd 10 | git fetch origin 11 | git reset --hard origin/master 12 | 13 | # Fix jakefile to expose the internal APIs to service 14 | < Jakefile.js > Jakefile.new.js sed -E "s/\*stripInternal\*\/ true/\*stripInternal\*\/ false/" 15 | mv Jakefile.new.js Jakefile.js 16 | 17 | # Install jake and everything else 18 | npm install 19 | 20 | # Build once to get a new LKG 21 | ./node_modules/.bin/jake release tsc --trace 22 | cp ./built/local/* ./bin/ 23 | 24 | # Copy the source TypeScript compiler and services, but not the tsconfig.json files 25 | cp -r ./src/compiler/* ../src/compiler 26 | cp -r ./src/services/* ../src/services 27 | rm ../src/services/tsconfig.json ../src/compiler/tsconfig.json 28 | 29 | # Do pre build modifications 30 | node ../extensions/preBuild.js 31 | 32 | # Now build using the LKG 33 | ./bin/tsc -p ../src 34 | ./bin/tsc -p ../extensions 35 | 36 | # Also copy the lib.* stuff from LKG 37 | cp ./bin/lib* ../bin 38 | 39 | # add custom extension 40 | node ../extensions/addExtensions.js 41 | 42 | # Reset sub typescript 43 | git reset --hard origin/master 44 | cd .. 45 | -------------------------------------------------------------------------------- /src/services/formatting/ruleDescriptor.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | /* @internal */ 4 | namespace ts.formatting { 5 | export class RuleDescriptor { 6 | constructor(public LeftTokenRange: Shared.TokenRange, public RightTokenRange: Shared.TokenRange) { 7 | } 8 | 9 | public toString(): string { 10 | return "[leftRange=" + this.LeftTokenRange + "," + 11 | "rightRange=" + this.RightTokenRange + "]"; 12 | } 13 | 14 | static create1(left: SyntaxKind, right: SyntaxKind): RuleDescriptor { 15 | return RuleDescriptor.create4(Shared.TokenRange.FromToken(left), Shared.TokenRange.FromToken(right)); 16 | } 17 | 18 | static create2(left: Shared.TokenRange, right: SyntaxKind): RuleDescriptor { 19 | return RuleDescriptor.create4(left, Shared.TokenRange.FromToken(right)); 20 | } 21 | 22 | static create3(left: SyntaxKind, right: Shared.TokenRange): RuleDescriptor { 23 | return RuleDescriptor.create4(Shared.TokenRange.FromToken(left), right); 24 | } 25 | 26 | static create4(left: Shared.TokenRange, right: Shared.TokenRange): RuleDescriptor { 27 | return new RuleDescriptor(left, right); 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /bin/lib.es2017.intl.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | 17 | 18 | /// 19 | 20 | 21 | type DateTimeFormatPartTypes = "day" | "dayPeriod" | "era" | "hour" | "literal" | "minute" | "month" | "second" | "timeZoneName" | "weekday" | "year"; 22 | 23 | interface DateTimeFormatPart { 24 | type: DateTimeFormatPartTypes; 25 | value: string; 26 | } 27 | 28 | interface DateTimeFormat { 29 | formatToParts(date?: Date | number): DateTimeFormatPart[]; 30 | } 31 | -------------------------------------------------------------------------------- /src/extensions.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Sample: add a new utility function 3 | */ 4 | module ts { 5 | export function syntaxKindToName(kind: ts.SyntaxKind): string { 6 | return (ts).SyntaxKind[kind]; 7 | } 8 | 9 | /** 10 | * Pulled straight out of `tsc.ts`. Ask to make it exported 11 | */ 12 | export function reportDiagnostic(diagnostic: Diagnostic) { 13 | let output = ""; 14 | 15 | if (diagnostic.file) { 16 | let loc = getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); 17 | 18 | output += `${ diagnostic.file.fileName }(${ loc.line + 1 },${ loc.character + 1 }): `; 19 | } 20 | 21 | let category = DiagnosticCategory[diagnostic.category].toLowerCase(); 22 | output += `${ category } TS${ diagnostic.code }: ${ flattenDiagnosticMessageText(diagnostic.messageText, sys.newLine) }${ sys.newLine }`; 23 | 24 | sys.write(output); 25 | } 26 | } 27 | 28 | /** 29 | * Make ts a global variable (this means we have a consistent typescript definition file) 30 | */ 31 | declare module NodeJS { 32 | export interface Global { 33 | } 34 | } 35 | declare var global: NodeJS.Global; 36 | if (typeof global !== "undefined") { 37 | (global as any).ts = ts; 38 | } 39 | if (typeof window !== "undefined") { 40 | (window as any).ts = ts; 41 | } 42 | -------------------------------------------------------------------------------- /src/services/formatting/rulesProvider.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | /* @internal */ 4 | namespace ts.formatting { 5 | export class RulesProvider { 6 | private globalRules: Rules; 7 | private options: ts.FormatCodeSettings; 8 | private rulesMap: RulesMap; 9 | 10 | constructor() { 11 | this.globalRules = new Rules(); 12 | const activeRules = this.globalRules.HighPriorityCommonRules.slice(0).concat(this.globalRules.UserConfigurableRules).concat(this.globalRules.LowPriorityCommonRules); 13 | this.rulesMap = RulesMap.create(activeRules); 14 | } 15 | 16 | public getRuleName(rule: Rule): string { 17 | return this.globalRules.getRuleName(rule); 18 | } 19 | 20 | public getRuleByName(name: string): Rule { 21 | return this.globalRules[name]; 22 | } 23 | 24 | public getRulesMap() { 25 | return this.rulesMap; 26 | } 27 | 28 | public getFormatOptions(): Readonly { 29 | return this.options; 30 | } 31 | 32 | public ensureUpToDate(options: ts.FormatCodeSettings) { 33 | if (!this.options || !ts.compareDataObjects(this.options, options)) { 34 | this.options = ts.clone(options); 35 | } 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /bin/lib.es2015.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | 17 | 18 | /// 19 | 20 | 21 | /// 22 | /// 23 | /// 24 | /// 25 | /// 26 | /// 27 | /// 28 | /// 29 | /// 30 | /// -------------------------------------------------------------------------------- /register.js: -------------------------------------------------------------------------------- 1 | /// 2 | var t = require('./bin/typescript.js'); 3 | var fileExtension = ['.ts', '.tsx']; 4 | exports.isTypeScript = function (file) { 5 | var r = new RegExp("\\.(" + fileExtension.join("|") + ")$"); 6 | return r.test(file); 7 | }; 8 | var fs = require('fs'); 9 | function loadFile(module, filename) { 10 | var configFile = t.findConfigFile(filename); 11 | var compilerOpts = { 12 | module: 1, 13 | target: 1 14 | }; 15 | if (configFile) { 16 | var configFileContents = t.readConfigFile(configFile); 17 | var opts = configFileContents.config; 18 | opts.files = []; 19 | compilerOpts = t.parseConfigFile(opts, null, process.cwd()).options; 20 | } 21 | var js = t.transpile(fs.readFileSync(filename, 'utf8'), compilerOpts); 22 | module._compile(js, filename); 23 | } 24 | exports.loadFile = loadFile; 25 | if (require.extensions) { 26 | for (var _i = 0; _i < fileExtension.length; _i++) { 27 | var ext = fileExtension[_i]; 28 | require.extensions[ext] = loadFile; 29 | } 30 | } 31 | var child_process = require('child_process'); 32 | if (child_process) { 33 | var fork = child_process.fork; 34 | var binary = require.resolve('./bin/tse'); 35 | child_process.fork = function (path, args, options) { 36 | if (exports.isTypeScript(path)) { 37 | if (!Array.isArray(args)) { 38 | options = args || {}; 39 | args = []; 40 | } 41 | args = [path].concat(args); 42 | path = binary; 43 | } 44 | fork(path, args, options); 45 | }; 46 | } 47 | -------------------------------------------------------------------------------- /extensions/addExtensions.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This script is responsible for making required modifications to our version of TypeScript post build 3 | */ 4 | 5 | // Utilities 6 | declare var require, __dirname; 7 | var fs = require('fs'); 8 | var EOL: string = require('os').EOL; 9 | export function readFile(filePath: string): string { 10 | return fs.readFileSync(__dirname + '/' + filePath, 'utf8'); 11 | } 12 | export function writeFile(filePath: string, content: string) { 13 | fs.writeFileSync(__dirname + '/' + filePath, content); 14 | } 15 | 16 | // Read original files 17 | var dtsOriginal = readFile('../bin/typescript.d.ts'); 18 | var jsOriginal = readFile('../bin/typescript.js'); 19 | 20 | // Setup final output destinations 21 | var finalDtsLocation = '../bin/ntypescript.d.ts'; 22 | var finalJsLocation = '../bin/ntypescript.js'; 23 | 24 | // Setup final output 25 | var finalDtsContent = dtsOriginal; 26 | var finalJsContent = jsOriginal; 27 | 28 | /** 29 | * Transform as needed 30 | */ 31 | 32 | // Add global import 33 | finalDtsContent = finalDtsContent + EOL + ` 34 | declare module "ntypescript" { 35 | export = ts; 36 | } 37 | `; 38 | // I think the `const enum` causes more pain than its worth for dev tools (everything needs to be rebuilt). So change to enum to prevent inlining 39 | finalDtsContent = finalDtsContent.replace(/const enum /g, 'enum '); 40 | 41 | // No need for `ts.executeCommandLine(ts.sys.args);` in ntypescript. Its called from `tsc` manually 42 | finalJsContent = finalJsContent.replace(/ts.executeCommandLine\(ts\.sys\.args\);/g, ''); 43 | 44 | /** 45 | * Write out outputs 46 | */ 47 | writeFile(finalDtsLocation, finalDtsContent); 48 | writeFile(finalJsLocation, finalJsContent); 49 | -------------------------------------------------------------------------------- /bin/lib.esnext.asynciterable.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | 17 | 18 | /// 19 | 20 | 21 | /// 22 | /// 23 | 24 | interface SymbolConstructor { 25 | /** 26 | * A method that returns the default async iterator for an object. Called by the semantics of 27 | * the for-await-of statement. 28 | */ 29 | readonly asyncIterator: symbol; 30 | } 31 | 32 | interface AsyncIterator { 33 | next(value?: any): Promise>; 34 | return?(value?: any): Promise>; 35 | throw?(e?: any): Promise>; 36 | } 37 | 38 | interface AsyncIterable { 39 | [Symbol.asyncIterator](): AsyncIterator; 40 | } 41 | 42 | interface AsyncIterableIterator extends AsyncIterator { 43 | [Symbol.asyncIterator](): AsyncIterableIterator; 44 | } -------------------------------------------------------------------------------- /src/services/codeFixProvider.ts: -------------------------------------------------------------------------------- 1 | /* @internal */ 2 | namespace ts { 3 | export interface CodeFix { 4 | errorCodes: number[]; 5 | getCodeActions(context: CodeFixContext): CodeAction[] | undefined; 6 | } 7 | 8 | export interface CodeFixContext { 9 | errorCode: number; 10 | sourceFile: SourceFile; 11 | span: TextSpan; 12 | program: Program; 13 | newLineCharacter: string; 14 | host: LanguageServiceHost; 15 | cancellationToken: CancellationToken; 16 | rulesProvider: formatting.RulesProvider; 17 | } 18 | 19 | export namespace codefix { 20 | const codeFixes: CodeFix[][] = []; 21 | 22 | export function registerCodeFix(codeFix: CodeFix) { 23 | forEach(codeFix.errorCodes, error => { 24 | let fixes = codeFixes[error]; 25 | if (!fixes) { 26 | fixes = []; 27 | codeFixes[error] = fixes; 28 | } 29 | fixes.push(codeFix); 30 | }); 31 | } 32 | 33 | export function getSupportedErrorCodes() { 34 | return Object.keys(codeFixes); 35 | } 36 | 37 | export function getFixes(context: CodeFixContext): CodeAction[] { 38 | const fixes = codeFixes[context.errorCode]; 39 | let allActions: CodeAction[] = []; 40 | 41 | forEach(fixes, f => { 42 | const actions = f.getCodeActions(context); 43 | if (actions && actions.length > 0) { 44 | allActions = allActions.concat(actions); 45 | } 46 | }); 47 | 48 | return allActions; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/services/goToImplementation.ts: -------------------------------------------------------------------------------- 1 | /* @internal */ 2 | namespace ts.GoToImplementation { 3 | export function getImplementationAtPosition(typeChecker: TypeChecker, cancellationToken: CancellationToken, sourceFiles: SourceFile[], node: Node): ImplementationLocation[] { 4 | // If invoked directly on a shorthand property assignment, then return 5 | // the declaration of the symbol being assigned (not the symbol being assigned to). 6 | if (node.parent.kind === SyntaxKind.ShorthandPropertyAssignment) { 7 | const result: ReferenceEntry[] = []; 8 | FindAllReferences.getReferenceEntriesForShorthandPropertyAssignment(node, typeChecker, result); 9 | return result.length > 0 ? result : undefined; 10 | } 11 | else if (node.kind === SyntaxKind.SuperKeyword || isSuperProperty(node.parent)) { 12 | // References to and accesses on the super keyword only have one possible implementation, so no 13 | // need to "Find all References" 14 | const symbol = typeChecker.getSymbolAtLocation(node); 15 | return symbol.valueDeclaration && [FindAllReferences.getReferenceEntryFromNode(symbol.valueDeclaration)]; 16 | } 17 | else { 18 | // Perform "Find all References" and retrieve only those that are implementations 19 | const referencedSymbols = FindAllReferences.getReferencedSymbolsForNode(typeChecker, cancellationToken, 20 | node, sourceFiles, /*findInStrings*/false, /*findInComments*/false, /*implementations*/true); 21 | const result = flatMap(referencedSymbols, symbol => 22 | map(symbol.references, ({ textSpan, fileName }) => ({ textSpan, fileName }))); 23 | 24 | return result && result.length > 0 ? result : undefined; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /register.ts: -------------------------------------------------------------------------------- 1 | /// 2 | var t: typeof ts = require('./bin/typescript.js'); 3 | 4 | /** Determine if a filename represents a TypeScript file. */ 5 | var fileExtension = ['.ts', '.tsx']; 6 | export var isTypeScript = (file) => { 7 | let r = new RegExp("\\.("+fileExtension.join("|") +")$"); 8 | return r.test(file); 9 | } 10 | 11 | /** Load and runt TypeScript for Node */ 12 | import fs = require('fs'); 13 | export function loadFile(module, filename) { 14 | var configFile = t.findConfigFile(filename); 15 | var compilerOpts = { 16 | module: t.ModuleKind.CommonJS, 17 | target: t.ScriptTarget.ES5 18 | }; 19 | if (configFile) { 20 | var configFileContents = t.readConfigFile(configFile); 21 | var opts = configFileContents.config; 22 | opts.files = []; 23 | compilerOpts = t.parseConfigFile(opts, null, process.cwd()).options; 24 | } 25 | var js = t.transpile(fs.readFileSync(filename,'utf8'), compilerOpts); 26 | module._compile(js, filename); 27 | } 28 | 29 | /** If the installed version of Node supports require.extensions, register TypeScript as an extension. */ 30 | if (require.extensions) { 31 | for (var ext of fileExtension) { 32 | require.extensions[ext] = loadFile; 33 | } 34 | } 35 | 36 | /** If we’re on Node, patch child_process.fork so that TypeScript is able to fork both TypeScript files, and JavaScript files, directly. */ 37 | import child_process = require('child_process'); 38 | if (child_process) { 39 | var {fork} = child_process; 40 | var binary = require.resolve('./bin/tse'); 41 | child_process.fork = function(path, args?, options?) { 42 | if (isTypeScript(path)) { 43 | if (!Array.isArray(args)) { 44 | options = args || {} 45 | args = [] 46 | } 47 | args = [path].concat(args) 48 | path = binary 49 | } 50 | fork(path, args, options) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /bin/lib.es2015.reflect.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | 17 | 18 | /// 19 | 20 | 21 | declare namespace Reflect { 22 | function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; 23 | function construct(target: Function, argumentsList: ArrayLike, newTarget?: any): any; 24 | function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean; 25 | function deleteProperty(target: object, propertyKey: PropertyKey): boolean; 26 | function get(target: object, propertyKey: PropertyKey, receiver?: any): any; 27 | function getOwnPropertyDescriptor(target: object, propertyKey: PropertyKey): PropertyDescriptor; 28 | function getPrototypeOf(target: object): object; 29 | function has(target: object, propertyKey: PropertyKey): boolean; 30 | function isExtensible(target: object): boolean; 31 | function ownKeys(target: object): Array; 32 | function preventExtensions(target: object): boolean; 33 | function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; 34 | function setPrototypeOf(target: object, proto: any): boolean; 35 | } 36 | -------------------------------------------------------------------------------- /src/services/codefixes/fixExtendsInterfaceBecomesImplements.ts: -------------------------------------------------------------------------------- 1 | /* @internal */ 2 | namespace ts.codefix { 3 | registerCodeFix({ 4 | errorCodes: [Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements.code], 5 | getCodeActions: (context: CodeFixContext) => { 6 | const sourceFile = context.sourceFile; 7 | const start = context.span.start; 8 | const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); 9 | const classDeclNode = getContainingClass(token); 10 | if (!(token.kind === SyntaxKind.Identifier && isClassLike(classDeclNode))) { 11 | return undefined; 12 | } 13 | 14 | const heritageClauses = classDeclNode.heritageClauses; 15 | if (!(heritageClauses && heritageClauses.length > 0)) { 16 | return undefined; 17 | } 18 | 19 | const extendsToken = heritageClauses[0].getFirstToken(); 20 | if (!(extendsToken && extendsToken.kind === SyntaxKind.ExtendsKeyword)) { 21 | return undefined; 22 | } 23 | 24 | const changeTracker = textChanges.ChangeTracker.fromCodeFixContext(context); 25 | changeTracker.replaceNode(sourceFile, extendsToken, createToken(SyntaxKind.ImplementsKeyword)); 26 | 27 | // We replace existing keywords with commas. 28 | for (let i = 1; i < heritageClauses.length; i++) { 29 | const keywordToken = heritageClauses[i].getFirstToken(); 30 | if (keywordToken) { 31 | changeTracker.replaceNode(sourceFile, keywordToken, createToken(SyntaxKind.CommaToken)); 32 | } 33 | } 34 | 35 | const result = [{ 36 | description: getLocaleSpecificMessage(Diagnostics.Change_extends_to_implements), 37 | changes: changeTracker.getChanges() 38 | }]; 39 | 40 | return result; 41 | } 42 | }); 43 | } 44 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - 5 4 | env: 5 | global: 6 | - secure: WXkeUKwWKTv2uUCyIiDdQ0e5gQCoX9gGj6wiNh9G7IATqcecxTw6cpQGj3J8YWDIjbtNXfAkJwohhGtXYr7VnkXRA1s0POYM+8cvM5I+ZDtZkXM9EvCwMYxf9XZ8qQ/4fegeSoZqfx1qgh+Sfh6Wp93I4W+AfB8VONLIGgXr172QGwYmkynPpC//mYA6sUZoQo4Y796PtBblc+7oM0a5A5chQ5r1CVqPqRZ/i9aNrH2UTdYjCMNE395LqwHSJGk5eunT5ebA4OcClme1wL78MJtGS1ZZIOEHSBv7mBrOcp29kYknc/m1PaOYBMdppmRBLr6Q5oUg8QzaILW2TypsWkosWpSlbemW1lsutqlFRkmtsjfX3ZVOoeIx/7J9v+pDA2gb7VMtNzwlkRpcLfHBmfuXuiPNXwLS1Ogl2D8JUD+rjwB3FI6pE2zZqNL7zMe7yhCQ/1wqGdlNqB1Ifb9T2RRkDCEUr+dw3sGn6Ecgk4XThUwY3vVzABj0C906Wc7UpsVvf1qjLCRg48lYG8kmhLqEylL+IUs3XXMSv69/YLxnDvRdF/d1FZHWKcoTeWYmXr3k1q0ePYEDXpX6/8MXWix1Qql4AAOjIxOgRufBPlDWe6QS2b97K4OPo+m3cf/RaLPz+jUOpf59l6CNnceBYLKs00Taf0KSgs+YVADAV6M= 7 | before_script: 8 | - git config --global user.email "basaratali@gmail.com" 9 | - git config --global user.name "Travis-CI" 10 | - git remote set-url origin https://github.com/TypeStrong/ntypescript.git 11 | script: 12 | - bash prepare.sh 13 | after_success: 14 | - git config credential.helper "store --file=.git/credentials" 15 | - echo "https://${GH_TOKEN}:@github.com" > .git/credentials 16 | - git config --global push.default matching 17 | - bash release.sh 18 | branches: 19 | only: 20 | - master 21 | deploy: 22 | provider: npm 23 | email: basaratali@gmail.com 24 | api_key: 25 | secure: s/KSMaTnT6JdVOmaw5n3KnA5piUjxopXjOEH/k2uTph2zY7XVvGw83UX797IUDNTRKAX1OrgfaB+VQ+bT1Tf7KAqOgy1MtvS/lFJMMmRO5U1HI8Dj5NXWQ87GFHO1/iDZgVxRju/kkjxG/WkBfkJCex0B2smqC0HFWZKBOWlBLgjJGHs+gZV02CzWQc72kZ9PRTxbeh5Lid2D7NXAY1BfFKHyvAlibd+3sZTdjfeVQzyGg94I6pNQOpr1O0MzKv7ttZ+7iEN2cLoH9t/2927LdR1lIlyl7ArE/UY5ob4W9PpwXYXjb4O1j7vvo/S33bgXzKy1cwL1udoe5B9MvUoU8Qg64ffqyD+RRhj2ZgnnXhYIovDwOEYFbRSMgaYgoI54ThpyQXZbvwxuqWxMh5rSeUGzi5Ah36Z6zqfSYo5J7XC+mXUiqBfIXNjOpbw43rASLiM25/rMvXVDlEeDh1rgpIKDu2DVuX0Zyw4apNu+7cjlFfZ0iQwVAN5xzzJ2DOgPNosjbWe5g4RR5t2bBq9CxDYxQPNB7x1GhUk82qlij23ssoLfvNyYuLaoILuCyDly1FLHr1U6Q9VBOKvLR7qqjn0F7ZpEi8RKbNgpqNWf7ExXDOcNuoHHuHJWvKMDfj8xlkV9PeWFkCiYtm6xr1DQd/6HUkN+uh/d8SjNkgJlPM= 26 | on: 27 | repo: TypeStrong/ntypescript 28 | -------------------------------------------------------------------------------- /bin/lib.es2015.symbol.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | 17 | 18 | /// 19 | 20 | 21 | interface Symbol { 22 | /** Returns a string representation of an object. */ 23 | toString(): string; 24 | 25 | /** Returns the primitive value of the specified object. */ 26 | valueOf(): symbol; 27 | } 28 | 29 | interface SymbolConstructor { 30 | /** 31 | * A reference to the prototype. 32 | */ 33 | readonly prototype: Symbol; 34 | 35 | /** 36 | * Returns a new unique Symbol value. 37 | * @param description Description of the new Symbol object. 38 | */ 39 | (description?: string | number): symbol; 40 | 41 | /** 42 | * Returns a Symbol object from the global symbol registry matching the given key if found. 43 | * Otherwise, returns a new symbol with this key. 44 | * @param key key to search for. 45 | */ 46 | for(key: string): symbol; 47 | 48 | /** 49 | * Returns a key from the global symbol registry matching the given Symbol if found. 50 | * Otherwise, returns a undefined. 51 | * @param sym Symbol to find the key for. 52 | */ 53 | keyFor(sym: symbol): string | undefined; 54 | } 55 | 56 | declare var Symbol: SymbolConstructor; -------------------------------------------------------------------------------- /bin/lib.es2015.proxy.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | 17 | 18 | /// 19 | 20 | 21 | interface ProxyHandler { 22 | getPrototypeOf? (target: T): object | null; 23 | setPrototypeOf? (target: T, v: any): boolean; 24 | isExtensible? (target: T): boolean; 25 | preventExtensions? (target: T): boolean; 26 | getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor | undefined; 27 | has? (target: T, p: PropertyKey): boolean; 28 | get? (target: T, p: PropertyKey, receiver: any): any; 29 | set? (target: T, p: PropertyKey, value: any, receiver: any): boolean; 30 | deleteProperty? (target: T, p: PropertyKey): boolean; 31 | defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean; 32 | enumerate? (target: T): PropertyKey[]; 33 | ownKeys? (target: T): PropertyKey[]; 34 | apply? (target: T, thisArg: any, argArray?: any): any; 35 | construct? (target: T, argArray: any, newTarget?: any): object; 36 | } 37 | 38 | interface ProxyConstructor { 39 | revocable(target: T, handler: ProxyHandler): { proxy: T; revoke: () => void; }; 40 | new (target: T, handler: ProxyHandler): T; 41 | } 42 | declare var Proxy: ProxyConstructor; 43 | -------------------------------------------------------------------------------- /bin/lib.es2017.object.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | 17 | 18 | /// 19 | 20 | 21 | interface ObjectConstructor { 22 | /** 23 | * Returns an array of values of the enumerable properties of an object 24 | * @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. 25 | */ 26 | values(o: { [s: string]: T }): T[]; 27 | 28 | /** 29 | * Returns an array of values of the enumerable properties of an object 30 | * @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. 31 | */ 32 | values(o: any): any[]; 33 | 34 | /** 35 | * Returns an array of key/values of the enumerable properties of an object 36 | * @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. 37 | */ 38 | entries(o: { [s: string]: T }): [string, T][]; 39 | 40 | /** 41 | * Returns an array of key/values of the enumerable properties of an object 42 | * @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. 43 | */ 44 | entries(o: any): [string, any][]; 45 | } 46 | -------------------------------------------------------------------------------- /src/services/codefixes/fixSpelling.ts: -------------------------------------------------------------------------------- 1 | /* @internal */ 2 | namespace ts.codefix { 3 | registerCodeFix({ 4 | errorCodes: [Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2.code, 5 | Diagnostics.Cannot_find_name_0_Did_you_mean_1.code], 6 | getCodeActions: getActionsForCorrectSpelling 7 | }); 8 | 9 | function getActionsForCorrectSpelling(context: CodeFixContext): CodeAction[] | undefined { 10 | const sourceFile = context.sourceFile; 11 | 12 | // This is the identifier of the misspelled word. eg: 13 | // this.speling = 1; 14 | // ^^^^^^^ 15 | const node = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); // TODO: GH#15852 16 | const checker = context.program.getTypeChecker(); 17 | let suggestion: string; 18 | if (node.kind === SyntaxKind.Identifier && isPropertyAccessExpression(node.parent)) { 19 | const containingType = checker.getTypeAtLocation(node.parent.expression); 20 | suggestion = checker.getSuggestionForNonexistentProperty(node as Identifier, containingType); 21 | } 22 | else { 23 | const meaning = getMeaningFromLocation(node); 24 | suggestion = checker.getSuggestionForNonexistentSymbol(node, getTextOfNode(node), convertSemanticMeaningToSymbolFlags(meaning)); 25 | } 26 | if (suggestion) { 27 | return [{ 28 | description: formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Change_spelling_to_0), [suggestion]), 29 | changes: [{ 30 | fileName: sourceFile.fileName, 31 | textChanges: [{ 32 | span: { start: node.getStart(), length: node.getWidth() }, 33 | newText: suggestion 34 | }], 35 | }], 36 | }]; 37 | } 38 | } 39 | 40 | function convertSemanticMeaningToSymbolFlags(meaning: SemanticMeaning): SymbolFlags { 41 | let flags = 0; 42 | if (meaning & SemanticMeaning.Namespace) { 43 | flags |= SymbolFlags.Namespace; 44 | } 45 | if (meaning & SemanticMeaning.Type) { 46 | flags |= SymbolFlags.Type; 47 | } 48 | if (meaning & SemanticMeaning.Value) { 49 | flags |= SymbolFlags.Value; 50 | } 51 | return flags; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.5.3", 3 | "compilerOptions": { 4 | "target": "es5", 5 | "isolatedModules": false, 6 | "jsx": "react", 7 | "experimentalDecorators": true, 8 | "emitDecoratorMetadata": true, 9 | "declaration": true, 10 | "noImplicitAny": false, 11 | "removeComments": false, 12 | "noLib": false, 13 | "preserveConstEnums": true, 14 | "suppressImplicitAnyIndexErrors": true, 15 | "out": "../bin/typescript.js" 16 | }, 17 | "scripts": { 18 | "postbuild" : "node ../extensions/addExtensions.js" 19 | }, 20 | "buildOnSave": true, 21 | "files": [ 22 | "./compiler/parser.ts", 23 | "./compiler/binder.ts", 24 | "./compiler/checker.ts", 25 | "./compiler/commandLineParser.ts", 26 | "./compiler/core.ts", 27 | "./compiler/sys.ts", 28 | "./compiler/declarationEmitter.ts", 29 | "./compiler/diagnosticInformationMap.generated.ts", 30 | "./compiler/emitter.ts", 31 | "./compiler/program.ts", 32 | "./compiler/scanner.ts", 33 | "./compiler/tsc.ts", 34 | "./compiler/types.ts", 35 | "./compiler/utilities.ts", 36 | "./services/breakpoints.ts", 37 | "./services/formatting/formatting.ts", 38 | "./services/formatting/formattingContext.ts", 39 | "./services/formatting/formattingRequestKind.ts", 40 | "./services/formatting/formattingScanner.ts", 41 | "./services/formatting/references.ts", 42 | "./services/formatting/rule.ts", 43 | "./services/formatting/ruleAction.ts", 44 | "./services/formatting/ruleDescriptor.ts", 45 | "./services/formatting/ruleFlag.ts", 46 | "./services/formatting/ruleOperation.ts", 47 | "./services/formatting/ruleOperationContext.ts", 48 | "./services/formatting/rules.ts", 49 | "./services/formatting/rulesMap.ts", 50 | "./services/formatting/rulesProvider.ts", 51 | "./services/formatting/smartIndenter.ts", 52 | "./services/formatting/tokenRange.ts", 53 | "./services/navigateTo.ts", 54 | "./services/navigationBar.ts", 55 | "./services/outliningElementsCollector.ts", 56 | "./services/patternMatcher.ts", 57 | "./services/services.ts", 58 | "./services/shims.ts", 59 | "./services/signatureHelp.ts", 60 | "./services/utilities.ts", 61 | "./extensions.ts" 62 | ] 63 | } 64 | -------------------------------------------------------------------------------- /bin/lib.es2015.generator.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | 17 | 18 | /// 19 | 20 | 21 | interface Generator extends Iterator { } 22 | 23 | interface GeneratorFunction { 24 | /** 25 | * Creates a new Generator object. 26 | * @param args A list of arguments the function accepts. 27 | */ 28 | new (...args: any[]): Generator; 29 | /** 30 | * Creates a new Generator object. 31 | * @param args A list of arguments the function accepts. 32 | */ 33 | (...args: any[]): Generator; 34 | /** 35 | * The length of the arguments. 36 | */ 37 | readonly length: number; 38 | /** 39 | * Returns the name of the function. 40 | */ 41 | readonly name: string; 42 | /** 43 | * A reference to the prototype. 44 | */ 45 | readonly prototype: Generator; 46 | } 47 | 48 | interface GeneratorFunctionConstructor { 49 | /** 50 | * Creates a new Generator function. 51 | * @param args A list of arguments the function accepts. 52 | */ 53 | new (...args: string[]): GeneratorFunction; 54 | /** 55 | * Creates a new Generator function. 56 | * @param args A list of arguments the function accepts. 57 | */ 58 | (...args: string[]): GeneratorFunction; 59 | /** 60 | * The length of the arguments. 61 | */ 62 | readonly length: number; 63 | /** 64 | * Returns the name of the function. 65 | */ 66 | readonly name: string; 67 | /** 68 | * A reference to the prototype. 69 | */ 70 | readonly prototype: GeneratorFunction; 71 | } 72 | declare var GeneratorFunction: GeneratorFunctionConstructor; 73 | -------------------------------------------------------------------------------- /src/services/codefixes/fixClassSuperMustPrecedeThisAccess.ts: -------------------------------------------------------------------------------- 1 | /* @internal */ 2 | namespace ts.codefix { 3 | registerCodeFix({ 4 | errorCodes: [Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], 5 | getCodeActions: (context: CodeFixContext) => { 6 | const sourceFile = context.sourceFile; 7 | 8 | const token = getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false); 9 | if (token.kind !== SyntaxKind.ThisKeyword) { 10 | return undefined; 11 | } 12 | 13 | const constructor = getContainingFunction(token); 14 | const superCall = findSuperCall((constructor).body); 15 | if (!superCall) { 16 | return undefined; 17 | } 18 | 19 | // figure out if the `this` access is actually inside the supercall 20 | // i.e. super(this.a), since in that case we won't suggest a fix 21 | if (superCall.expression && superCall.expression.kind === SyntaxKind.CallExpression) { 22 | const arguments = (superCall.expression).arguments; 23 | for (let i = 0; i < arguments.length; i++) { 24 | if ((arguments[i]).expression === token) { 25 | return undefined; 26 | } 27 | } 28 | } 29 | const changeTracker = textChanges.ChangeTracker.fromCodeFixContext(context); 30 | changeTracker.insertNodeAfter(sourceFile, getOpenBrace(constructor, sourceFile), superCall, { suffix: context.newLineCharacter }); 31 | changeTracker.deleteNode(sourceFile, superCall); 32 | 33 | return [{ 34 | description: getLocaleSpecificMessage(Diagnostics.Make_super_call_the_first_statement_in_the_constructor), 35 | changes: changeTracker.getChanges() 36 | }]; 37 | 38 | function findSuperCall(n: Node): ExpressionStatement { 39 | if (n.kind === SyntaxKind.ExpressionStatement && isSuperCall((n).expression)) { 40 | return n; 41 | } 42 | if (isFunctionLike(n)) { 43 | return undefined; 44 | } 45 | return forEachChild(n, findSuperCall); 46 | } 47 | } 48 | }); 49 | } -------------------------------------------------------------------------------- /bin/lib.es2017.string.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | 17 | 18 | /// 19 | 20 | 21 | interface String { 22 | /** 23 | * Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. 24 | * The padding is applied from the start (left) of the current string. 25 | * 26 | * @param maxLength The length of the resulting string once the current string has been padded. 27 | * If this parameter is smaller than the current string's length, the current string will be returned as it is. 28 | * 29 | * @param fillString The string to pad the current string with. 30 | * If this string is too long, it will be truncated and the left-most part will be applied. 31 | * The default value for this parameter is " " (U+0020). 32 | */ 33 | padStart(maxLength: number, fillString?: string): string; 34 | 35 | /** 36 | * Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. 37 | * The padding is applied from the end (right) of the current string. 38 | * 39 | * @param maxLength The length of the resulting string once the current string has been padded. 40 | * If this parameter is smaller than the current string's length, the current string will be returned as it is. 41 | * 42 | * @param fillString The string to pad the current string with. 43 | * If this string is too long, it will be truncated and the left-most part will be applied. 44 | * The default value for this parameter is " " (U+0020). 45 | */ 46 | padEnd(maxLength: number, fillString?: string): string; 47 | } 48 | -------------------------------------------------------------------------------- /src/services/refactorProvider.ts: -------------------------------------------------------------------------------- 1 | /* @internal */ 2 | namespace ts { 3 | export interface Refactor { 4 | /** An unique code associated with each refactor */ 5 | name: string; 6 | 7 | /** Description of the refactor to display in the UI of the editor */ 8 | description: string; 9 | 10 | /** Compute the associated code actions */ 11 | getEditsForAction(context: RefactorContext, actionName: string): RefactorEditInfo | undefined; 12 | 13 | /** Compute (quickly) which actions are available here */ 14 | getAvailableActions(context: RefactorContext): ApplicableRefactorInfo[] | undefined; 15 | } 16 | 17 | export interface RefactorContext { 18 | file: SourceFile; 19 | startPosition: number; 20 | endPosition?: number; 21 | program: Program; 22 | newLineCharacter: string; 23 | rulesProvider?: formatting.RulesProvider; 24 | cancellationToken?: CancellationToken; 25 | } 26 | 27 | export namespace refactor { 28 | // A map with the refactor code as key, the refactor itself as value 29 | // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want 30 | const refactors: Map = createMap(); 31 | 32 | export function registerRefactor(refactor: Refactor) { 33 | refactors.set(refactor.name, refactor); 34 | } 35 | 36 | export function getApplicableRefactors(context: RefactorContext): ApplicableRefactorInfo[] | undefined { 37 | let results: ApplicableRefactorInfo[]; 38 | const refactorList: Refactor[] = []; 39 | refactors.forEach(refactor => { 40 | refactorList.push(refactor); 41 | }); 42 | for (const refactor of refactorList) { 43 | if (context.cancellationToken && context.cancellationToken.isCancellationRequested()) { 44 | return results; 45 | } 46 | const infos = refactor.getAvailableActions(context); 47 | if (infos && infos.length) { 48 | (results || (results = [])).push(...infos); 49 | } 50 | } 51 | return results; 52 | } 53 | 54 | export function getEditsForRefactor(context: RefactorContext, refactorName: string, actionName: string): RefactorEditInfo | undefined { 55 | const refactor = refactors.get(refactorName); 56 | return refactor && refactor.getEditsForAction(context, actionName); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/services/codefixes/fixClassDoesntImplementInheritedAbstractMember.ts: -------------------------------------------------------------------------------- 1 | /* @internal */ 2 | namespace ts.codefix { 3 | registerCodeFix({ 4 | errorCodes: [Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2.code], 5 | getCodeActions: getActionForClassLikeMissingAbstractMember 6 | }); 7 | 8 | registerCodeFix({ 9 | errorCodes: [Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1.code], 10 | getCodeActions: getActionForClassLikeMissingAbstractMember 11 | }); 12 | 13 | function getActionForClassLikeMissingAbstractMember(context: CodeFixContext): CodeAction[] | undefined { 14 | const sourceFile = context.sourceFile; 15 | const start = context.span.start; 16 | // This is the identifier in the case of a class declaration 17 | // or the class keyword token in the case of a class expression. 18 | const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); 19 | const checker = context.program.getTypeChecker(); 20 | 21 | if (isClassLike(token.parent)) { 22 | const classDeclaration = token.parent as ClassLikeDeclaration; 23 | 24 | const extendsNode = getClassExtendsHeritageClauseElement(classDeclaration); 25 | const instantiatedExtendsType = checker.getTypeAtLocation(extendsNode); 26 | 27 | // Note that this is ultimately derived from a map indexed by symbol names, 28 | // so duplicates cannot occur. 29 | const extendsSymbols = checker.getPropertiesOfType(instantiatedExtendsType); 30 | const abstractAndNonPrivateExtendsSymbols = extendsSymbols.filter(symbolPointsToNonPrivateAndAbstractMember); 31 | 32 | const newNodes = createMissingMemberNodes(classDeclaration, abstractAndNonPrivateExtendsSymbols, checker); 33 | const changes = newNodesToChanges(newNodes, getOpenBraceOfClassLike(classDeclaration, sourceFile), context); 34 | if (changes && changes.length > 0) { 35 | return [{ 36 | description: getLocaleSpecificMessage(Diagnostics.Implement_inherited_abstract_class), 37 | changes 38 | }]; 39 | } 40 | } 41 | 42 | return undefined; 43 | 44 | } 45 | 46 | function symbolPointsToNonPrivateAndAbstractMember(symbol: Symbol): boolean { 47 | const decls = symbol.getDeclarations(); 48 | Debug.assert(!!(decls && decls.length > 0)); 49 | const flags = getModifierFlags(decls[0]); 50 | return !(flags & ModifierFlags.Private) && !!(flags & ModifierFlags.Abstract); 51 | } 52 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "1.5.0-alpha", 3 | "compilerOptions": { 4 | "target": "es5", 5 | "module": "commonjs", 6 | "jsx": "react", 7 | "declaration": false, 8 | "noImplicitAny": false, 9 | "removeComments": true, 10 | "noLib": false, 11 | "preserveConstEnums": true, 12 | "suppressImplicitAnyIndexErrors": true 13 | }, 14 | "filesGlob": [ 15 | "./**/*.ts", 16 | "./**/*.tsx", 17 | "!./bin/**/*", 18 | "!./TypeScript/**", 19 | "!./node_modules/**", 20 | "!./tests/grunt/**" 21 | ], 22 | "files": [ 23 | "./extensions/addExtensions.ts", 24 | "./register.ts", 25 | "./src/compiler/binder.ts", 26 | "./src/compiler/checker.ts", 27 | "./src/compiler/commandLineParser.ts", 28 | "./src/compiler/core.ts", 29 | "./src/compiler/declarationEmitter.ts", 30 | "./src/compiler/diagnosticInformationMap.generated.ts", 31 | "./src/compiler/emitter.ts", 32 | "./src/compiler/parser.ts", 33 | "./src/compiler/program.ts", 34 | "./src/compiler/scanner.ts", 35 | "./src/compiler/sys.ts", 36 | "./src/compiler/tsc.ts", 37 | "./src/compiler/types.ts", 38 | "./src/compiler/utilities.ts", 39 | "./src/extensions.ts", 40 | "./src/services/breakpoints.ts", 41 | "./src/services/formatting/formatting.ts", 42 | "./src/services/formatting/formattingContext.ts", 43 | "./src/services/formatting/formattingRequestKind.ts", 44 | "./src/services/formatting/formattingScanner.ts", 45 | "./src/services/formatting/references.ts", 46 | "./src/services/formatting/rule.ts", 47 | "./src/services/formatting/ruleAction.ts", 48 | "./src/services/formatting/ruleDescriptor.ts", 49 | "./src/services/formatting/ruleFlag.ts", 50 | "./src/services/formatting/ruleOperation.ts", 51 | "./src/services/formatting/ruleOperationContext.ts", 52 | "./src/services/formatting/rules.ts", 53 | "./src/services/formatting/rulesMap.ts", 54 | "./src/services/formatting/rulesProvider.ts", 55 | "./src/services/formatting/smartIndenter.ts", 56 | "./src/services/formatting/tokenRange.ts", 57 | "./src/services/navigateTo.ts", 58 | "./src/services/navigationBar.ts", 59 | "./src/services/outliningElementsCollector.ts", 60 | "./src/services/patternMatcher.ts", 61 | "./src/services/services.ts", 62 | "./src/services/shims.ts", 63 | "./src/services/signatureHelp.ts", 64 | "./src/services/utilities.ts", 65 | "./tasks/ntypescript.ts", 66 | "./tests/tse/1start.ts", 67 | "./tests/tse/2iwillfork.ts", 68 | "./tests/tse/3iwilllogargs.ts", 69 | "./tse.ts", 70 | "./typings/gruntjs/gruntjs.d.ts", 71 | "./typings/node/node.d.ts", 72 | "./typings/tsd.d.ts" 73 | ] 74 | } 75 | -------------------------------------------------------------------------------- /bin/lib.es2015.collection.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | 17 | 18 | /// 19 | 20 | 21 | interface Map { 22 | clear(): void; 23 | delete(key: K): boolean; 24 | forEach(callbackfn: (value: V, key: K, map: Map) => void, thisArg?: any): void; 25 | get(key: K): V | undefined; 26 | has(key: K): boolean; 27 | set(key: K, value: V): this; 28 | readonly size: number; 29 | } 30 | 31 | interface MapConstructor { 32 | new (): Map; 33 | new (entries?: [K, V][]): Map; 34 | readonly prototype: Map; 35 | } 36 | declare var Map: MapConstructor; 37 | 38 | interface ReadonlyMap { 39 | forEach(callbackfn: (value: V, key: K, map: ReadonlyMap) => void, thisArg?: any): void; 40 | get(key: K): V | undefined; 41 | has(key: K): boolean; 42 | readonly size: number; 43 | } 44 | 45 | interface WeakMap { 46 | delete(key: K): boolean; 47 | get(key: K): V | undefined; 48 | has(key: K): boolean; 49 | set(key: K, value: V): this; 50 | } 51 | 52 | interface WeakMapConstructor { 53 | new (): WeakMap; 54 | new (entries?: [K, V][]): WeakMap; 55 | readonly prototype: WeakMap; 56 | } 57 | declare var WeakMap: WeakMapConstructor; 58 | 59 | interface Set { 60 | add(value: T): this; 61 | clear(): void; 62 | delete(value: T): boolean; 63 | forEach(callbackfn: (value: T, value2: T, set: Set) => void, thisArg?: any): void; 64 | has(value: T): boolean; 65 | readonly size: number; 66 | } 67 | 68 | interface SetConstructor { 69 | new (): Set; 70 | new (values?: T[]): Set; 71 | readonly prototype: Set; 72 | } 73 | declare var Set: SetConstructor; 74 | 75 | interface ReadonlySet { 76 | forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; 77 | has(value: T): boolean; 78 | readonly size: number; 79 | } 80 | 81 | interface WeakSet { 82 | add(value: T): this; 83 | delete(value: T): boolean; 84 | has(value: T): boolean; 85 | } 86 | 87 | interface WeakSetConstructor { 88 | new (): WeakSet; 89 | new (values?: T[]): WeakSet; 90 | readonly prototype: WeakSet; 91 | } 92 | declare var WeakSet: WeakSetConstructor; 93 | -------------------------------------------------------------------------------- /src/compiler/performance.ts: -------------------------------------------------------------------------------- 1 | /*@internal*/ 2 | namespace ts { 3 | declare const performance: { now?(): number } | undefined; 4 | /** Gets a timestamp with (at least) ms resolution */ 5 | export const timestamp = typeof performance !== "undefined" && performance.now ? () => performance.now() : Date.now ? Date.now : () => +(new Date()); 6 | } 7 | 8 | /*@internal*/ 9 | /** Performance measurements for the compiler. */ 10 | namespace ts.performance { 11 | declare const onProfilerEvent: { (markName: string): void; profiler: boolean; }; 12 | 13 | const profilerEvent = typeof onProfilerEvent === "function" && onProfilerEvent.profiler === true 14 | ? onProfilerEvent 15 | : (_markName: string) => { }; 16 | 17 | let enabled = false; 18 | let profilerStart = 0; 19 | let counts: Map; 20 | let marks: Map; 21 | let measures: Map; 22 | 23 | /** 24 | * Marks a performance event. 25 | * 26 | * @param markName The name of the mark. 27 | */ 28 | export function mark(markName: string) { 29 | if (enabled) { 30 | marks.set(markName, timestamp()); 31 | counts.set(markName, (counts.get(markName) || 0) + 1); 32 | profilerEvent(markName); 33 | } 34 | } 35 | 36 | /** 37 | * Adds a performance measurement with the specified name. 38 | * 39 | * @param measureName The name of the performance measurement. 40 | * @param startMarkName The name of the starting mark. If not supplied, the point at which the 41 | * profiler was enabled is used. 42 | * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is 43 | * used. 44 | */ 45 | export function measure(measureName: string, startMarkName?: string, endMarkName?: string) { 46 | if (enabled) { 47 | const end = endMarkName && marks.get(endMarkName) || timestamp(); 48 | const start = startMarkName && marks.get(startMarkName) || profilerStart; 49 | measures.set(measureName, (measures.get(measureName) || 0) + (end - start)); 50 | } 51 | } 52 | 53 | /** 54 | * Gets the number of times a marker was encountered. 55 | * 56 | * @param markName The name of the mark. 57 | */ 58 | export function getCount(markName: string) { 59 | return counts && counts.get(markName) || 0; 60 | } 61 | 62 | /** 63 | * Gets the total duration of all measurements with the supplied name. 64 | * 65 | * @param measureName The name of the measure whose durations should be accumulated. 66 | */ 67 | export function getDuration(measureName: string) { 68 | return measures && measures.get(measureName) || 0; 69 | } 70 | 71 | /** 72 | * Iterate over each measure, performing some action 73 | * 74 | * @param cb The action to perform for each measure 75 | */ 76 | export function forEachMeasure(cb: (measureName: string, duration: number) => void) { 77 | measures.forEach((measure, key) => { 78 | cb(key, measure); 79 | }); 80 | } 81 | 82 | /** Enables (and resets) performance measurements for the compiler. */ 83 | export function enable() { 84 | counts = createMap(); 85 | marks = createMap(); 86 | measures = createMap(); 87 | enabled = true; 88 | profilerStart = timestamp(); 89 | } 90 | 91 | /** Disables performance measurements for the compiler. */ 92 | export function disable() { 93 | enabled = false; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/services/codefixes/fixClassIncorrectlyImplementsInterface.ts: -------------------------------------------------------------------------------- 1 | /* @internal */ 2 | namespace ts.codefix { 3 | registerCodeFix({ 4 | errorCodes: [Diagnostics.Class_0_incorrectly_implements_interface_1.code], 5 | getCodeActions: getActionForClassLikeIncorrectImplementsInterface 6 | }); 7 | 8 | function getActionForClassLikeIncorrectImplementsInterface(context: CodeFixContext): CodeAction[] | undefined { 9 | const sourceFile = context.sourceFile; 10 | const start = context.span.start; 11 | const token = getTokenAtPosition(sourceFile, start, /*includeJsDocComment*/ false); 12 | const checker = context.program.getTypeChecker(); 13 | 14 | const classDeclaration = getContainingClass(token); 15 | if (!classDeclaration) { 16 | return undefined; 17 | } 18 | 19 | const openBrace = getOpenBraceOfClassLike(classDeclaration, sourceFile); 20 | const classType = checker.getTypeAtLocation(classDeclaration) as InterfaceType; 21 | const implementedTypeNodes = getClassImplementsHeritageClauseElements(classDeclaration); 22 | 23 | const hasNumericIndexSignature = !!checker.getIndexTypeOfType(classType, IndexKind.Number); 24 | const hasStringIndexSignature = !!checker.getIndexTypeOfType(classType, IndexKind.String); 25 | 26 | const result: CodeAction[] = []; 27 | for (const implementedTypeNode of implementedTypeNodes) { 28 | // Note that this is ultimately derived from a map indexed by symbol names, 29 | // so duplicates cannot occur. 30 | const implementedType = checker.getTypeAtLocation(implementedTypeNode) as InterfaceType; 31 | const implementedTypeSymbols = checker.getPropertiesOfType(implementedType); 32 | const nonPrivateMembers = implementedTypeSymbols.filter(symbol => !(getModifierFlags(symbol.valueDeclaration) & ModifierFlags.Private)); 33 | 34 | let newNodes: Node[] = []; 35 | createAndAddMissingIndexSignatureDeclaration(implementedType, IndexKind.Number, hasNumericIndexSignature, newNodes); 36 | createAndAddMissingIndexSignatureDeclaration(implementedType, IndexKind.String, hasStringIndexSignature, newNodes); 37 | newNodes = newNodes.concat(createMissingMemberNodes(classDeclaration, nonPrivateMembers, checker)); 38 | const message = formatStringFromArgs(getLocaleSpecificMessage(Diagnostics.Implement_interface_0), [implementedTypeNode.getText()]); 39 | if (newNodes.length > 0) { 40 | pushAction(result, newNodes, message); 41 | } 42 | } 43 | 44 | return result; 45 | 46 | function createAndAddMissingIndexSignatureDeclaration(type: InterfaceType, kind: IndexKind, hasIndexSigOfKind: boolean, newNodes: Node[]): void { 47 | if (hasIndexSigOfKind) { 48 | return; 49 | } 50 | 51 | const indexInfoOfKind = checker.getIndexInfoOfType(type, kind); 52 | 53 | if (!indexInfoOfKind) { 54 | return; 55 | } 56 | const newIndexSignatureDeclaration = checker.indexInfoToIndexSignatureDeclaration(indexInfoOfKind, kind, classDeclaration); 57 | newNodes.push(newIndexSignatureDeclaration); 58 | } 59 | 60 | function pushAction(result: CodeAction[], newNodes: Node[], description: string): void { 61 | const newAction: CodeAction = { 62 | description: description, 63 | changes: newNodesToChanges(newNodes, openBrace, context) 64 | }; 65 | result.push(newAction); 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /src/services/codefixes/disableJsDiagnostics.ts: -------------------------------------------------------------------------------- 1 | /* @internal */ 2 | namespace ts.codefix { 3 | registerCodeFix({ 4 | errorCodes: getApplicableDiagnosticCodes(), 5 | getCodeActions: getDisableJsDiagnosticsCodeActions 6 | }); 7 | 8 | function getApplicableDiagnosticCodes(): number[] { 9 | const allDiagnostcs = >Diagnostics; 10 | return Object.keys(allDiagnostcs) 11 | .filter(d => allDiagnostcs[d] && allDiagnostcs[d].category === DiagnosticCategory.Error) 12 | .map(d => allDiagnostcs[d].code); 13 | } 14 | 15 | function getIgnoreCommentLocationForLocation(sourceFile: SourceFile, position: number, newLineCharacter: string) { 16 | const { line } = getLineAndCharacterOfPosition(sourceFile, position); 17 | const lineStartPosition = getStartPositionOfLine(line, sourceFile); 18 | const startPosition = getFirstNonSpaceCharacterPosition(sourceFile.text, lineStartPosition); 19 | 20 | // First try to see if we can put the '// @ts-ignore' on the previous line. 21 | // We need to make sure that we are not in the middle of a string literal or a comment. 22 | // We also want to check if the previous line holds a comment for a node on the next line 23 | // if so, we do not want to separate the node from its comment if we can. 24 | if (!isInComment(sourceFile, startPosition) && !isInString(sourceFile, startPosition) && !isInTemplateString(sourceFile, startPosition)) { 25 | const token = getTouchingToken(sourceFile, startPosition, /*includeJsDocComment*/ false); 26 | const tokenLeadingCommnets = getLeadingCommentRangesOfNode(token, sourceFile); 27 | if (!tokenLeadingCommnets || !tokenLeadingCommnets.length || tokenLeadingCommnets[0].pos >= startPosition) { 28 | return { 29 | span: { start: startPosition, length: 0 }, 30 | newText: `// @ts-ignore${newLineCharacter}` 31 | }; 32 | } 33 | } 34 | 35 | // If all fails, add an extra new line immediatlly before the error span. 36 | return { 37 | span: { start: position, length: 0 }, 38 | newText: `${position === startPosition ? "" : newLineCharacter}// @ts-ignore${newLineCharacter}` 39 | }; 40 | } 41 | 42 | function getDisableJsDiagnosticsCodeActions(context: CodeFixContext): CodeAction[] | undefined { 43 | const { sourceFile, program, newLineCharacter, span } = context; 44 | 45 | if (!isInJavaScriptFile(sourceFile) || !isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { 46 | return undefined; 47 | } 48 | 49 | return [{ 50 | description: getLocaleSpecificMessage(Diagnostics.Ignore_this_error_message), 51 | changes: [{ 52 | fileName: sourceFile.fileName, 53 | textChanges: [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter)] 54 | }] 55 | }, 56 | { 57 | description: getLocaleSpecificMessage(Diagnostics.Disable_checking_for_this_file), 58 | changes: [{ 59 | fileName: sourceFile.fileName, 60 | textChanges: [{ 61 | span: { 62 | start: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.pos : 0, 63 | length: sourceFile.checkJsDirective ? sourceFile.checkJsDirective.end - sourceFile.checkJsDirective.pos : 0 64 | }, 65 | newText: `// @ts-nocheck${newLineCharacter}` 66 | }] 67 | }] 68 | }]; 69 | } 70 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NTypeScript is dead. [Bring your own TypeScript](https://github.com/basarat/byots) 🌹 2 | 3 | The following is left as legacy docs. 4 | 5 | # NTypeScript 6 | 7 | [![Downloads](http://img.shields.io/npm/dm/ntypescript.svg)](https://npmjs.org/package/ntypescript) 8 | [![BuildStatus](https://travis-ci.org/TypeStrong/ntypescript.svg)](https://travis-ci.org/TypeStrong/ntypescript) 9 | 10 | **Nicer** [**TypeScript**](https://github.com/Microsoft/TypeScript), **making it easier to work with the compiler API** 🌹 11 | 12 | [![NPM](https://nodei.co/npm-dl/ntypescript.png)](https://nodei.co/npm/ntypescript/) 13 | 14 | > Kudos to the TypeScript team for maintaining all the code that this project depends on. This project is just a minor automation on top. 15 | 16 | Niceness list: 17 | 18 | * Releases everyday. 19 | * Consistent side by side usage (just add an `n` prefix): `require('ntypescript')`, `ntsc` 20 | * `package.json` links you to typescript definitions (using `typescript.definition` entry) 21 | * Super Nice: We expose the internal APIs (the ones that have `/* internal */`) 22 | * Super Nice: We expose the global `ts` variable. Just `require('ntypescript')` once and start using `ts` like you are in the actual compiler source code. 23 | * Super Nice: Converts `const enum` in the compiler definition to `enum`. This decreases the typescript compiler version dependence on your dev tools TS->JS emit. 24 | * Easier to muck around with the compiler / language service when installed from NPM. Just open any file from `node_modules/ntypescript/src` folder in atom-typescript and press `f6` to get a new *local* rebuild. 25 | 26 | Design incompatibilities: 27 | * This project does not ship with `tsserver`. 28 | 29 | ## Install 30 | Similar to `typescript` you can install and use `ntypescript` globally: 31 | 32 | ``` sh 33 | npm install ntypescript -g 34 | ``` 35 | 36 | or in your package.json 37 | 38 | ```sh 39 | npm install ntypescript@latest --save --save-exact 40 | ``` 41 | 42 | Each release is named after the day it was built and the git commit hash in Microsoft/TypeScript/master that it was built from. We recommend adding `save-exact` as there are no guarantees on when stuff might break and you want your users to get the same version you tested. 43 | 44 | ## Usage 45 | 46 | ### Globally 47 | You can use `ntsc` *exactly* like the `tsc` command line tool. 48 | 49 | ### Require 50 | Use `require('ntypescript')` 51 | 52 | ### Global `ts` 53 | In addition to returning what `typescript` returns we also expose `ts` as a global. 54 | 55 | ```ts 56 | declare var require: any; 57 | require('ntypescript'); 58 | console.log(ts.createScanner); 59 | ``` 60 | Which makes it easy to use the compiler API if you are using it heavily. Note you only need to `require` *once* from any file. 61 | 62 | ### Replace TypeScript 63 | For `require('typescript')` you can do that quite simply using your package.json: 64 | 65 | ```json 66 | "dependencies": { 67 | "typescript": "https://github.com/basarat/ntypescript/tarball/" 68 | } 69 | ``` 70 | Release name example : `1.201506301047.1+e1c9d28cb0706f81c14ca95b92fa3e2a223cc60b` 71 | 72 | ### Grunt 73 | This project comes with a built in `grunt` task called `ntypescript`. Just has just one *task* level option: 74 | 75 | * `project` : path to the project directory i.e. the *directory* that contains `tsconfig.json`. 76 | 77 | Here is a sample `Gruntfile.js` for usage: 78 | 79 | ```ts 80 | module.exports = function(grunt) { 81 | grunt.loadNpmTasks('ntypescript'); 82 | 83 | grunt.initConfig({ 84 | ntypescript: { 85 | options: { 86 | project: '.' 87 | } 88 | }, 89 | }); 90 | 91 | grunt.registerTask('default', ['ntypescript']); 92 | }; 93 | ``` 94 | 95 | ### NPM Scripts 96 | Init and setup in `package.json` 97 | ```bash 98 | npm init 99 | npm install ntypescript@latest --save --save-exact 100 | ``` 101 | ```json 102 | "scripts": { 103 | "build": "ntsc -p ./src" 104 | }, 105 | ``` 106 | And then you just need to do the following to build your project: 107 | ```bash 108 | npm run build 109 | ``` 110 | 111 | # About 112 | Note that this is a personal endeavor, not officially by Microsoft. 113 | -------------------------------------------------------------------------------- /src/compiler/transformers/es7.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | 4 | /*@internal*/ 5 | namespace ts { 6 | export function transformES7(context: TransformationContext) { 7 | const { hoistVariableDeclaration } = context; 8 | 9 | return transformSourceFile; 10 | 11 | function transformSourceFile(node: SourceFile) { 12 | if (isDeclarationFile(node)) { 13 | return node; 14 | } 15 | 16 | return visitEachChild(node, visitor, context); 17 | } 18 | 19 | function visitor(node: Node): VisitResult { 20 | if (node.transformFlags & TransformFlags.ES7) { 21 | return visitorWorker(node); 22 | } 23 | else if (node.transformFlags & TransformFlags.ContainsES7) { 24 | return visitEachChild(node, visitor, context); 25 | } 26 | else { 27 | return node; 28 | } 29 | } 30 | 31 | function visitorWorker(node: Node): VisitResult { 32 | switch (node.kind) { 33 | case SyntaxKind.BinaryExpression: 34 | return visitBinaryExpression(node); 35 | 36 | default: 37 | Debug.failBadSyntaxKind(node); 38 | return visitEachChild(node, visitor, context); 39 | } 40 | } 41 | 42 | function visitBinaryExpression(node: BinaryExpression): Expression { 43 | // We are here because ES7 adds support for the exponentiation operator. 44 | const left = visitNode(node.left, visitor, isExpression); 45 | const right = visitNode(node.right, visitor, isExpression); 46 | if (node.operatorToken.kind === SyntaxKind.AsteriskAsteriskEqualsToken) { 47 | let target: Expression; 48 | let value: Expression; 49 | if (isElementAccessExpression(left)) { 50 | // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)` 51 | const expressionTemp = createTempVariable(hoistVariableDeclaration); 52 | 53 | const argumentExpressionTemp = createTempVariable(hoistVariableDeclaration); 54 | 55 | target = createElementAccess( 56 | createAssignment(expressionTemp, left.expression, /*location*/ left.expression), 57 | createAssignment(argumentExpressionTemp, left.argumentExpression, /*location*/ left.argumentExpression), 58 | /*location*/ left 59 | ); 60 | 61 | value = createElementAccess( 62 | expressionTemp, 63 | argumentExpressionTemp, 64 | /*location*/ left 65 | ); 66 | } 67 | else if (isPropertyAccessExpression(left)) { 68 | // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)` 69 | const expressionTemp = createTempVariable(hoistVariableDeclaration); 70 | 71 | target = createPropertyAccess( 72 | createAssignment(expressionTemp, left.expression, /*location*/ left.expression), 73 | left.name, 74 | /*location*/ left 75 | ); 76 | 77 | value = createPropertyAccess( 78 | expressionTemp, 79 | left.name, 80 | /*location*/ left 81 | ); 82 | } 83 | else { 84 | // Transforms `a **= b` into `a = Math.pow(a, b)` 85 | target = left; 86 | value = left; 87 | } 88 | 89 | return createAssignment(target, createMathPow(value, right, /*location*/ node), /*location*/ node); 90 | } 91 | else if (node.operatorToken.kind === SyntaxKind.AsteriskAsteriskToken) { 92 | // Transforms `a ** b` into `Math.pow(a, b)` 93 | return createMathPow(left, right, /*location*/ node); 94 | } 95 | else { 96 | Debug.failBadSyntaxKind(node); 97 | return visitEachChild(node, visitor, context); 98 | } 99 | } 100 | } 101 | } -------------------------------------------------------------------------------- /src/compiler/transformers/es2016.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | 4 | /*@internal*/ 5 | namespace ts { 6 | export function transformES2016(context: TransformationContext) { 7 | const { hoistVariableDeclaration } = context; 8 | 9 | return transformSourceFile; 10 | 11 | function transformSourceFile(node: SourceFile) { 12 | if (node.isDeclarationFile) { 13 | return node; 14 | } 15 | 16 | return visitEachChild(node, visitor, context); 17 | } 18 | 19 | function visitor(node: Node): VisitResult { 20 | if ((node.transformFlags & TransformFlags.ContainsES2016) === 0) { 21 | return node; 22 | } 23 | switch (node.kind) { 24 | case SyntaxKind.BinaryExpression: 25 | return visitBinaryExpression(node); 26 | default: 27 | return visitEachChild(node, visitor, context); 28 | } 29 | } 30 | 31 | function visitBinaryExpression(node: BinaryExpression): Expression { 32 | switch (node.operatorToken.kind) { 33 | case SyntaxKind.AsteriskAsteriskEqualsToken: 34 | return visitExponentiationAssignmentExpression(node); 35 | case SyntaxKind.AsteriskAsteriskToken: 36 | return visitExponentiationExpression(node); 37 | default: 38 | return visitEachChild(node, visitor, context); 39 | } 40 | } 41 | 42 | function visitExponentiationAssignmentExpression(node: BinaryExpression) { 43 | let target: Expression; 44 | let value: Expression; 45 | const left = visitNode(node.left, visitor, isExpression); 46 | const right = visitNode(node.right, visitor, isExpression); 47 | if (isElementAccessExpression(left)) { 48 | // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)` 49 | const expressionTemp = createTempVariable(hoistVariableDeclaration); 50 | const argumentExpressionTemp = createTempVariable(hoistVariableDeclaration); 51 | target = setTextRange( 52 | createElementAccess( 53 | setTextRange(createAssignment(expressionTemp, left.expression), left.expression), 54 | setTextRange(createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression) 55 | ), 56 | left 57 | ); 58 | value = setTextRange( 59 | createElementAccess( 60 | expressionTemp, 61 | argumentExpressionTemp 62 | ), 63 | left 64 | ); 65 | } 66 | else if (isPropertyAccessExpression(left)) { 67 | // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)` 68 | const expressionTemp = createTempVariable(hoistVariableDeclaration); 69 | target = setTextRange( 70 | createPropertyAccess( 71 | setTextRange(createAssignment(expressionTemp, left.expression), left.expression), 72 | left.name 73 | ), 74 | left 75 | ); 76 | value = setTextRange( 77 | createPropertyAccess( 78 | expressionTemp, 79 | left.name 80 | ), 81 | left 82 | ); 83 | } 84 | else { 85 | // Transforms `a **= b` into `a = Math.pow(a, b)` 86 | target = left; 87 | value = left; 88 | } 89 | return setTextRange( 90 | createAssignment( 91 | target, 92 | createMathPow(value, right, /*location*/ node) 93 | ), 94 | node 95 | ); 96 | } 97 | 98 | function visitExponentiationExpression(node: BinaryExpression) { 99 | // Transforms `a ** b` into `Math.pow(a, b)` 100 | const left = visitNode(node.left, visitor, isExpression); 101 | const right = visitNode(node.right, visitor, isExpression); 102 | return createMathPow(left, right, /*location*/ node); 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /bin/lib.dom.iterable.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | 17 | 18 | /// 19 | 20 | 21 | /// 22 | 23 | interface DOMTokenList { 24 | [Symbol.iterator](): IterableIterator; 25 | } 26 | 27 | interface FormData { 28 | /** 29 | * Returns an array of key, value pairs for every entry in the list 30 | */ 31 | entries(): IterableIterator<[string, string | File]>; 32 | /** 33 | * Returns a list of keys in the list 34 | */ 35 | keys(): IterableIterator; 36 | /** 37 | * Returns a list of values in the list 38 | */ 39 | values(): IterableIterator; 40 | 41 | [Symbol.iterator](): IterableIterator; 42 | } 43 | 44 | interface Headers { 45 | [Symbol.iterator](): IterableIterator<[string, string]>; 46 | /** 47 | * Returns an iterator allowing to go through all key/value pairs contained in this object. 48 | */ 49 | entries(): IterableIterator<[string, string]>; 50 | /** 51 | * Returns an iterator allowing to go through all keys f the key/value pairs contained in this object. 52 | */ 53 | keys(): IterableIterator; 54 | /** 55 | * Returns an iterator allowing to go through all values of the key/value pairs contained in this object. 56 | */ 57 | values(): IterableIterator; 58 | } 59 | 60 | interface NodeList { 61 | /** 62 | * Returns an array of key, value pairs for every entry in the list 63 | */ 64 | entries(): IterableIterator<[number, Node]>; 65 | /** 66 | * Performs the specified action for each node in an list. 67 | * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list. 68 | * @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. 69 | */ 70 | forEach(callbackfn: (value: Node, index: number, listObj: NodeList) => void, thisArg?: any): void; 71 | /** 72 | * Returns an list of keys in the list 73 | */ 74 | keys(): IterableIterator; 75 | 76 | /** 77 | * Returns an list of values in the list 78 | */ 79 | values(): IterableIterator; 80 | 81 | 82 | [Symbol.iterator](): IterableIterator; 83 | } 84 | 85 | interface NodeListOf { 86 | 87 | /** 88 | * Returns an array of key, value pairs for every entry in the list 89 | */ 90 | entries(): IterableIterator<[number, TNode]>; 91 | 92 | /** 93 | * Performs the specified action for each node in an list. 94 | * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list. 95 | * @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. 96 | */ 97 | forEach(callbackfn: (value: TNode, index: number, listObj: NodeListOf) => void, thisArg?: any): void; 98 | /** 99 | * Returns an list of keys in the list 100 | */ 101 | keys(): IterableIterator; 102 | /** 103 | * Returns an list of values in the list 104 | */ 105 | values(): IterableIterator; 106 | 107 | [Symbol.iterator](): IterableIterator; 108 | } 109 | 110 | interface URLSearchParams { 111 | /** 112 | * Returns an array of key, value pairs for every entry in the search params 113 | */ 114 | entries(): IterableIterator<[string, string]>; 115 | /** 116 | * Returns a list of keys in the search params 117 | */ 118 | keys(): IterableIterator; 119 | /** 120 | * Returns a list of values in the search params 121 | */ 122 | values(): IterableIterator; 123 | /** 124 | * iterate over key/value pairs 125 | */ 126 | [Symbol.iterator](): IterableIterator<[string, string]>; 127 | } 128 | -------------------------------------------------------------------------------- /src/services/formatting/formattingContext.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | /* @internal */ 4 | namespace ts.formatting { 5 | export class FormattingContext { 6 | public currentTokenSpan: TextRangeWithKind; 7 | public nextTokenSpan: TextRangeWithKind; 8 | public contextNode: Node; 9 | public currentTokenParent: Node; 10 | public nextTokenParent: Node; 11 | 12 | private contextNodeAllOnSameLine: boolean; 13 | private nextNodeAllOnSameLine: boolean; 14 | private tokensAreOnSameLine: boolean; 15 | private contextNodeBlockIsOnOneLine: boolean; 16 | private nextNodeBlockIsOnOneLine: boolean; 17 | 18 | constructor(public readonly sourceFile: SourceFileLike, public formattingRequestKind: FormattingRequestKind, public options: ts.FormatCodeSettings) { 19 | } 20 | 21 | public updateContext(currentRange: TextRangeWithKind, currentTokenParent: Node, nextRange: TextRangeWithKind, nextTokenParent: Node, commonParent: Node) { 22 | Debug.assert(currentRange !== undefined, "currentTokenSpan is null"); 23 | Debug.assert(currentTokenParent !== undefined, "currentTokenParent is null"); 24 | Debug.assert(nextRange !== undefined, "nextTokenSpan is null"); 25 | Debug.assert(nextTokenParent !== undefined, "nextTokenParent is null"); 26 | Debug.assert(commonParent !== undefined, "commonParent is null"); 27 | 28 | this.currentTokenSpan = currentRange; 29 | this.currentTokenParent = currentTokenParent; 30 | this.nextTokenSpan = nextRange; 31 | this.nextTokenParent = nextTokenParent; 32 | this.contextNode = commonParent; 33 | 34 | // drop cached results 35 | this.contextNodeAllOnSameLine = undefined; 36 | this.nextNodeAllOnSameLine = undefined; 37 | this.tokensAreOnSameLine = undefined; 38 | this.contextNodeBlockIsOnOneLine = undefined; 39 | this.nextNodeBlockIsOnOneLine = undefined; 40 | } 41 | 42 | public ContextNodeAllOnSameLine(): boolean { 43 | if (this.contextNodeAllOnSameLine === undefined) { 44 | this.contextNodeAllOnSameLine = this.NodeIsOnOneLine(this.contextNode); 45 | } 46 | 47 | return this.contextNodeAllOnSameLine; 48 | } 49 | 50 | public NextNodeAllOnSameLine(): boolean { 51 | if (this.nextNodeAllOnSameLine === undefined) { 52 | this.nextNodeAllOnSameLine = this.NodeIsOnOneLine(this.nextTokenParent); 53 | } 54 | 55 | return this.nextNodeAllOnSameLine; 56 | } 57 | 58 | public TokensAreOnSameLine(): boolean { 59 | if (this.tokensAreOnSameLine === undefined) { 60 | const startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line; 61 | const endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line; 62 | this.tokensAreOnSameLine = (startLine === endLine); 63 | } 64 | 65 | return this.tokensAreOnSameLine; 66 | } 67 | 68 | public ContextNodeBlockIsOnOneLine() { 69 | if (this.contextNodeBlockIsOnOneLine === undefined) { 70 | this.contextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.contextNode); 71 | } 72 | 73 | return this.contextNodeBlockIsOnOneLine; 74 | } 75 | 76 | public NextNodeBlockIsOnOneLine() { 77 | if (this.nextNodeBlockIsOnOneLine === undefined) { 78 | this.nextNodeBlockIsOnOneLine = this.BlockIsOnOneLine(this.nextTokenParent); 79 | } 80 | 81 | return this.nextNodeBlockIsOnOneLine; 82 | } 83 | 84 | private NodeIsOnOneLine(node: Node): boolean { 85 | const startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line; 86 | const endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line; 87 | return startLine === endLine; 88 | } 89 | 90 | private BlockIsOnOneLine(node: Node): boolean { 91 | const openBrace = findChildOfKind(node, SyntaxKind.OpenBraceToken, this.sourceFile); 92 | const closeBrace = findChildOfKind(node, SyntaxKind.CloseBraceToken, this.sourceFile); 93 | if (openBrace && closeBrace) { 94 | const startLine = this.sourceFile.getLineAndCharacterOfPosition(openBrace.getEnd()).line; 95 | const endLine = this.sourceFile.getLineAndCharacterOfPosition(closeBrace.getStart(this.sourceFile)).line; 96 | return startLine === endLine; 97 | } 98 | return false; 99 | } 100 | } 101 | } -------------------------------------------------------------------------------- /src/services/rename.ts: -------------------------------------------------------------------------------- 1 | /* @internal */ 2 | namespace ts.Rename { 3 | export function getRenameInfo(typeChecker: TypeChecker, defaultLibFileName: string, getCanonicalFileName: (fileName: string) => string, sourceFile: SourceFile, position: number): RenameInfo { 4 | const getCanonicalDefaultLibName = memoize(() => getCanonicalFileName(ts.normalizePath(defaultLibFileName))); 5 | const node = getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); 6 | const renameInfo = node && nodeIsEligibleForRename(node) 7 | ? getRenameInfoForNode(node, typeChecker, sourceFile, isDefinedInLibraryFile) 8 | : undefined; 9 | return renameInfo || getRenameInfoError(Diagnostics.You_cannot_rename_this_element); 10 | 11 | function isDefinedInLibraryFile(declaration: Node) { 12 | if (!defaultLibFileName) { 13 | return false; 14 | } 15 | 16 | const sourceFile = declaration.getSourceFile(); 17 | const canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile.fileName)); 18 | return canonicalName === getCanonicalDefaultLibName(); 19 | } 20 | } 21 | 22 | function getRenameInfoForNode(node: Node, typeChecker: TypeChecker, sourceFile: SourceFile, isDefinedInLibraryFile: (declaration: Node) => boolean): RenameInfo | undefined { 23 | const symbol = typeChecker.getSymbolAtLocation(node); 24 | 25 | // Only allow a symbol to be renamed if it actually has at least one declaration. 26 | if (symbol) { 27 | const declarations = symbol.getDeclarations(); 28 | if (declarations && declarations.length > 0) { 29 | // Disallow rename for elements that are defined in the standard TypeScript library. 30 | if (some(declarations, isDefinedInLibraryFile)) { 31 | return getRenameInfoError(Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); 32 | } 33 | 34 | // Cannot rename `default` as in `import { default as foo } from "./someModule"; 35 | if (node.kind === SyntaxKind.Identifier && 36 | (node as Identifier).originalKeywordKind === SyntaxKind.DefaultKeyword && 37 | symbol.parent.flags & ts.SymbolFlags.Module) { 38 | return undefined; 39 | } 40 | 41 | const displayName = stripQuotes(getDeclaredName(typeChecker, symbol, node)); 42 | const kind = SymbolDisplay.getSymbolKind(typeChecker, symbol, node); 43 | return kind ? getRenameInfoSuccess(displayName, typeChecker.getFullyQualifiedName(symbol), kind, SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile) : undefined; 44 | } 45 | } 46 | else if (node.kind === SyntaxKind.StringLiteral) { 47 | if (isDefinedInLibraryFile(node)) { 48 | return getRenameInfoError(Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library); 49 | } 50 | 51 | const displayName = stripQuotes((node as StringLiteral).text); 52 | return getRenameInfoSuccess(displayName, displayName, ScriptElementKind.variableElement, ScriptElementKindModifier.none, node, sourceFile); 53 | } 54 | } 55 | 56 | function getRenameInfoSuccess(displayName: string, fullDisplayName: string, kind: ScriptElementKind, kindModifiers: string, node: Node, sourceFile: SourceFile): RenameInfo { 57 | return { 58 | canRename: true, 59 | kind, 60 | displayName, 61 | localizedErrorMessage: undefined, 62 | fullDisplayName, 63 | kindModifiers, 64 | triggerSpan: createTriggerSpanForNode(node, sourceFile) 65 | }; 66 | } 67 | 68 | function getRenameInfoError(diagnostic: DiagnosticMessage): RenameInfo { 69 | return { 70 | canRename: false, 71 | localizedErrorMessage: getLocaleSpecificMessage(diagnostic), 72 | displayName: undefined, 73 | fullDisplayName: undefined, 74 | kind: undefined, 75 | kindModifiers: undefined, 76 | triggerSpan: undefined 77 | }; 78 | } 79 | 80 | function createTriggerSpanForNode(node: Node, sourceFile: SourceFile) { 81 | let start = node.getStart(sourceFile); 82 | let width = node.getWidth(sourceFile); 83 | if (node.kind === SyntaxKind.StringLiteral) { 84 | // Exclude the quotes 85 | start += 1; 86 | width -= 2; 87 | } 88 | return createTextSpan(start, width); 89 | } 90 | 91 | function nodeIsEligibleForRename(node: Node): boolean { 92 | return node.kind === ts.SyntaxKind.Identifier || 93 | node.kind === SyntaxKind.StringLiteral || 94 | isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || 95 | isThis(node); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/compiler/transformers/module/es2015.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | 4 | /*@internal*/ 5 | namespace ts { 6 | export function transformES2015Module(context: TransformationContext) { 7 | const compilerOptions = context.getCompilerOptions(); 8 | const previousOnEmitNode = context.onEmitNode; 9 | const previousOnSubstituteNode = context.onSubstituteNode; 10 | context.onEmitNode = onEmitNode; 11 | context.onSubstituteNode = onSubstituteNode; 12 | context.enableEmitNotification(SyntaxKind.SourceFile); 13 | context.enableSubstitution(SyntaxKind.Identifier); 14 | 15 | let currentSourceFile: SourceFile; 16 | return transformSourceFile; 17 | 18 | function transformSourceFile(node: SourceFile) { 19 | if (node.isDeclarationFile) { 20 | return node; 21 | } 22 | 23 | if (isExternalModule(node) || compilerOptions.isolatedModules) { 24 | const externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(node, compilerOptions); 25 | if (externalHelpersModuleName) { 26 | const statements: Statement[] = []; 27 | const statementOffset = addPrologue(statements, node.statements); 28 | append(statements, 29 | createImportDeclaration( 30 | /*decorators*/ undefined, 31 | /*modifiers*/ undefined, 32 | createImportClause(/*name*/ undefined, createNamespaceImport(externalHelpersModuleName)), 33 | createLiteral(externalHelpersModuleNameText) 34 | ) 35 | ); 36 | 37 | addRange(statements, visitNodes(node.statements, visitor, isStatement, statementOffset)); 38 | return updateSourceFileNode( 39 | node, 40 | setTextRange(createNodeArray(statements), node.statements)); 41 | } 42 | else { 43 | return visitEachChild(node, visitor, context); 44 | } 45 | } 46 | 47 | return node; 48 | } 49 | 50 | function visitor(node: Node): VisitResult { 51 | switch (node.kind) { 52 | case SyntaxKind.ImportEqualsDeclaration: 53 | // Elide `import=` as it is not legal with --module ES6 54 | return undefined; 55 | case SyntaxKind.ExportAssignment: 56 | return visitExportAssignment(node); 57 | } 58 | 59 | return node; 60 | } 61 | 62 | function visitExportAssignment(node: ExportAssignment): VisitResult { 63 | // Elide `export=` as it is not legal with --module ES6 64 | return node.isExportEquals ? undefined : node; 65 | } 66 | 67 | // 68 | // Emit Notification 69 | // 70 | 71 | /** 72 | * Hook for node emit. 73 | * 74 | * @param hint A hint as to the intended usage of the node. 75 | * @param node The node to emit. 76 | * @param emit A callback used to emit the node in the printer. 77 | */ 78 | function onEmitNode(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void { 79 | if (isSourceFile(node)) { 80 | currentSourceFile = node; 81 | previousOnEmitNode(hint, node, emitCallback); 82 | currentSourceFile = undefined; 83 | } 84 | else { 85 | previousOnEmitNode(hint, node, emitCallback); 86 | } 87 | } 88 | 89 | // 90 | // Substitutions 91 | // 92 | 93 | /** 94 | * Hooks node substitutions. 95 | * 96 | * @param hint A hint as to the intended usage of the node. 97 | * @param node The node to substitute. 98 | */ 99 | function onSubstituteNode(hint: EmitHint, node: Node) { 100 | node = previousOnSubstituteNode(hint, node); 101 | if (isIdentifier(node) && hint === EmitHint.Expression) { 102 | return substituteExpressionIdentifier(node); 103 | } 104 | 105 | return node; 106 | } 107 | 108 | function substituteExpressionIdentifier(node: Identifier): Expression { 109 | if (getEmitFlags(node) & EmitFlags.HelperName) { 110 | const externalHelpersModuleName = getExternalHelpersModuleName(currentSourceFile); 111 | if (externalHelpersModuleName) { 112 | return createPropertyAccess(externalHelpersModuleName, node); 113 | } 114 | } 115 | return node; 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /bin/lib.es2016.array.include.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | 17 | 18 | /// 19 | 20 | 21 | interface Array { 22 | /** 23 | * Determines whether an array includes a certain element, returning true or false as appropriate. 24 | * @param searchElement The element to search for. 25 | * @param fromIndex The position in this array at which to begin searching for searchElement. 26 | */ 27 | includes(searchElement: T, fromIndex?: number): boolean; 28 | } 29 | 30 | interface ReadonlyArray { 31 | /** 32 | * Determines whether an array includes a certain element, returning true or false as appropriate. 33 | * @param searchElement The element to search for. 34 | * @param fromIndex The position in this array at which to begin searching for searchElement. 35 | */ 36 | includes(searchElement: T, fromIndex?: number): boolean; 37 | } 38 | 39 | interface Int8Array { 40 | /** 41 | * Determines whether an array includes a certain element, returning true or false as appropriate. 42 | * @param searchElement The element to search for. 43 | * @param fromIndex The position in this array at which to begin searching for searchElement. 44 | */ 45 | includes(searchElement: number, fromIndex?: number): boolean; 46 | } 47 | 48 | interface Uint8Array { 49 | /** 50 | * Determines whether an array includes a certain element, returning true or false as appropriate. 51 | * @param searchElement The element to search for. 52 | * @param fromIndex The position in this array at which to begin searching for searchElement. 53 | */ 54 | includes(searchElement: number, fromIndex?: number): boolean; 55 | } 56 | 57 | interface Uint8ClampedArray { 58 | /** 59 | * Determines whether an array includes a certain element, returning true or false as appropriate. 60 | * @param searchElement The element to search for. 61 | * @param fromIndex The position in this array at which to begin searching for searchElement. 62 | */ 63 | includes(searchElement: number, fromIndex?: number): boolean; 64 | } 65 | 66 | interface Int16Array { 67 | /** 68 | * Determines whether an array includes a certain element, returning true or false as appropriate. 69 | * @param searchElement The element to search for. 70 | * @param fromIndex The position in this array at which to begin searching for searchElement. 71 | */ 72 | includes(searchElement: number, fromIndex?: number): boolean; 73 | } 74 | 75 | interface Uint16Array { 76 | /** 77 | * Determines whether an array includes a certain element, returning true or false as appropriate. 78 | * @param searchElement The element to search for. 79 | * @param fromIndex The position in this array at which to begin searching for searchElement. 80 | */ 81 | includes(searchElement: number, fromIndex?: number): boolean; 82 | } 83 | 84 | interface Int32Array { 85 | /** 86 | * Determines whether an array includes a certain element, returning true or false as appropriate. 87 | * @param searchElement The element to search for. 88 | * @param fromIndex The position in this array at which to begin searching for searchElement. 89 | */ 90 | includes(searchElement: number, fromIndex?: number): boolean; 91 | } 92 | 93 | interface Uint32Array { 94 | /** 95 | * Determines whether an array includes a certain element, returning true or false as appropriate. 96 | * @param searchElement The element to search for. 97 | * @param fromIndex The position in this array at which to begin searching for searchElement. 98 | */ 99 | includes(searchElement: number, fromIndex?: number): boolean; 100 | } 101 | 102 | interface Float32Array { 103 | /** 104 | * Determines whether an array includes a certain element, returning true or false as appropriate. 105 | * @param searchElement The element to search for. 106 | * @param fromIndex The position in this array at which to begin searching for searchElement. 107 | */ 108 | includes(searchElement: number, fromIndex?: number): boolean; 109 | } 110 | 111 | interface Float64Array { 112 | /** 113 | * Determines whether an array includes a certain element, returning true or false as appropriate. 114 | * @param searchElement The element to search for. 115 | * @param fromIndex The position in this array at which to begin searching for searchElement. 116 | */ 117 | includes(searchElement: number, fromIndex?: number): boolean; 118 | } -------------------------------------------------------------------------------- /src/compiler/transformers/es5.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | 4 | /*@internal*/ 5 | namespace ts { 6 | /** 7 | * Transforms ES5 syntax into ES3 syntax. 8 | * 9 | * @param context Context and state information for the transformation. 10 | */ 11 | export function transformES5(context: TransformationContext) { 12 | const compilerOptions = context.getCompilerOptions(); 13 | 14 | // enable emit notification only if using --jsx preserve or react-native 15 | let previousOnEmitNode: (hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) => void; 16 | let noSubstitution: boolean[]; 17 | if (compilerOptions.jsx === JsxEmit.Preserve || compilerOptions.jsx === JsxEmit.ReactNative) { 18 | previousOnEmitNode = context.onEmitNode; 19 | context.onEmitNode = onEmitNode; 20 | context.enableEmitNotification(SyntaxKind.JsxOpeningElement); 21 | context.enableEmitNotification(SyntaxKind.JsxClosingElement); 22 | context.enableEmitNotification(SyntaxKind.JsxSelfClosingElement); 23 | noSubstitution = []; 24 | } 25 | 26 | const previousOnSubstituteNode = context.onSubstituteNode; 27 | context.onSubstituteNode = onSubstituteNode; 28 | context.enableSubstitution(SyntaxKind.PropertyAccessExpression); 29 | context.enableSubstitution(SyntaxKind.PropertyAssignment); 30 | return transformSourceFile; 31 | 32 | /** 33 | * Transforms an ES5 source file to ES3. 34 | * 35 | * @param node A SourceFile 36 | */ 37 | function transformSourceFile(node: SourceFile) { 38 | return node; 39 | } 40 | 41 | /** 42 | * Called by the printer just before a node is printed. 43 | * 44 | * @param hint A hint as to the intended usage of the node. 45 | * @param node The node to emit. 46 | * @param emitCallback A callback used to emit the node. 47 | */ 48 | function onEmitNode(hint: EmitHint, node: Node, emitCallback: (emitContext: EmitHint, node: Node) => void) { 49 | switch (node.kind) { 50 | case SyntaxKind.JsxOpeningElement: 51 | case SyntaxKind.JsxClosingElement: 52 | case SyntaxKind.JsxSelfClosingElement: 53 | const tagName = (node).tagName; 54 | noSubstitution[getOriginalNodeId(tagName)] = true; 55 | break; 56 | } 57 | 58 | previousOnEmitNode(hint, node, emitCallback); 59 | } 60 | 61 | /** 62 | * Hooks node substitutions. 63 | * 64 | * @param hint A hint as to the intended usage of the node. 65 | * @param node The node to substitute. 66 | */ 67 | function onSubstituteNode(hint: EmitHint, node: Node) { 68 | if (node.id && noSubstitution && noSubstitution[node.id]) { 69 | return previousOnSubstituteNode(hint, node); 70 | } 71 | 72 | node = previousOnSubstituteNode(hint, node); 73 | if (isPropertyAccessExpression(node)) { 74 | return substitutePropertyAccessExpression(node); 75 | } 76 | else if (isPropertyAssignment(node)) { 77 | return substitutePropertyAssignment(node); 78 | } 79 | return node; 80 | } 81 | 82 | /** 83 | * Substitutes a PropertyAccessExpression whose name is a reserved word. 84 | * 85 | * @param node A PropertyAccessExpression 86 | */ 87 | function substitutePropertyAccessExpression(node: PropertyAccessExpression): Expression { 88 | const literalName = trySubstituteReservedName(node.name); 89 | if (literalName) { 90 | return setTextRange(createElementAccess(node.expression, literalName), node); 91 | } 92 | return node; 93 | } 94 | 95 | /** 96 | * Substitutes a PropertyAssignment whose name is a reserved word. 97 | * 98 | * @param node A PropertyAssignment 99 | */ 100 | function substitutePropertyAssignment(node: PropertyAssignment): PropertyAssignment { 101 | const literalName = isIdentifier(node.name) && trySubstituteReservedName(node.name); 102 | if (literalName) { 103 | return updatePropertyAssignment(node, literalName, node.initializer); 104 | } 105 | return node; 106 | } 107 | 108 | /** 109 | * If an identifier name is a reserved word, returns a string literal for the name. 110 | * 111 | * @param name An Identifier 112 | */ 113 | function trySubstituteReservedName(name: Identifier) { 114 | const token = name.originalKeywordKind || (nodeIsSynthesized(name) ? stringToToken(name.text) : undefined); 115 | if (token >= SyntaxKind.FirstReservedWord && token <= SyntaxKind.LastReservedWord) { 116 | return setTextRange(createLiteral(name), name); 117 | } 118 | return undefined; 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/services/formatting/tokenRange.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | /* @internal */ 4 | namespace ts.formatting { 5 | export namespace Shared { 6 | const allTokens: SyntaxKind[] = []; 7 | for (let token = SyntaxKind.FirstToken; token <= SyntaxKind.LastToken; token++) { 8 | allTokens.push(token); 9 | } 10 | 11 | class TokenValuesAccess implements TokenRange { 12 | constructor(private readonly tokens: SyntaxKind[] = []) { } 13 | 14 | public GetTokens(): SyntaxKind[] { 15 | return this.tokens; 16 | } 17 | 18 | public Contains(token: SyntaxKind): boolean { 19 | return this.tokens.indexOf(token) >= 0; 20 | } 21 | 22 | public isSpecific() { return true; } 23 | } 24 | 25 | class TokenSingleValueAccess implements TokenRange { 26 | constructor(private readonly token: SyntaxKind) {} 27 | 28 | public GetTokens(): SyntaxKind[] { 29 | return [this.token]; 30 | } 31 | 32 | public Contains(tokenValue: SyntaxKind): boolean { 33 | return tokenValue === this.token; 34 | } 35 | 36 | public isSpecific() { return true; } 37 | } 38 | 39 | class TokenAllAccess implements TokenRange { 40 | public GetTokens(): SyntaxKind[] { 41 | return allTokens; 42 | } 43 | 44 | public Contains(): boolean { 45 | return true; 46 | } 47 | 48 | public toString(): string { 49 | return "[allTokens]"; 50 | } 51 | 52 | public isSpecific() { return false; } 53 | } 54 | 55 | class TokenAllExceptAccess implements TokenRange { 56 | constructor(private readonly except: SyntaxKind) {} 57 | 58 | public GetTokens(): SyntaxKind[] { 59 | return allTokens.filter(t => t !== this.except); 60 | } 61 | 62 | public Contains(token: SyntaxKind): boolean { 63 | return token !== this.except; 64 | } 65 | 66 | public isSpecific() { return false; } 67 | } 68 | 69 | export interface TokenRange { 70 | GetTokens(): SyntaxKind[]; 71 | Contains(token: SyntaxKind): boolean; 72 | isSpecific(): boolean; 73 | } 74 | 75 | export namespace TokenRange { 76 | export function FromToken(token: SyntaxKind): TokenRange { 77 | return new TokenSingleValueAccess(token); 78 | } 79 | 80 | export function FromTokens(tokens: SyntaxKind[]): TokenRange { 81 | return new TokenValuesAccess(tokens); 82 | } 83 | 84 | export function FromRange(from: SyntaxKind, to: SyntaxKind, except: SyntaxKind[] = []): TokenRange { 85 | const tokens: SyntaxKind[] = []; 86 | for (let token = from; token <= to; token++) { 87 | if (ts.indexOf(except, token) < 0) { 88 | tokens.push(token); 89 | } 90 | } 91 | return new TokenValuesAccess(tokens); 92 | } 93 | 94 | export function AnyExcept(token: SyntaxKind): TokenRange { 95 | return new TokenAllExceptAccess(token); 96 | } 97 | 98 | export const Any: TokenRange = new TokenAllAccess(); 99 | export const AnyIncludingMultilineComments = TokenRange.FromTokens([...allTokens, SyntaxKind.MultiLineCommentTrivia]); 100 | export const Keywords = TokenRange.FromRange(SyntaxKind.FirstKeyword, SyntaxKind.LastKeyword); 101 | export const BinaryOperators = TokenRange.FromRange(SyntaxKind.FirstBinaryOperator, SyntaxKind.LastBinaryOperator); 102 | export const BinaryKeywordOperators = TokenRange.FromTokens([ 103 | SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword, SyntaxKind.OfKeyword, SyntaxKind.AsKeyword, SyntaxKind.IsKeyword]); 104 | export const UnaryPrefixOperators = TokenRange.FromTokens([ 105 | SyntaxKind.PlusPlusToken, SyntaxKind.MinusMinusToken, SyntaxKind.TildeToken, SyntaxKind.ExclamationToken]); 106 | export const UnaryPrefixExpressions = TokenRange.FromTokens([ 107 | SyntaxKind.NumericLiteral, SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken, 108 | SyntaxKind.OpenBraceToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); 109 | export const UnaryPreincrementExpressions = TokenRange.FromTokens([ 110 | SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); 111 | export const UnaryPostincrementExpressions = TokenRange.FromTokens([ 112 | SyntaxKind.Identifier, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.NewKeyword]); 113 | export const UnaryPredecrementExpressions = TokenRange.FromTokens([ 114 | SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]); 115 | export const UnaryPostdecrementExpressions = TokenRange.FromTokens([ 116 | SyntaxKind.Identifier, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken, SyntaxKind.NewKeyword]); 117 | export const Comments = TokenRange.FromTokens([SyntaxKind.SingleLineCommentTrivia, SyntaxKind.MultiLineCommentTrivia]); 118 | export const TypeNames = TokenRange.FromTokens([ 119 | SyntaxKind.Identifier, SyntaxKind.NumberKeyword, SyntaxKind.StringKeyword, SyntaxKind.BooleanKeyword, 120 | SyntaxKind.SymbolKeyword, SyntaxKind.VoidKeyword, SyntaxKind.AnyKeyword]); 121 | } 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /bin/lib.es2017.sharedmemory.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | 17 | 18 | /// 19 | 20 | 21 | /// 22 | /// 23 | 24 | interface SharedArrayBuffer { 25 | /** 26 | * Read-only. The length of the ArrayBuffer (in bytes). 27 | */ 28 | readonly byteLength: number; 29 | 30 | /* 31 | * The SharedArrayBuffer constructor's length property whose value is 1. 32 | */ 33 | length: number; 34 | /** 35 | * Returns a section of an SharedArrayBuffer. 36 | */ 37 | slice(begin: number, end?: number): SharedArrayBuffer; 38 | readonly [Symbol.species]: SharedArrayBuffer; 39 | readonly [Symbol.toStringTag]: "SharedArrayBuffer"; 40 | } 41 | 42 | interface SharedArrayBufferConstructor { 43 | readonly prototype: SharedArrayBuffer; 44 | new (byteLength: number): SharedArrayBuffer; 45 | } 46 | declare var SharedArrayBuffer: SharedArrayBufferConstructor; 47 | 48 | interface ArrayBufferTypes { 49 | SharedArrayBuffer: SharedArrayBuffer; 50 | } 51 | 52 | interface Atomics { 53 | /** 54 | * Adds a value to the value at the given position in the array, returning the original value. 55 | * Until this atomic operation completes, any other read or write operation against the array 56 | * will block. 57 | */ 58 | add(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; 59 | 60 | /** 61 | * Stores the bitwise AND of a value with the value at the given position in the array, 62 | * returning the original value. Until this atomic operation completes, any other read or 63 | * write operation against the array will block. 64 | */ 65 | and(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; 66 | 67 | /** 68 | * Replaces the value at the given position in the array if the original value equals the given 69 | * expected value, returning the original value. Until this atomic operation completes, any 70 | * other read or write operation against the array will block. 71 | */ 72 | compareExchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, expectedValue: number, replacementValue: number): number; 73 | 74 | /** 75 | * Replaces the value at the given position in the array, returning the original value. Until 76 | * this atomic operation completes, any other read or write operation against the array will 77 | * block. 78 | */ 79 | exchange(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; 80 | 81 | /** 82 | * Returns a value indicating whether high-performance algorithms can use atomic operations 83 | * (`true`) or must use locks (`false`) for the given number of bytes-per-element of a typed 84 | * array. 85 | */ 86 | isLockFree(size: number): boolean; 87 | 88 | /** 89 | * Returns the value at the given position in the array. Until this atomic operation completes, 90 | * any other read or write operation against the array will block. 91 | */ 92 | load(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number): number; 93 | 94 | /** 95 | * Stores the bitwise OR of a value with the value at the given position in the array, 96 | * returning the original value. Until this atomic operation completes, any other read or write 97 | * operation against the array will block. 98 | */ 99 | or(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; 100 | 101 | /** 102 | * Stores a value at the given position in the array, returning the new value. Until this 103 | * atomic operation completes, any other read or write operation against the array will block. 104 | */ 105 | store(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; 106 | 107 | /** 108 | * Subtracts a value from the value at the given position in the array, returning the original 109 | * value. Until this atomic operation completes, any other read or write operation against the 110 | * array will block. 111 | */ 112 | sub(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; 113 | 114 | /** 115 | * If the value at the given position in the array is equal to the provided value, the current 116 | * agent is put to sleep causing execution to suspend until the timeout expires (returning 117 | * `"timed-out"`) or until the agent is awoken (returning `"ok"`); otherwise, returns 118 | * `"not-equal"`. 119 | */ 120 | wait(typedArray: Int32Array, index: number, value: number, timeout?: number): "ok" | "not-equal" | "timed-out"; 121 | 122 | /** 123 | * Wakes up sleeping agents that are waiting on the given index of the array, returning the 124 | * number of agents that were awoken. 125 | */ 126 | wake(typedArray: Int32Array, index: number, count: number): number; 127 | 128 | /** 129 | * Stores the bitwise XOR of a value with the value at the given position in the array, 130 | * returning the original value. Until this atomic operation completes, any other read or write 131 | * operation against the array will block. 132 | */ 133 | xor(typedArray: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array, index: number, value: number): number; 134 | 135 | readonly [Symbol.toStringTag]: "Atomics"; 136 | } 137 | 138 | declare var Atomics: Atomics; -------------------------------------------------------------------------------- /src/compiler/transformers/module/es6.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | 4 | /*@internal*/ 5 | namespace ts { 6 | export function transformES6Module(context: TransformationContext) { 7 | const compilerOptions = context.getCompilerOptions(); 8 | const resolver = context.getEmitResolver(); 9 | 10 | let currentSourceFile: SourceFile; 11 | 12 | return transformSourceFile; 13 | 14 | function transformSourceFile(node: SourceFile) { 15 | if (isDeclarationFile(node)) { 16 | return node; 17 | } 18 | 19 | if (isExternalModule(node) || compilerOptions.isolatedModules) { 20 | currentSourceFile = node; 21 | return visitEachChild(node, visitor, context); 22 | } 23 | return node; 24 | } 25 | 26 | function visitor(node: Node): VisitResult { 27 | switch (node.kind) { 28 | case SyntaxKind.ImportDeclaration: 29 | return visitImportDeclaration(node); 30 | case SyntaxKind.ImportEqualsDeclaration: 31 | return visitImportEqualsDeclaration(node); 32 | case SyntaxKind.ImportClause: 33 | return visitImportClause(node); 34 | case SyntaxKind.NamedImports: 35 | case SyntaxKind.NamespaceImport: 36 | return visitNamedBindings(node); 37 | case SyntaxKind.ImportSpecifier: 38 | return visitImportSpecifier(node); 39 | case SyntaxKind.ExportAssignment: 40 | return visitExportAssignment(node); 41 | case SyntaxKind.ExportDeclaration: 42 | return visitExportDeclaration(node); 43 | case SyntaxKind.NamedExports: 44 | return visitNamedExports(node); 45 | case SyntaxKind.ExportSpecifier: 46 | return visitExportSpecifier(node); 47 | } 48 | 49 | return node; 50 | } 51 | 52 | function visitExportAssignment(node: ExportAssignment): ExportAssignment { 53 | if (node.isExportEquals) { 54 | return undefined; // do not emit export equals for ES6 55 | } 56 | const original = getOriginalNode(node); 57 | return nodeIsSynthesized(original) || resolver.isValueAliasDeclaration(original) ? node : undefined; 58 | } 59 | 60 | function visitExportDeclaration(node: ExportDeclaration): ExportDeclaration { 61 | if (!node.exportClause) { 62 | return resolver.moduleExportsSomeValue(node.moduleSpecifier) ? node : undefined; 63 | } 64 | if (!resolver.isValueAliasDeclaration(node)) { 65 | return undefined; 66 | } 67 | const newExportClause = visitNode(node.exportClause, visitor, isNamedExports, /*optional*/ true); 68 | if (node.exportClause === newExportClause) { 69 | return node; 70 | } 71 | return newExportClause 72 | ? createExportDeclaration( 73 | /*decorators*/ undefined, 74 | /*modifiers*/ undefined, 75 | newExportClause, 76 | node.moduleSpecifier) 77 | : undefined; 78 | } 79 | 80 | function visitNamedExports(node: NamedExports): NamedExports { 81 | const newExports = visitNodes(node.elements, visitor, isExportSpecifier); 82 | if (node.elements === newExports) { 83 | return node; 84 | } 85 | return newExports.length ? createNamedExports(newExports) : undefined; 86 | } 87 | 88 | function visitExportSpecifier(node: ExportSpecifier): ExportSpecifier { 89 | return resolver.isValueAliasDeclaration(node) ? node : undefined; 90 | } 91 | 92 | function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): ImportEqualsDeclaration { 93 | return !isExternalModuleImportEqualsDeclaration(node) || resolver.isReferencedAliasDeclaration(node) ? node : undefined; 94 | } 95 | 96 | function visitImportDeclaration(node: ImportDeclaration) { 97 | if (node.importClause) { 98 | const newImportClause = visitNode(node.importClause, visitor, isImportClause); 99 | if (!newImportClause.name && !newImportClause.namedBindings) { 100 | return undefined; 101 | } 102 | else if (newImportClause !== node.importClause) { 103 | return createImportDeclaration( 104 | /*decorators*/ undefined, 105 | /*modifiers*/ undefined, 106 | newImportClause, 107 | node.moduleSpecifier); 108 | } 109 | } 110 | return node; 111 | } 112 | 113 | function visitImportClause(node: ImportClause): ImportClause { 114 | let newDefaultImport = node.name; 115 | if (!resolver.isReferencedAliasDeclaration(node)) { 116 | newDefaultImport = undefined; 117 | } 118 | const newNamedBindings = visitNode(node.namedBindings, visitor, isNamedImportBindings, /*optional*/ true); 119 | return newDefaultImport !== node.name || newNamedBindings !== node.namedBindings 120 | ? createImportClause(newDefaultImport, newNamedBindings) 121 | : node; 122 | } 123 | 124 | function visitNamedBindings(node: NamedImportBindings): VisitResult { 125 | if (node.kind === SyntaxKind.NamespaceImport) { 126 | return resolver.isReferencedAliasDeclaration(node) ? node : undefined; 127 | } 128 | else { 129 | const newNamedImportElements = visitNodes((node).elements, visitor, isImportSpecifier); 130 | if (!newNamedImportElements || newNamedImportElements.length == 0) { 131 | return undefined; 132 | } 133 | if (newNamedImportElements === (node).elements) { 134 | return node; 135 | } 136 | return createNamedImports(newNamedImportElements); 137 | } 138 | } 139 | 140 | function visitImportSpecifier(node: ImportSpecifier) { 141 | return resolver.isReferencedAliasDeclaration(node) ? node : undefined; 142 | } 143 | } 144 | } -------------------------------------------------------------------------------- /src/services/transpile.ts: -------------------------------------------------------------------------------- 1 | namespace ts { 2 | export interface TranspileOptions { 3 | compilerOptions?: CompilerOptions; 4 | fileName?: string; 5 | reportDiagnostics?: boolean; 6 | moduleName?: string; 7 | renamedDependencies?: MapLike; 8 | transformers?: CustomTransformers; 9 | } 10 | 11 | export interface TranspileOutput { 12 | outputText: string; 13 | diagnostics?: Diagnostic[]; 14 | sourceMapText?: string; 15 | } 16 | 17 | /* 18 | * This function will compile source text from 'input' argument using specified compiler options. 19 | * If not options are provided - it will use a set of default compiler options. 20 | * Extra compiler options that will unconditionally be used by this function are: 21 | * - isolatedModules = true 22 | * - allowNonTsExtensions = true 23 | * - noLib = true 24 | * - noResolve = true 25 | */ 26 | export function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput { 27 | const diagnostics: Diagnostic[] = []; 28 | 29 | const options: CompilerOptions = transpileOptions.compilerOptions ? fixupCompilerOptions(transpileOptions.compilerOptions, diagnostics) : getDefaultCompilerOptions(); 30 | 31 | options.isolatedModules = true; 32 | 33 | // transpileModule does not write anything to disk so there is no need to verify that there are no conflicts between input and output paths. 34 | options.suppressOutputPathCheck = true; 35 | 36 | // Filename can be non-ts file. 37 | options.allowNonTsExtensions = true; 38 | 39 | // We are not returning a sourceFile for lib file when asked by the program, 40 | // so pass --noLib to avoid reporting a file not found error. 41 | options.noLib = true; 42 | 43 | // Clear out other settings that would not be used in transpiling this module 44 | options.lib = undefined; 45 | options.types = undefined; 46 | options.noEmit = undefined; 47 | options.noEmitOnError = undefined; 48 | options.paths = undefined; 49 | options.rootDirs = undefined; 50 | options.declaration = undefined; 51 | options.declarationDir = undefined; 52 | options.out = undefined; 53 | options.outFile = undefined; 54 | 55 | // We are not doing a full typecheck, we are not resolving the whole context, 56 | // so pass --noResolve to avoid reporting missing file errors. 57 | options.noResolve = true; 58 | 59 | // if jsx is specified then treat file as .tsx 60 | const inputFileName = transpileOptions.fileName || (options.jsx ? "module.tsx" : "module.ts"); 61 | const sourceFile = createSourceFile(inputFileName, input, options.target); 62 | if (transpileOptions.moduleName) { 63 | sourceFile.moduleName = transpileOptions.moduleName; 64 | } 65 | 66 | if (transpileOptions.renamedDependencies) { 67 | sourceFile.renamedDependencies = createMapFromTemplate(transpileOptions.renamedDependencies); 68 | } 69 | 70 | const newLine = getNewLineCharacter(options); 71 | 72 | // Output 73 | let outputText: string; 74 | let sourceMapText: string; 75 | 76 | // Create a compilerHost object to allow the compiler to read and write files 77 | const compilerHost: CompilerHost = { 78 | getSourceFile: (fileName) => fileName === normalizePath(inputFileName) ? sourceFile : undefined, 79 | writeFile: (name, text) => { 80 | if (fileExtensionIs(name, ".map")) { 81 | Debug.assert(sourceMapText === undefined, `Unexpected multiple source map outputs for the file '${name}'`); 82 | sourceMapText = text; 83 | } 84 | else { 85 | Debug.assert(outputText === undefined, `Unexpected multiple outputs for the file: '${name}'`); 86 | outputText = text; 87 | } 88 | }, 89 | getDefaultLibFileName: () => "lib.d.ts", 90 | useCaseSensitiveFileNames: () => false, 91 | getCanonicalFileName: fileName => fileName, 92 | getCurrentDirectory: () => "", 93 | getNewLine: () => newLine, 94 | fileExists: (fileName): boolean => fileName === inputFileName, 95 | readFile: () => "", 96 | directoryExists: () => true, 97 | getDirectories: () => [] 98 | }; 99 | 100 | const program = createProgram([inputFileName], options, compilerHost); 101 | 102 | if (transpileOptions.reportDiagnostics) { 103 | addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile)); 104 | addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics()); 105 | } 106 | // Emit 107 | program.emit(/*targetSourceFile*/ undefined, /*writeFile*/ undefined, /*cancellationToken*/ undefined, /*emitOnlyDtsFiles*/ undefined, transpileOptions.transformers); 108 | 109 | Debug.assert(outputText !== undefined, "Output generation failed"); 110 | 111 | return { outputText, diagnostics, sourceMapText }; 112 | } 113 | 114 | /* 115 | * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result. 116 | */ 117 | export function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string { 118 | const output = transpileModule(input, { compilerOptions, fileName, reportDiagnostics: !!diagnostics, moduleName }); 119 | // addRange correctly handles cases when wither 'from' or 'to' argument is missing 120 | addRange(diagnostics, output.diagnostics); 121 | return output.outputText; 122 | } 123 | 124 | let commandLineOptionsStringToEnum: CommandLineOptionOfCustomType[]; 125 | 126 | /** JS users may pass in string values for enum compiler options (such as ModuleKind), so convert. */ 127 | /*@internal*/ 128 | export function fixupCompilerOptions(options: CompilerOptions, diagnostics: Diagnostic[]): CompilerOptions { 129 | // Lazily create this value to fix module loading errors. 130 | commandLineOptionsStringToEnum = commandLineOptionsStringToEnum || filter(optionDeclarations, o => 131 | typeof o.type === "object" && !forEachEntry(o.type, v => typeof v !== "number")); 132 | 133 | options = cloneCompilerOptions(options); 134 | 135 | for (const opt of commandLineOptionsStringToEnum) { 136 | if (!hasProperty(options, opt.name)) { 137 | continue; 138 | } 139 | 140 | const value = options[opt.name]; 141 | // Value should be a key of opt.type 142 | if (typeof value === "string") { 143 | // If value is not a string, this will fail 144 | options[opt.name] = parseCustomTypeOption(opt, value, diagnostics); 145 | } 146 | else { 147 | if (!forEachEntry(opt.type, v => v === value)) { 148 | // Supplied value isn't a valid enum value. 149 | diagnostics.push(createCompilerDiagnosticForInvalidCustomType(opt)); 150 | } 151 | } 152 | } 153 | 154 | return options; 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/services/formatting/rulesMap.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | /* @internal */ 4 | namespace ts.formatting { 5 | export class RulesMap { 6 | public map: RulesBucket[]; 7 | public mapRowLength: number; 8 | 9 | constructor() { 10 | this.map = []; 11 | this.mapRowLength = 0; 12 | } 13 | 14 | static create(rules: Rule[]): RulesMap { 15 | const result = new RulesMap(); 16 | result.Initialize(rules); 17 | return result; 18 | } 19 | 20 | public Initialize(rules: Rule[]) { 21 | this.mapRowLength = SyntaxKind.LastToken + 1; 22 | this.map = new Array(this.mapRowLength * this.mapRowLength); // new Array(this.mapRowLength * this.mapRowLength); 23 | 24 | // This array is used only during construction of the rulesbucket in the map 25 | const rulesBucketConstructionStateList: RulesBucketConstructionState[] = new Array(this.map.length); // new Array(this.map.length); 26 | 27 | this.FillRules(rules, rulesBucketConstructionStateList); 28 | return this.map; 29 | } 30 | 31 | public FillRules(rules: Rule[], rulesBucketConstructionStateList: RulesBucketConstructionState[]): void { 32 | rules.forEach((rule) => { 33 | this.FillRule(rule, rulesBucketConstructionStateList); 34 | }); 35 | } 36 | 37 | private GetRuleBucketIndex(row: number, column: number): number { 38 | Debug.assert(row <= SyntaxKind.LastKeyword && column <= SyntaxKind.LastKeyword, "Must compute formatting context from tokens"); 39 | const rulesBucketIndex = (row * this.mapRowLength) + column; 40 | return rulesBucketIndex; 41 | } 42 | 43 | private FillRule(rule: Rule, rulesBucketConstructionStateList: RulesBucketConstructionState[]): void { 44 | const specificRule = rule.Descriptor.LeftTokenRange.isSpecific() && rule.Descriptor.RightTokenRange.isSpecific(); 45 | 46 | rule.Descriptor.LeftTokenRange.GetTokens().forEach((left) => { 47 | rule.Descriptor.RightTokenRange.GetTokens().forEach((right) => { 48 | const rulesBucketIndex = this.GetRuleBucketIndex(left, right); 49 | 50 | let rulesBucket = this.map[rulesBucketIndex]; 51 | if (rulesBucket === undefined) { 52 | rulesBucket = this.map[rulesBucketIndex] = new RulesBucket(); 53 | } 54 | 55 | rulesBucket.AddRule(rule, specificRule, rulesBucketConstructionStateList, rulesBucketIndex); 56 | }); 57 | }); 58 | } 59 | 60 | public GetRule(context: FormattingContext): Rule { 61 | const bucketIndex = this.GetRuleBucketIndex(context.currentTokenSpan.kind, context.nextTokenSpan.kind); 62 | const bucket = this.map[bucketIndex]; 63 | if (bucket) { 64 | for (const rule of bucket.Rules()) { 65 | if (rule.Operation.Context.InContext(context)) { 66 | return rule; 67 | } 68 | } 69 | } 70 | return undefined; 71 | } 72 | } 73 | 74 | const MaskBitSize = 5; 75 | const Mask = 0x1f; 76 | 77 | export enum RulesPosition { 78 | IgnoreRulesSpecific = 0, 79 | IgnoreRulesAny = MaskBitSize * 1, 80 | ContextRulesSpecific = MaskBitSize * 2, 81 | ContextRulesAny = MaskBitSize * 3, 82 | NoContextRulesSpecific = MaskBitSize * 4, 83 | NoContextRulesAny = MaskBitSize * 5 84 | } 85 | 86 | export class RulesBucketConstructionState { 87 | private rulesInsertionIndexBitmap: number; 88 | 89 | constructor() { 90 | //// The Rules list contains all the inserted rules into a rulebucket in the following order: 91 | //// 1- Ignore rules with specific token combination 92 | //// 2- Ignore rules with any token combination 93 | //// 3- Context rules with specific token combination 94 | //// 4- Context rules with any token combination 95 | //// 5- Non-context rules with specific token combination 96 | //// 6- Non-context rules with any token combination 97 | //// 98 | //// The member rulesInsertionIndexBitmap is used to describe the number of rules 99 | //// in each sub-bucket (above) hence can be used to know the index of where to insert 100 | //// the next rule. It's a bitmap which contains 6 different sections each is given 5 bits. 101 | //// 102 | //// Example: 103 | //// In order to insert a rule to the end of sub-bucket (3), we get the index by adding 104 | //// the values in the bitmap segments 3rd, 2nd, and 1st. 105 | this.rulesInsertionIndexBitmap = 0; 106 | } 107 | 108 | public GetInsertionIndex(maskPosition: RulesPosition): number { 109 | let index = 0; 110 | 111 | let pos = 0; 112 | let indexBitmap = this.rulesInsertionIndexBitmap; 113 | 114 | while (pos <= maskPosition) { 115 | index += (indexBitmap & Mask); 116 | indexBitmap >>= MaskBitSize; 117 | pos += MaskBitSize; 118 | } 119 | 120 | return index; 121 | } 122 | 123 | public IncreaseInsertionIndex(maskPosition: RulesPosition): void { 124 | let value = (this.rulesInsertionIndexBitmap >> maskPosition) & Mask; 125 | value++; 126 | Debug.assert((value & Mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules."); 127 | 128 | let temp = this.rulesInsertionIndexBitmap & ~(Mask << maskPosition); 129 | temp |= value << maskPosition; 130 | 131 | this.rulesInsertionIndexBitmap = temp; 132 | } 133 | } 134 | 135 | export class RulesBucket { 136 | private rules: Rule[]; 137 | 138 | constructor() { 139 | this.rules = []; 140 | } 141 | 142 | public Rules(): Rule[] { 143 | return this.rules; 144 | } 145 | 146 | public AddRule(rule: Rule, specificTokens: boolean, constructionState: RulesBucketConstructionState[], rulesBucketIndex: number): void { 147 | let position: RulesPosition; 148 | 149 | if (rule.Operation.Action === RuleAction.Ignore) { 150 | position = specificTokens ? 151 | RulesPosition.IgnoreRulesSpecific : 152 | RulesPosition.IgnoreRulesAny; 153 | } 154 | else if (!rule.Operation.Context.IsAny()) { 155 | position = specificTokens ? 156 | RulesPosition.ContextRulesSpecific : 157 | RulesPosition.ContextRulesAny; 158 | } 159 | else { 160 | position = specificTokens ? 161 | RulesPosition.NoContextRulesSpecific : 162 | RulesPosition.NoContextRulesAny; 163 | } 164 | 165 | let state = constructionState[rulesBucketIndex]; 166 | if (state === undefined) { 167 | state = constructionState[rulesBucketIndex] = new RulesBucketConstructionState(); 168 | } 169 | const index = state.GetInsertionIndex(position); 170 | this.rules.splice(index, 0, rule); 171 | state.IncreaseInsertionIndex(position); 172 | } 173 | } 174 | } -------------------------------------------------------------------------------- /src/services/outliningElementsCollector.ts: -------------------------------------------------------------------------------- 1 | /* @internal */ 2 | namespace ts.OutliningElementsCollector { 3 | export function collectElements(sourceFile: SourceFile, cancellationToken: CancellationToken): OutliningSpan[] { 4 | const elements: OutliningSpan[] = []; 5 | const collapseText = "..."; 6 | 7 | function addOutliningSpan(hintSpanNode: Node, startElement: Node, endElement: Node, autoCollapse: boolean) { 8 | if (hintSpanNode && startElement && endElement) { 9 | const span: OutliningSpan = { 10 | textSpan: createTextSpanFromBounds(startElement.pos, endElement.end), 11 | hintSpan: createTextSpanFromNode(hintSpanNode, sourceFile), 12 | bannerText: collapseText, 13 | autoCollapse: autoCollapse 14 | }; 15 | elements.push(span); 16 | } 17 | } 18 | 19 | function addOutliningSpanComments(commentSpan: CommentRange, autoCollapse: boolean) { 20 | if (commentSpan) { 21 | const span: OutliningSpan = { 22 | textSpan: createTextSpanFromBounds(commentSpan.pos, commentSpan.end), 23 | hintSpan: createTextSpanFromBounds(commentSpan.pos, commentSpan.end), 24 | bannerText: collapseText, 25 | autoCollapse: autoCollapse 26 | }; 27 | elements.push(span); 28 | } 29 | } 30 | 31 | function addOutliningForLeadingCommentsForNode(n: Node) { 32 | const comments = ts.getLeadingCommentRangesOfNode(n, sourceFile); 33 | 34 | if (comments) { 35 | let firstSingleLineCommentStart = -1; 36 | let lastSingleLineCommentEnd = -1; 37 | let isFirstSingleLineComment = true; 38 | let singleLineCommentCount = 0; 39 | 40 | for (const currentComment of comments) { 41 | cancellationToken.throwIfCancellationRequested(); 42 | 43 | // For single line comments, combine consecutive ones (2 or more) into 44 | // a single span from the start of the first till the end of the last 45 | if (currentComment.kind === SyntaxKind.SingleLineCommentTrivia) { 46 | if (isFirstSingleLineComment) { 47 | firstSingleLineCommentStart = currentComment.pos; 48 | } 49 | isFirstSingleLineComment = false; 50 | lastSingleLineCommentEnd = currentComment.end; 51 | singleLineCommentCount++; 52 | } 53 | else if (currentComment.kind === SyntaxKind.MultiLineCommentTrivia) { 54 | combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); 55 | addOutliningSpanComments(currentComment, /*autoCollapse*/ false); 56 | 57 | singleLineCommentCount = 0; 58 | lastSingleLineCommentEnd = -1; 59 | isFirstSingleLineComment = true; 60 | } 61 | } 62 | 63 | combineAndAddMultipleSingleLineComments(singleLineCommentCount, firstSingleLineCommentStart, lastSingleLineCommentEnd); 64 | } 65 | } 66 | 67 | function combineAndAddMultipleSingleLineComments(count: number, start: number, end: number) { 68 | 69 | // Only outline spans of two or more consecutive single line comments 70 | if (count > 1) { 71 | const multipleSingleLineComments: CommentRange = { 72 | kind: SyntaxKind.SingleLineCommentTrivia, 73 | pos: start, 74 | end: end, 75 | }; 76 | 77 | addOutliningSpanComments(multipleSingleLineComments, /*autoCollapse*/ false); 78 | } 79 | } 80 | 81 | function autoCollapse(node: Node) { 82 | return isFunctionBlock(node) && node.parent.kind !== SyntaxKind.ArrowFunction; 83 | } 84 | 85 | let depth = 0; 86 | const maxDepth = 20; 87 | function walk(n: Node): void { 88 | cancellationToken.throwIfCancellationRequested(); 89 | if (depth > maxDepth) { 90 | return; 91 | } 92 | 93 | if (isDeclaration(n)) { 94 | addOutliningForLeadingCommentsForNode(n); 95 | } 96 | 97 | switch (n.kind) { 98 | case SyntaxKind.Block: 99 | if (!isFunctionBlock(n)) { 100 | const parent = n.parent; 101 | const openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile); 102 | const closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile); 103 | 104 | // Check if the block is standalone, or 'attached' to some parent statement. 105 | // If the latter, we want to collapse the block, but consider its hint span 106 | // to be the entire span of the parent. 107 | if (parent.kind === SyntaxKind.DoStatement || 108 | parent.kind === SyntaxKind.ForInStatement || 109 | parent.kind === SyntaxKind.ForOfStatement || 110 | parent.kind === SyntaxKind.ForStatement || 111 | parent.kind === SyntaxKind.IfStatement || 112 | parent.kind === SyntaxKind.WhileStatement || 113 | parent.kind === SyntaxKind.WithStatement || 114 | parent.kind === SyntaxKind.CatchClause) { 115 | 116 | addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n)); 117 | break; 118 | } 119 | 120 | if (parent.kind === SyntaxKind.TryStatement) { 121 | // Could be the try-block, or the finally-block. 122 | const tryStatement = parent; 123 | if (tryStatement.tryBlock === n) { 124 | addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n)); 125 | break; 126 | } 127 | else if (tryStatement.finallyBlock === n) { 128 | const finallyKeyword = findChildOfKind(tryStatement, SyntaxKind.FinallyKeyword, sourceFile); 129 | if (finallyKeyword) { 130 | addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n)); 131 | break; 132 | } 133 | } 134 | 135 | // fall through. 136 | } 137 | 138 | // Block was a standalone block. In this case we want to only collapse 139 | // the span of the block, independent of any parent span. 140 | const span = createTextSpanFromNode(n); 141 | elements.push({ 142 | textSpan: span, 143 | hintSpan: span, 144 | bannerText: collapseText, 145 | autoCollapse: autoCollapse(n) 146 | }); 147 | break; 148 | } 149 | // falls through 150 | 151 | case SyntaxKind.ModuleBlock: { 152 | const openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile); 153 | const closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile); 154 | addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n)); 155 | break; 156 | } 157 | case SyntaxKind.ClassDeclaration: 158 | case SyntaxKind.InterfaceDeclaration: 159 | case SyntaxKind.EnumDeclaration: 160 | case SyntaxKind.ObjectLiteralExpression: 161 | case SyntaxKind.CaseBlock: { 162 | const openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile); 163 | const closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile); 164 | addOutliningSpan(n, openBrace, closeBrace, autoCollapse(n)); 165 | break; 166 | } 167 | case SyntaxKind.ArrayLiteralExpression: 168 | const openBracket = findChildOfKind(n, SyntaxKind.OpenBracketToken, sourceFile); 169 | const closeBracket = findChildOfKind(n, SyntaxKind.CloseBracketToken, sourceFile); 170 | addOutliningSpan(n, openBracket, closeBracket, autoCollapse(n)); 171 | break; 172 | } 173 | depth++; 174 | forEachChild(n, walk); 175 | depth--; 176 | } 177 | 178 | walk(sourceFile); 179 | return elements; 180 | } 181 | } -------------------------------------------------------------------------------- /src/compiler/transformers/utilities.ts: -------------------------------------------------------------------------------- 1 | /* @internal */ 2 | namespace ts { 3 | export function getOriginalNodeId(node: Node) { 4 | node = getOriginalNode(node); 5 | return node ? getNodeId(node) : 0; 6 | } 7 | 8 | export interface ExternalModuleInfo { 9 | externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[]; // imports of other external modules 10 | externalHelpersImportDeclaration: ImportDeclaration | undefined; // import of external helpers 11 | exportSpecifiers: Map; // export specifiers by name 12 | exportedBindings: Identifier[][]; // exported names of local declarations 13 | exportedNames: Identifier[]; // all exported names local to module 14 | exportEquals: ExportAssignment | undefined; // an export= declaration if one was present 15 | hasExportStarsToExportValues: boolean; // whether this module contains export* 16 | } 17 | 18 | export function collectExternalModuleInfo(sourceFile: SourceFile, resolver: EmitResolver, compilerOptions: CompilerOptions): ExternalModuleInfo { 19 | const externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[] = []; 20 | const exportSpecifiers = createMultiMap(); 21 | const exportedBindings: Identifier[][] = []; 22 | const uniqueExports = createMap(); 23 | let exportedNames: Identifier[]; 24 | let hasExportDefault = false; 25 | let exportEquals: ExportAssignment = undefined; 26 | let hasExportStarsToExportValues = false; 27 | 28 | for (const node of sourceFile.statements) { 29 | switch (node.kind) { 30 | case SyntaxKind.ImportDeclaration: 31 | // import "mod" 32 | // import x from "mod" 33 | // import * as x from "mod" 34 | // import { x, y } from "mod" 35 | externalImports.push(node); 36 | break; 37 | 38 | case SyntaxKind.ImportEqualsDeclaration: 39 | if ((node).moduleReference.kind === SyntaxKind.ExternalModuleReference) { 40 | // import x = require("mod") 41 | externalImports.push(node); 42 | } 43 | 44 | break; 45 | 46 | case SyntaxKind.ExportDeclaration: 47 | if ((node).moduleSpecifier) { 48 | if (!(node).exportClause) { 49 | // export * from "mod" 50 | externalImports.push(node); 51 | hasExportStarsToExportValues = true; 52 | } 53 | else { 54 | // export { x, y } from "mod" 55 | externalImports.push(node); 56 | } 57 | } 58 | else { 59 | // export { x, y } 60 | for (const specifier of (node).exportClause.elements) { 61 | if (!uniqueExports.get(specifier.name.text)) { 62 | const name = specifier.propertyName || specifier.name; 63 | exportSpecifiers.add(name.text, specifier); 64 | 65 | const decl = resolver.getReferencedImportDeclaration(name) 66 | || resolver.getReferencedValueDeclaration(name); 67 | 68 | if (decl) { 69 | multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name); 70 | } 71 | 72 | uniqueExports.set(specifier.name.text, true); 73 | exportedNames = append(exportedNames, specifier.name); 74 | } 75 | } 76 | } 77 | break; 78 | 79 | case SyntaxKind.ExportAssignment: 80 | if ((node).isExportEquals && !exportEquals) { 81 | // export = x 82 | exportEquals = node; 83 | } 84 | break; 85 | 86 | case SyntaxKind.VariableStatement: 87 | if (hasModifier(node, ModifierFlags.Export)) { 88 | for (const decl of (node).declarationList.declarations) { 89 | exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames); 90 | } 91 | } 92 | break; 93 | 94 | case SyntaxKind.FunctionDeclaration: 95 | if (hasModifier(node, ModifierFlags.Export)) { 96 | if (hasModifier(node, ModifierFlags.Default)) { 97 | // export default function() { } 98 | if (!hasExportDefault) { 99 | multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), getDeclarationName(node)); 100 | hasExportDefault = true; 101 | } 102 | } 103 | else { 104 | // export function x() { } 105 | const name = (node).name; 106 | if (!uniqueExports.get(name.text)) { 107 | multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); 108 | uniqueExports.set(name.text, true); 109 | exportedNames = append(exportedNames, name); 110 | } 111 | } 112 | } 113 | break; 114 | 115 | case SyntaxKind.ClassDeclaration: 116 | if (hasModifier(node, ModifierFlags.Export)) { 117 | if (hasModifier(node, ModifierFlags.Default)) { 118 | // export default class { } 119 | if (!hasExportDefault) { 120 | multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), getDeclarationName(node)); 121 | hasExportDefault = true; 122 | } 123 | } 124 | else { 125 | // export class x { } 126 | const name = (node).name; 127 | if (!uniqueExports.get(name.text)) { 128 | multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name); 129 | uniqueExports.set(name.text, true); 130 | exportedNames = append(exportedNames, name); 131 | } 132 | } 133 | } 134 | break; 135 | } 136 | } 137 | 138 | const externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues); 139 | const externalHelpersImportDeclaration = externalHelpersModuleName && createImportDeclaration( 140 | /*decorators*/ undefined, 141 | /*modifiers*/ undefined, 142 | createImportClause(/*name*/ undefined, createNamespaceImport(externalHelpersModuleName)), 143 | createLiteral(externalHelpersModuleNameText)); 144 | 145 | if (externalHelpersImportDeclaration) { 146 | externalImports.unshift(externalHelpersImportDeclaration); 147 | } 148 | 149 | return { externalImports, exportSpecifiers, exportEquals, hasExportStarsToExportValues, exportedBindings, exportedNames, externalHelpersImportDeclaration }; 150 | } 151 | 152 | function collectExportedVariableInfo(decl: VariableDeclaration | BindingElement, uniqueExports: Map, exportedNames: Identifier[]) { 153 | if (isBindingPattern(decl.name)) { 154 | for (const element of decl.name.elements) { 155 | if (!isOmittedExpression(element)) { 156 | exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames); 157 | } 158 | } 159 | } 160 | else if (!isGeneratedIdentifier(decl.name)) { 161 | if (!uniqueExports.get(decl.name.text)) { 162 | uniqueExports.set(decl.name.text, true); 163 | exportedNames = append(exportedNames, decl.name); 164 | } 165 | } 166 | return exportedNames; 167 | } 168 | 169 | /** Use a sparse array as a multi-map. */ 170 | function multiMapSparseArrayAdd(map: V[][], key: number, value: V): V[] { 171 | let values = map[key]; 172 | if (values) { 173 | values.push(value); 174 | } 175 | else { 176 | map[key] = values = [value]; 177 | } 178 | return values; 179 | } 180 | } -------------------------------------------------------------------------------- /src/services/navigateTo.ts: -------------------------------------------------------------------------------- 1 | /* @internal */ 2 | namespace ts.NavigateTo { 3 | type RawNavigateToItem = { name: string; fileName: string; matchKind: PatternMatchKind; isCaseSensitive: boolean; declaration: Declaration }; 4 | 5 | export function getNavigateToItems(sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number, excludeDtsFiles: boolean): NavigateToItem[] { 6 | const patternMatcher = createPatternMatcher(searchValue); 7 | let rawItems: RawNavigateToItem[] = []; 8 | 9 | // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] 10 | for (const sourceFile of sourceFiles) { 11 | cancellationToken.throwIfCancellationRequested(); 12 | 13 | if (excludeDtsFiles && fileExtensionIs(sourceFile.fileName, Extension.Dts)) { 14 | continue; 15 | } 16 | 17 | forEachEntry(sourceFile.getNamedDeclarations(), (declarations, name) => { 18 | if (declarations) { 19 | // First do a quick check to see if the name of the declaration matches the 20 | // last portion of the (possibly) dotted name they're searching for. 21 | let matches = patternMatcher.getMatchesForLastSegmentOfPattern(name); 22 | 23 | if (!matches) { 24 | return; // continue to next named declarations 25 | } 26 | 27 | for (const declaration of declarations) { 28 | // It was a match! If the pattern has dots in it, then also see if the 29 | // declaration container matches as well. 30 | if (patternMatcher.patternContainsDots) { 31 | const containers = getContainers(declaration); 32 | if (!containers) { 33 | return true; // Break out of named declarations and go to the next source file. 34 | } 35 | 36 | matches = patternMatcher.getMatches(containers, name); 37 | 38 | if (!matches) { 39 | return; // continue to next named declarations 40 | } 41 | } 42 | 43 | const fileName = sourceFile.fileName; 44 | const matchKind = bestMatchKind(matches); 45 | rawItems.push({ name, fileName, matchKind, isCaseSensitive: allMatchesAreCaseSensitive(matches), declaration }); 46 | } 47 | } 48 | }); 49 | } 50 | 51 | // Remove imports when the imported declaration is already in the list and has the same name. 52 | rawItems = filter(rawItems, item => { 53 | const decl = item.declaration; 54 | if (decl.kind === SyntaxKind.ImportClause || decl.kind === SyntaxKind.ImportSpecifier || decl.kind === SyntaxKind.ImportEqualsDeclaration) { 55 | const importer = checker.getSymbolAtLocation((decl as NamedDeclaration).name); 56 | const imported = checker.getAliasedSymbol(importer); 57 | return importer.name !== imported.name; 58 | } 59 | else { 60 | return true; 61 | } 62 | }); 63 | 64 | rawItems.sort(compareNavigateToItems); 65 | if (maxResultCount !== undefined) { 66 | rawItems = rawItems.slice(0, maxResultCount); 67 | } 68 | 69 | const items = map(rawItems, createNavigateToItem); 70 | 71 | return items; 72 | 73 | function allMatchesAreCaseSensitive(matches: PatternMatch[]): boolean { 74 | Debug.assert(matches.length > 0); 75 | 76 | // This is a case sensitive match, only if all the submatches were case sensitive. 77 | for (const match of matches) { 78 | if (!match.isCaseSensitive) { 79 | return false; 80 | } 81 | } 82 | 83 | return true; 84 | } 85 | 86 | function getTextOfIdentifierOrLiteral(node: Node) { 87 | if (node) { 88 | if (node.kind === SyntaxKind.Identifier || 89 | node.kind === SyntaxKind.StringLiteral || 90 | node.kind === SyntaxKind.NumericLiteral) { 91 | 92 | return (node).text; 93 | } 94 | } 95 | 96 | return undefined; 97 | } 98 | 99 | function tryAddSingleDeclarationName(declaration: Declaration, containers: string[]) { 100 | if (declaration) { 101 | const name = getNameOfDeclaration(declaration); 102 | if (name) { 103 | const text = getTextOfIdentifierOrLiteral(name); 104 | if (text !== undefined) { 105 | containers.unshift(text); 106 | } 107 | else if (name.kind === SyntaxKind.ComputedPropertyName) { 108 | return tryAddComputedPropertyName((name).expression, containers, /*includeLastPortion*/ true); 109 | } 110 | else { 111 | // Don't know how to add this. 112 | return false; 113 | } 114 | } 115 | } 116 | 117 | return true; 118 | } 119 | 120 | // Only added the names of computed properties if they're simple dotted expressions, like: 121 | // 122 | // [X.Y.Z]() { } 123 | function tryAddComputedPropertyName(expression: Expression, containers: string[], includeLastPortion: boolean): boolean { 124 | const text = getTextOfIdentifierOrLiteral(expression); 125 | if (text !== undefined) { 126 | if (includeLastPortion) { 127 | containers.unshift(text); 128 | } 129 | return true; 130 | } 131 | 132 | if (expression.kind === SyntaxKind.PropertyAccessExpression) { 133 | const propertyAccess = expression; 134 | if (includeLastPortion) { 135 | containers.unshift(propertyAccess.name.text); 136 | } 137 | 138 | return tryAddComputedPropertyName(propertyAccess.expression, containers, /*includeLastPortion*/ true); 139 | } 140 | 141 | return false; 142 | } 143 | 144 | function getContainers(declaration: Declaration) { 145 | const containers: string[] = []; 146 | 147 | // First, if we started with a computed property name, then add all but the last 148 | // portion into the container array. 149 | const name = getNameOfDeclaration(declaration); 150 | if (name.kind === SyntaxKind.ComputedPropertyName) { 151 | if (!tryAddComputedPropertyName((name).expression, containers, /*includeLastPortion*/ false)) { 152 | return undefined; 153 | } 154 | } 155 | 156 | // Now, walk up our containers, adding all their names to the container array. 157 | declaration = getContainerNode(declaration); 158 | 159 | while (declaration) { 160 | if (!tryAddSingleDeclarationName(declaration, containers)) { 161 | return undefined; 162 | } 163 | 164 | declaration = getContainerNode(declaration); 165 | } 166 | 167 | return containers; 168 | } 169 | 170 | function bestMatchKind(matches: PatternMatch[]) { 171 | Debug.assert(matches.length > 0); 172 | let bestMatchKind = PatternMatchKind.camelCase; 173 | 174 | for (const match of matches) { 175 | const kind = match.kind; 176 | if (kind < bestMatchKind) { 177 | bestMatchKind = kind; 178 | } 179 | } 180 | 181 | return bestMatchKind; 182 | } 183 | 184 | function compareNavigateToItems(i1: RawNavigateToItem, i2: RawNavigateToItem) { 185 | // TODO(cyrusn): get the gamut of comparisons that VS already uses here. 186 | // Right now we just sort by kind first, and then by name of the item. 187 | // We first sort case insensitively. So "Aaa" will come before "bar". 188 | // Then we sort case sensitively, so "aaa" will come before "Aaa". 189 | return i1.matchKind - i2.matchKind || 190 | ts.compareStringsCaseInsensitive(i1.name, i2.name) || 191 | ts.compareStrings(i1.name, i2.name); 192 | } 193 | 194 | function createNavigateToItem(rawItem: RawNavigateToItem): NavigateToItem { 195 | const declaration = rawItem.declaration; 196 | const container = getContainerNode(declaration); 197 | const containerName = container && getNameOfDeclaration(container); 198 | return { 199 | name: rawItem.name, 200 | kind: getNodeKind(declaration), 201 | kindModifiers: getNodeModifiers(declaration), 202 | matchKind: PatternMatchKind[rawItem.matchKind], 203 | isCaseSensitive: rawItem.isCaseSensitive, 204 | fileName: rawItem.fileName, 205 | textSpan: createTextSpanFromNode(declaration), 206 | // TODO(jfreeman): What should be the containerName when the container has a computed name? 207 | containerName: containerName ? (containerName).text : "", 208 | containerKind: containerName ? getNodeKind(container) : ScriptElementKind.unknown 209 | }; 210 | } 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /bin/lib.scripthost.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | 17 | 18 | /// 19 | 20 | 21 | 22 | 23 | ///////////////////////////// 24 | /// Windows Script Host APIS 25 | ///////////////////////////// 26 | 27 | 28 | interface ActiveXObject { 29 | new (s: string): any; 30 | } 31 | declare var ActiveXObject: ActiveXObject; 32 | 33 | interface ITextWriter { 34 | Write(s: string): void; 35 | WriteLine(s: string): void; 36 | Close(): void; 37 | } 38 | 39 | interface TextStreamBase { 40 | /** 41 | * The column number of the current character position in an input stream. 42 | */ 43 | Column: number; 44 | 45 | /** 46 | * The current line number in an input stream. 47 | */ 48 | Line: number; 49 | 50 | /** 51 | * Closes a text stream. 52 | * It is not necessary to close standard streams; they close automatically when the process ends. If 53 | * you close a standard stream, be aware that any other pointers to that standard stream become invalid. 54 | */ 55 | Close(): void; 56 | } 57 | 58 | interface TextStreamWriter extends TextStreamBase { 59 | /** 60 | * Sends a string to an output stream. 61 | */ 62 | Write(s: string): void; 63 | 64 | /** 65 | * Sends a specified number of blank lines (newline characters) to an output stream. 66 | */ 67 | WriteBlankLines(intLines: number): void; 68 | 69 | /** 70 | * Sends a string followed by a newline character to an output stream. 71 | */ 72 | WriteLine(s: string): void; 73 | } 74 | 75 | interface TextStreamReader extends TextStreamBase { 76 | /** 77 | * Returns a specified number of characters from an input stream, starting at the current pointer position. 78 | * Does not return until the ENTER key is pressed. 79 | * Can only be used on a stream in reading mode; causes an error in writing or appending mode. 80 | */ 81 | Read(characters: number): string; 82 | 83 | /** 84 | * Returns all characters from an input stream. 85 | * Can only be used on a stream in reading mode; causes an error in writing or appending mode. 86 | */ 87 | ReadAll(): string; 88 | 89 | /** 90 | * Returns an entire line from an input stream. 91 | * Although this method extracts the newline character, it does not add it to the returned string. 92 | * Can only be used on a stream in reading mode; causes an error in writing or appending mode. 93 | */ 94 | ReadLine(): string; 95 | 96 | /** 97 | * Skips a specified number of characters when reading from an input text stream. 98 | * Can only be used on a stream in reading mode; causes an error in writing or appending mode. 99 | * @param characters Positive number of characters to skip forward. (Backward skipping is not supported.) 100 | */ 101 | Skip(characters: number): void; 102 | 103 | /** 104 | * Skips the next line when reading from an input text stream. 105 | * Can only be used on a stream in reading mode, not writing or appending mode. 106 | */ 107 | SkipLine(): void; 108 | 109 | /** 110 | * Indicates whether the stream pointer position is at the end of a line. 111 | */ 112 | AtEndOfLine: boolean; 113 | 114 | /** 115 | * Indicates whether the stream pointer position is at the end of a stream. 116 | */ 117 | AtEndOfStream: boolean; 118 | } 119 | 120 | declare var WScript: { 121 | /** 122 | * Outputs text to either a message box (under WScript.exe) or the command console window followed by 123 | * a newline (under CScript.exe). 124 | */ 125 | Echo(s: any): void; 126 | 127 | /** 128 | * Exposes the write-only error output stream for the current script. 129 | * Can be accessed only while using CScript.exe. 130 | */ 131 | StdErr: TextStreamWriter; 132 | 133 | /** 134 | * Exposes the write-only output stream for the current script. 135 | * Can be accessed only while using CScript.exe. 136 | */ 137 | StdOut: TextStreamWriter; 138 | Arguments: { length: number; Item(n: number): string; }; 139 | 140 | /** 141 | * The full path of the currently running script. 142 | */ 143 | ScriptFullName: string; 144 | 145 | /** 146 | * Forces the script to stop immediately, with an optional exit code. 147 | */ 148 | Quit(exitCode?: number): number; 149 | 150 | /** 151 | * The Windows Script Host build version number. 152 | */ 153 | BuildVersion: number; 154 | 155 | /** 156 | * Fully qualified path of the host executable. 157 | */ 158 | FullName: string; 159 | 160 | /** 161 | * Gets/sets the script mode - interactive(true) or batch(false). 162 | */ 163 | Interactive: boolean; 164 | 165 | /** 166 | * The name of the host executable (WScript.exe or CScript.exe). 167 | */ 168 | Name: string; 169 | 170 | /** 171 | * Path of the directory containing the host executable. 172 | */ 173 | Path: string; 174 | 175 | /** 176 | * The filename of the currently running script. 177 | */ 178 | ScriptName: string; 179 | 180 | /** 181 | * Exposes the read-only input stream for the current script. 182 | * Can be accessed only while using CScript.exe. 183 | */ 184 | StdIn: TextStreamReader; 185 | 186 | /** 187 | * Windows Script Host version 188 | */ 189 | Version: string; 190 | 191 | /** 192 | * Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event. 193 | */ 194 | ConnectObject(objEventSource: any, strPrefix: string): void; 195 | 196 | /** 197 | * Creates a COM object. 198 | * @param strProgiID 199 | * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. 200 | */ 201 | CreateObject(strProgID: string, strPrefix?: string): any; 202 | 203 | /** 204 | * Disconnects a COM object from its event sources. 205 | */ 206 | DisconnectObject(obj: any): void; 207 | 208 | /** 209 | * Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file. 210 | * @param strPathname Fully qualified path to the file containing the object persisted to disk. 211 | * For objects in memory, pass a zero-length string. 212 | * @param strProgID 213 | * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. 214 | */ 215 | GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any; 216 | 217 | /** 218 | * Suspends script execution for a specified length of time, then continues execution. 219 | * @param intTime Interval (in milliseconds) to suspend script execution. 220 | */ 221 | Sleep(intTime: number): void; 222 | }; 223 | 224 | /** 225 | * Allows enumerating over a COM collection, which may not have indexed item access. 226 | */ 227 | interface Enumerator { 228 | /** 229 | * Returns true if the current item is the last one in the collection, or the collection is empty, 230 | * or the current item is undefined. 231 | */ 232 | atEnd(): boolean; 233 | 234 | /** 235 | * Returns the current item in the collection 236 | */ 237 | item(): T; 238 | 239 | /** 240 | * Resets the current item in the collection to the first item. If there are no items in the collection, 241 | * the current item is set to undefined. 242 | */ 243 | moveFirst(): void; 244 | 245 | /** 246 | * Moves the current item to the next item in the collection. If the enumerator is at the end of 247 | * the collection or the collection is empty, the current item is set to undefined. 248 | */ 249 | moveNext(): void; 250 | } 251 | 252 | interface EnumeratorConstructor { 253 | new (collection: any): Enumerator; 254 | new (collection: any): Enumerator; 255 | } 256 | 257 | declare var Enumerator: EnumeratorConstructor; 258 | 259 | /** 260 | * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions. 261 | */ 262 | interface VBArray { 263 | /** 264 | * Returns the number of dimensions (1-based). 265 | */ 266 | dimensions(): number; 267 | 268 | /** 269 | * Takes an index for each dimension in the array, and returns the item at the corresponding location. 270 | */ 271 | getItem(dimension1Index: number, ...dimensionNIndexes: number[]): T; 272 | 273 | /** 274 | * Returns the smallest available index for a given dimension. 275 | * @param dimension 1-based dimension (defaults to 1) 276 | */ 277 | lbound(dimension?: number): number; 278 | 279 | /** 280 | * Returns the largest available index for a given dimension. 281 | * @param dimension 1-based dimension (defaults to 1) 282 | */ 283 | ubound(dimension?: number): number; 284 | 285 | /** 286 | * Returns a Javascript array with all the elements in the VBArray. If there are multiple dimensions, 287 | * each successive dimension is appended to the end of the array. 288 | * Example: [[1,2,3],[4,5,6]] becomes [1,2,3,4,5,6] 289 | */ 290 | toArray(): T[]; 291 | } 292 | 293 | interface VBArrayConstructor { 294 | new (safeArray: any): VBArray; 295 | new (safeArray: any): VBArray; 296 | } 297 | 298 | declare var VBArray: VBArrayConstructor; 299 | 300 | /** 301 | * Automation date (VT_DATE) 302 | */ 303 | interface VarDate { } 304 | 305 | interface DateConstructor { 306 | new (vd: VarDate): Date; 307 | } 308 | 309 | interface Date { 310 | getVarDate: () => VarDate; 311 | } 312 | -------------------------------------------------------------------------------- /bin/lib.scriptHost.d.ts: -------------------------------------------------------------------------------- 1 | /*! ***************************************************************************** 2 | Copyright (c) Microsoft Corporation. All rights reserved. 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 4 | this file except in compliance with the License. You may obtain a copy of the 5 | License at http://www.apache.org/licenses/LICENSE-2.0 6 | 7 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 8 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 9 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 10 | MERCHANTABLITY OR NON-INFRINGEMENT. 11 | 12 | See the Apache Version 2.0 License for specific language governing permissions 13 | and limitations under the License. 14 | ***************************************************************************** */ 15 | 16 | /// 17 | 18 | 19 | ///////////////////////////// 20 | /// Windows Script Host APIS 21 | ///////////////////////////// 22 | 23 | 24 | interface ActiveXObject { 25 | new (s: string): any; 26 | } 27 | declare var ActiveXObject: ActiveXObject; 28 | 29 | interface ITextWriter { 30 | Write(s: string): void; 31 | WriteLine(s: string): void; 32 | Close(): void; 33 | } 34 | 35 | interface TextStreamBase { 36 | /** 37 | * The column number of the current character position in an input stream. 38 | */ 39 | Column: number; 40 | 41 | /** 42 | * The current line number in an input stream. 43 | */ 44 | Line: number; 45 | 46 | /** 47 | * Closes a text stream. 48 | * It is not necessary to close standard streams; they close automatically when the process ends. If 49 | * you close a standard stream, be aware that any other pointers to that standard stream become invalid. 50 | */ 51 | Close(): void; 52 | } 53 | 54 | interface TextStreamWriter extends TextStreamBase { 55 | /** 56 | * Sends a string to an output stream. 57 | */ 58 | Write(s: string): void; 59 | 60 | /** 61 | * Sends a specified number of blank lines (newline characters) to an output stream. 62 | */ 63 | WriteBlankLines(intLines: number): void; 64 | 65 | /** 66 | * Sends a string followed by a newline character to an output stream. 67 | */ 68 | WriteLine(s: string): void; 69 | } 70 | 71 | interface TextStreamReader extends TextStreamBase { 72 | /** 73 | * Returns a specified number of characters from an input stream, starting at the current pointer position. 74 | * Does not return until the ENTER key is pressed. 75 | * Can only be used on a stream in reading mode; causes an error in writing or appending mode. 76 | */ 77 | Read(characters: number): string; 78 | 79 | /** 80 | * Returns all characters from an input stream. 81 | * Can only be used on a stream in reading mode; causes an error in writing or appending mode. 82 | */ 83 | ReadAll(): string; 84 | 85 | /** 86 | * Returns an entire line from an input stream. 87 | * Although this method extracts the newline character, it does not add it to the returned string. 88 | * Can only be used on a stream in reading mode; causes an error in writing or appending mode. 89 | */ 90 | ReadLine(): string; 91 | 92 | /** 93 | * Skips a specified number of characters when reading from an input text stream. 94 | * Can only be used on a stream in reading mode; causes an error in writing or appending mode. 95 | * @param characters Positive number of characters to skip forward. (Backward skipping is not supported.) 96 | */ 97 | Skip(characters: number): void; 98 | 99 | /** 100 | * Skips the next line when reading from an input text stream. 101 | * Can only be used on a stream in reading mode, not writing or appending mode. 102 | */ 103 | SkipLine(): void; 104 | 105 | /** 106 | * Indicates whether the stream pointer position is at the end of a line. 107 | */ 108 | AtEndOfLine: boolean; 109 | 110 | /** 111 | * Indicates whether the stream pointer position is at the end of a stream. 112 | */ 113 | AtEndOfStream: boolean; 114 | } 115 | 116 | declare var WScript: { 117 | /** 118 | * Outputs text to either a message box (under WScript.exe) or the command console window followed by 119 | * a newline (under CScript.exe). 120 | */ 121 | Echo(s: any): void; 122 | 123 | /** 124 | * Exposes the write-only error output stream for the current script. 125 | * Can be accessed only while using CScript.exe. 126 | */ 127 | StdErr: TextStreamWriter; 128 | 129 | /** 130 | * Exposes the write-only output stream for the current script. 131 | * Can be accessed only while using CScript.exe. 132 | */ 133 | StdOut: TextStreamWriter; 134 | Arguments: { length: number; Item(n: number): string; }; 135 | 136 | /** 137 | * The full path of the currently running script. 138 | */ 139 | ScriptFullName: string; 140 | 141 | /** 142 | * Forces the script to stop immediately, with an optional exit code. 143 | */ 144 | Quit(exitCode?: number): number; 145 | 146 | /** 147 | * The Windows Script Host build version number. 148 | */ 149 | BuildVersion: number; 150 | 151 | /** 152 | * Fully qualified path of the host executable. 153 | */ 154 | FullName: string; 155 | 156 | /** 157 | * Gets/sets the script mode - interactive(true) or batch(false). 158 | */ 159 | Interactive: boolean; 160 | 161 | /** 162 | * The name of the host executable (WScript.exe or CScript.exe). 163 | */ 164 | Name: string; 165 | 166 | /** 167 | * Path of the directory containing the host executable. 168 | */ 169 | Path: string; 170 | 171 | /** 172 | * The filename of the currently running script. 173 | */ 174 | ScriptName: string; 175 | 176 | /** 177 | * Exposes the read-only input stream for the current script. 178 | * Can be accessed only while using CScript.exe. 179 | */ 180 | StdIn: TextStreamReader; 181 | 182 | /** 183 | * Windows Script Host version 184 | */ 185 | Version: string; 186 | 187 | /** 188 | * Connects a COM object's event sources to functions named with a given prefix, in the form prefix_event. 189 | */ 190 | ConnectObject(objEventSource: any, strPrefix: string): void; 191 | 192 | /** 193 | * Creates a COM object. 194 | * @param strProgiID 195 | * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. 196 | */ 197 | CreateObject(strProgID: string, strPrefix?: string): any; 198 | 199 | /** 200 | * Disconnects a COM object from its event sources. 201 | */ 202 | DisconnectObject(obj: any): void; 203 | 204 | /** 205 | * Retrieves an existing object with the specified ProgID from memory, or creates a new one from a file. 206 | * @param strPathname Fully qualified path to the file containing the object persisted to disk. 207 | * For objects in memory, pass a zero-length string. 208 | * @param strProgID 209 | * @param strPrefix Function names in the form prefix_event will be bound to this object's COM events. 210 | */ 211 | GetObject(strPathname: string, strProgID?: string, strPrefix?: string): any; 212 | 213 | /** 214 | * Suspends script execution for a specified length of time, then continues execution. 215 | * @param intTime Interval (in milliseconds) to suspend script execution. 216 | */ 217 | Sleep(intTime: number): void; 218 | }; 219 | 220 | /** 221 | * Allows enumerating over a COM collection, which may not have indexed item access. 222 | */ 223 | interface Enumerator { 224 | /** 225 | * Returns true if the current item is the last one in the collection, or the collection is empty, 226 | * or the current item is undefined. 227 | */ 228 | atEnd(): boolean; 229 | 230 | /** 231 | * Returns the current item in the collection 232 | */ 233 | item(): T; 234 | 235 | /** 236 | * Resets the current item in the collection to the first item. If there are no items in the collection, 237 | * the current item is set to undefined. 238 | */ 239 | moveFirst(): void; 240 | 241 | /** 242 | * Moves the current item to the next item in the collection. If the enumerator is at the end of 243 | * the collection or the collection is empty, the current item is set to undefined. 244 | */ 245 | moveNext(): void; 246 | } 247 | 248 | interface EnumeratorConstructor { 249 | new (collection: any): Enumerator; 250 | new (collection: any): Enumerator; 251 | } 252 | 253 | declare var Enumerator: EnumeratorConstructor; 254 | 255 | /** 256 | * Enables reading from a COM safe array, which might have an alternate lower bound, or multiple dimensions. 257 | */ 258 | interface VBArray { 259 | /** 260 | * Returns the number of dimensions (1-based). 261 | */ 262 | dimensions(): number; 263 | 264 | /** 265 | * Takes an index for each dimension in the array, and returns the item at the corresponding location. 266 | */ 267 | getItem(dimension1Index: number, ...dimensionNIndexes: number[]): T; 268 | 269 | /** 270 | * Returns the smallest available index for a given dimension. 271 | * @param dimension 1-based dimension (defaults to 1) 272 | */ 273 | lbound(dimension?: number): number; 274 | 275 | /** 276 | * Returns the largest available index for a given dimension. 277 | * @param dimension 1-based dimension (defaults to 1) 278 | */ 279 | ubound(dimension?: number): number; 280 | 281 | /** 282 | * Returns a Javascript array with all the elements in the VBArray. If there are multiple dimensions, 283 | * each successive dimension is appended to the end of the array. 284 | * Example: [[1,2,3],[4,5,6]] becomes [1,2,3,4,5,6] 285 | */ 286 | toArray(): T[]; 287 | } 288 | 289 | interface VBArrayConstructor { 290 | new (safeArray: any): VBArray; 291 | new (safeArray: any): VBArray; 292 | } 293 | 294 | declare var VBArray: VBArrayConstructor; 295 | --------------------------------------------------------------------------------