├── .gitignore ├── .npmignore ├── .vscode └── settings.json ├── LICENSE.md ├── README.md ├── gulpfile.js ├── lib ├── lib-es6-ts.d.ts ├── lib-es6-ts.js ├── lib-ts.d.ts ├── lib-ts.js ├── typescriptServices.d.ts └── typescriptServices.js ├── package.json ├── src ├── languageFeatures.ts ├── mode.ts ├── monaco.contribution.ts ├── tokenization.ts ├── typescript.ts ├── worker.ts └── workerManager.ts ├── test ├── all.js ├── assert.d.ts ├── mocha.d.ts ├── mocha.opts └── tokenization.test.ts └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules/ 2 | /out/ 3 | /release/ 4 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | /.vscode/ 2 | /lib/ 3 | /out/ 4 | /src/ 5 | /test/ 6 | /gulpfile.js 7 | /tsconfig.json 8 | /.npmignore 9 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | // Place your settings in this file to overwrite default and user settings. 2 | { 3 | "files.trimTrailingWhitespace": true, 4 | "search.exclude": { 5 | "**/node_modules": true, 6 | "**/release": true, 7 | "**/out": true 8 | } 9 | } -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) Microsoft Corporation 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## THIS REPOSITORY HAS MOVED TO https://github.com/Microsoft/monaco-typescript 2 | -------------------------------------------------------------------------------- /gulpfile.js: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | var gulp = require('gulp'); 7 | var tsb = require('gulp-tsb'); 8 | var assign = require('object-assign'); 9 | var fs = require('fs'); 10 | var path = require('path'); 11 | var merge = require('merge-stream'); 12 | var rjs = require('gulp-requirejs'); 13 | var uglify = require('gulp-uglify'); 14 | var rimraf = require('rimraf'); 15 | var es = require('event-stream'); 16 | 17 | var TYPESCRIPT_LIB_SOURCE = path.join(__dirname, 'node_modules', 'typescript', 'lib'); 18 | var TYPESCRIPT_LIB_DESTINATION = path.join(__dirname, 'lib'); 19 | 20 | gulp.task('clean-release', function(cb) { rimraf('release', { maxBusyTries: 1 }, cb); }); 21 | gulp.task('release', ['clean-release','compile'], function() { 22 | 23 | var sha1 = getGitVersion(__dirname); 24 | var semver = require('./package.json').version; 25 | var headerVersion = semver + '(' + sha1 + ')'; 26 | 27 | var BUNDLED_FILE_HEADER = [ 28 | '/*!-----------------------------------------------------------------------------', 29 | ' * Copyright (c) Microsoft Corporation. All rights reserved.', 30 | ' * monaco-typescript version: ' + headerVersion, 31 | ' * Released under the MIT license', 32 | ' * https://github.com/Microsoft/monaco-typescript/blob/master/LICENSE.md', 33 | ' *-----------------------------------------------------------------------------*/', 34 | '' 35 | ].join('\n'); 36 | 37 | function bundleOne(moduleId, exclude) { 38 | return rjs({ 39 | baseUrl: '/out/', 40 | name: 'vs/language/typescript/' + moduleId, 41 | out: moduleId + '.js', 42 | exclude: exclude, 43 | paths: { 44 | 'vs/language/typescript': __dirname + '/out' 45 | } 46 | }) 47 | } 48 | 49 | return merge( 50 | bundleOne('src/monaco.contribution'), 51 | bundleOne('lib/typescriptServices'), 52 | bundleOne('src/mode', ['vs/language/typescript/lib/typescriptServices']), 53 | bundleOne('src/worker', ['vs/language/typescript/lib/typescriptServices']) 54 | ) 55 | .pipe(uglify({ 56 | preserveComments: 'some' 57 | })) 58 | .pipe(es.through(function(data) { 59 | data.contents = new Buffer( 60 | BUNDLED_FILE_HEADER 61 | + data.contents.toString() 62 | ); 63 | this.emit('data', data); 64 | })) 65 | .pipe(gulp.dest('./release/')); 66 | }); 67 | 68 | 69 | var compilation = tsb.create(assign({ verbose: true }, require('./tsconfig.json').compilerOptions)); 70 | 71 | var tsSources = require('./tsconfig.json').filesGlob; 72 | 73 | function compileTask() { 74 | return merge( 75 | gulp.src('lib/*.js', { base: '.' }), 76 | gulp.src(tsSources).pipe(compilation()) 77 | ) 78 | .pipe(gulp.dest('out')); 79 | } 80 | 81 | gulp.task('clean-out', function(cb) { rimraf('out', { maxBusyTries: 1 }, cb); }); 82 | gulp.task('compile', ['clean-out'], compileTask); 83 | gulp.task('compile-without-clean', compileTask); 84 | gulp.task('watch', ['compile'], function() { 85 | gulp.watch(tsSources, ['compile-without-clean']); 86 | }); 87 | 88 | 89 | /** 90 | * Import files from TypeScript's dist 91 | */ 92 | gulp.task('import-typescript', function() { 93 | try { 94 | fs.statSync(TYPESCRIPT_LIB_DESTINATION); 95 | } catch (err) { 96 | fs.mkdirSync(TYPESCRIPT_LIB_DESTINATION); 97 | } 98 | importLibDeclarationFile('lib.d.ts'); 99 | importLibDeclarationFile('lib.es6.d.ts'); 100 | 101 | var tsServices = fs.readFileSync(path.join(TYPESCRIPT_LIB_SOURCE, 'typescriptServices.js')).toString(); 102 | tsServices += 103 | ` 104 | // MONACOCHANGE 105 | define([], function() { return ts; }); 106 | // END MONACOCHANGE 107 | `; 108 | fs.writeFileSync(path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServices.js'), tsServices); 109 | 110 | var dtsServices = fs.readFileSync(path.join(TYPESCRIPT_LIB_SOURCE, 'typescriptServices.d.ts')).toString(); 111 | dtsServices += 112 | ` 113 | // MONACOCHANGE 114 | export = ts; 115 | // END MONACOCHANGE 116 | `; 117 | fs.writeFileSync(path.join(TYPESCRIPT_LIB_DESTINATION, 'typescriptServices.d.ts'), dtsServices); 118 | }); 119 | 120 | /** 121 | * Import a lib*.d.ts file from TypeScript's dist 122 | */ 123 | function importLibDeclarationFile(name) { 124 | var dstName = name.replace(/\.d\.ts$/, '').replace(/\./g, '-') + '-ts'; 125 | var srcPath = path.join(TYPESCRIPT_LIB_SOURCE, name); 126 | 127 | var contents = fs.readFileSync(srcPath).toString(); 128 | 129 | var dstPath1 = path.join(TYPESCRIPT_LIB_DESTINATION, dstName + '.js'); 130 | fs.writeFileSync(dstPath1, 131 | `/*--------------------------------------------------------------------------------------------- 132 | * Copyright (c) Microsoft Corporation. All rights reserved. 133 | * Licensed under the MIT License. See License.txt in the project root for license information. 134 | *--------------------------------------------------------------------------------------------*/ 135 | 136 | // This is a generated file from ${name} 137 | 138 | define([], function() { return { contents: "${escapeText(contents)}"}; }); 139 | 140 | `); 141 | 142 | var dstPath2 = path.join(TYPESCRIPT_LIB_DESTINATION, dstName + '.d.ts'); 143 | fs.writeFileSync(dstPath2, 144 | `/*--------------------------------------------------------------------------------------------- 145 | * Copyright (c) Microsoft Corporation. All rights reserved. 146 | * Licensed under the MIT License. See License.txt in the project root for license information. 147 | *--------------------------------------------------------------------------------------------*/ 148 | 149 | export declare var contents: string; 150 | `); 151 | } 152 | 153 | /** 154 | * Escape text such that it can be used in a javascript string enclosed by double quotes (") 155 | */ 156 | function escapeText(text) { 157 | // http://www.javascriptkit.com/jsref/escapesequence.shtml 158 | // \b Backspace. 159 | // \f Form feed. 160 | // \n Newline. 161 | // \O Nul character. 162 | // \r Carriage return. 163 | // \t Horizontal tab. 164 | // \v Vertical tab. 165 | // \' Single quote or apostrophe. 166 | // \" Double quote. 167 | // \\ Backslash. 168 | // \ddd The Latin-1 character specified by the three octal digits between 0 and 377. ie, copyright symbol is \251. 169 | // \xdd The Latin-1 character specified by the two hexadecimal digits dd between 00 and FF. ie, copyright symbol is \xA9. 170 | // \udddd The Unicode character specified by the four hexadecimal digits dddd. ie, copyright symbol is \u00A9. 171 | var _backspace = '\b'.charCodeAt(0); 172 | var _formFeed = '\f'.charCodeAt(0); 173 | var _newLine = '\n'.charCodeAt(0); 174 | var _nullChar = 0; 175 | var _carriageReturn = '\r'.charCodeAt(0); 176 | var _tab = '\t'.charCodeAt(0); 177 | var _verticalTab = '\v'.charCodeAt(0); 178 | var _backslash = '\\'.charCodeAt(0); 179 | var _doubleQuote = '"'.charCodeAt(0); 180 | 181 | var startPos = 0, chrCode, replaceWith = null, resultPieces = []; 182 | 183 | for (var i = 0, len = text.length; i < len; i++) { 184 | chrCode = text.charCodeAt(i); 185 | switch (chrCode) { 186 | case _backspace: 187 | replaceWith = '\\b'; 188 | break; 189 | case _formFeed: 190 | replaceWith = '\\f'; 191 | break; 192 | case _newLine: 193 | replaceWith = '\\n'; 194 | break; 195 | case _nullChar: 196 | replaceWith = '\\0'; 197 | break; 198 | case _carriageReturn: 199 | replaceWith = '\\r'; 200 | break; 201 | case _tab: 202 | replaceWith = '\\t'; 203 | break; 204 | case _verticalTab: 205 | replaceWith = '\\v'; 206 | break; 207 | case _backslash: 208 | replaceWith = '\\\\'; 209 | break; 210 | case _doubleQuote: 211 | replaceWith = '\\"'; 212 | break; 213 | } 214 | if (replaceWith !== null) { 215 | resultPieces.push(text.substring(startPos, i)); 216 | resultPieces.push(replaceWith); 217 | startPos = i + 1; 218 | replaceWith = null; 219 | } 220 | } 221 | resultPieces.push(text.substring(startPos, len)); 222 | return resultPieces.join(''); 223 | } 224 | 225 | function getGitVersion(repo) { 226 | var git = path.join(repo, '.git'); 227 | var headPath = path.join(git, 'HEAD'); 228 | var head; 229 | 230 | try { 231 | head = fs.readFileSync(headPath, 'utf8').trim(); 232 | } catch (e) { 233 | return void 0; 234 | } 235 | 236 | if (/^[0-9a-f]{40}$/i.test(head)) { 237 | return head; 238 | } 239 | 240 | var refMatch = /^ref: (.*)$/.exec(head); 241 | 242 | if (!refMatch) { 243 | return void 0; 244 | } 245 | 246 | var ref = refMatch[1]; 247 | var refPath = path.join(git, ref); 248 | 249 | try { 250 | return fs.readFileSync(refPath, 'utf8').trim(); 251 | } catch (e) { 252 | // noop 253 | } 254 | 255 | var packedRefsPath = path.join(git, 'packed-refs'); 256 | var refsRaw; 257 | 258 | try { 259 | refsRaw = fs.readFileSync(packedRefsPath, 'utf8').trim(); 260 | } catch (e) { 261 | return void 0; 262 | } 263 | 264 | var refsRegex = /^([0-9a-f]{40})\s+(.+)$/gm; 265 | var refsMatch; 266 | var refs = {}; 267 | 268 | while (refsMatch = refsRegex.exec(refsRaw)) { 269 | refs[refsMatch[2]] = refsMatch[1]; 270 | } 271 | 272 | return refs[ref]; 273 | } -------------------------------------------------------------------------------- /lib/lib-es6-ts.d.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | export declare var contents: string; 7 | -------------------------------------------------------------------------------- /lib/lib-ts.d.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | export declare var contents: string; 7 | -------------------------------------------------------------------------------- /lib/typescriptServices.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 | declare namespace ts { 17 | interface Map { 18 | [index: string]: T; 19 | } 20 | type Path = string & { 21 | __pathBrand: any; 22 | }; 23 | interface FileMap { 24 | get(fileName: Path): T; 25 | set(fileName: Path, value: T): void; 26 | contains(fileName: Path): boolean; 27 | remove(fileName: Path): void; 28 | forEachValue(f: (key: Path, v: T) => void): void; 29 | clear(): void; 30 | } 31 | interface TextRange { 32 | pos: number; 33 | end: number; 34 | } 35 | enum SyntaxKind { 36 | Unknown = 0, 37 | EndOfFileToken = 1, 38 | SingleLineCommentTrivia = 2, 39 | MultiLineCommentTrivia = 3, 40 | NewLineTrivia = 4, 41 | WhitespaceTrivia = 5, 42 | ShebangTrivia = 6, 43 | ConflictMarkerTrivia = 7, 44 | NumericLiteral = 8, 45 | StringLiteral = 9, 46 | RegularExpressionLiteral = 10, 47 | NoSubstitutionTemplateLiteral = 11, 48 | TemplateHead = 12, 49 | TemplateMiddle = 13, 50 | TemplateTail = 14, 51 | OpenBraceToken = 15, 52 | CloseBraceToken = 16, 53 | OpenParenToken = 17, 54 | CloseParenToken = 18, 55 | OpenBracketToken = 19, 56 | CloseBracketToken = 20, 57 | DotToken = 21, 58 | DotDotDotToken = 22, 59 | SemicolonToken = 23, 60 | CommaToken = 24, 61 | LessThanToken = 25, 62 | LessThanSlashToken = 26, 63 | GreaterThanToken = 27, 64 | LessThanEqualsToken = 28, 65 | GreaterThanEqualsToken = 29, 66 | EqualsEqualsToken = 30, 67 | ExclamationEqualsToken = 31, 68 | EqualsEqualsEqualsToken = 32, 69 | ExclamationEqualsEqualsToken = 33, 70 | EqualsGreaterThanToken = 34, 71 | PlusToken = 35, 72 | MinusToken = 36, 73 | AsteriskToken = 37, 74 | AsteriskAsteriskToken = 38, 75 | SlashToken = 39, 76 | PercentToken = 40, 77 | PlusPlusToken = 41, 78 | MinusMinusToken = 42, 79 | LessThanLessThanToken = 43, 80 | GreaterThanGreaterThanToken = 44, 81 | GreaterThanGreaterThanGreaterThanToken = 45, 82 | AmpersandToken = 46, 83 | BarToken = 47, 84 | CaretToken = 48, 85 | ExclamationToken = 49, 86 | TildeToken = 50, 87 | AmpersandAmpersandToken = 51, 88 | BarBarToken = 52, 89 | QuestionToken = 53, 90 | ColonToken = 54, 91 | AtToken = 55, 92 | EqualsToken = 56, 93 | PlusEqualsToken = 57, 94 | MinusEqualsToken = 58, 95 | AsteriskEqualsToken = 59, 96 | AsteriskAsteriskEqualsToken = 60, 97 | SlashEqualsToken = 61, 98 | PercentEqualsToken = 62, 99 | LessThanLessThanEqualsToken = 63, 100 | GreaterThanGreaterThanEqualsToken = 64, 101 | GreaterThanGreaterThanGreaterThanEqualsToken = 65, 102 | AmpersandEqualsToken = 66, 103 | BarEqualsToken = 67, 104 | CaretEqualsToken = 68, 105 | Identifier = 69, 106 | BreakKeyword = 70, 107 | CaseKeyword = 71, 108 | CatchKeyword = 72, 109 | ClassKeyword = 73, 110 | ConstKeyword = 74, 111 | ContinueKeyword = 75, 112 | DebuggerKeyword = 76, 113 | DefaultKeyword = 77, 114 | DeleteKeyword = 78, 115 | DoKeyword = 79, 116 | ElseKeyword = 80, 117 | EnumKeyword = 81, 118 | ExportKeyword = 82, 119 | ExtendsKeyword = 83, 120 | FalseKeyword = 84, 121 | FinallyKeyword = 85, 122 | ForKeyword = 86, 123 | FunctionKeyword = 87, 124 | IfKeyword = 88, 125 | ImportKeyword = 89, 126 | InKeyword = 90, 127 | InstanceOfKeyword = 91, 128 | NewKeyword = 92, 129 | NullKeyword = 93, 130 | ReturnKeyword = 94, 131 | SuperKeyword = 95, 132 | SwitchKeyword = 96, 133 | ThisKeyword = 97, 134 | ThrowKeyword = 98, 135 | TrueKeyword = 99, 136 | TryKeyword = 100, 137 | TypeOfKeyword = 101, 138 | VarKeyword = 102, 139 | VoidKeyword = 103, 140 | WhileKeyword = 104, 141 | WithKeyword = 105, 142 | ImplementsKeyword = 106, 143 | InterfaceKeyword = 107, 144 | LetKeyword = 108, 145 | PackageKeyword = 109, 146 | PrivateKeyword = 110, 147 | ProtectedKeyword = 111, 148 | PublicKeyword = 112, 149 | StaticKeyword = 113, 150 | YieldKeyword = 114, 151 | AbstractKeyword = 115, 152 | AsKeyword = 116, 153 | AnyKeyword = 117, 154 | AsyncKeyword = 118, 155 | AwaitKeyword = 119, 156 | BooleanKeyword = 120, 157 | ConstructorKeyword = 121, 158 | DeclareKeyword = 122, 159 | GetKeyword = 123, 160 | IsKeyword = 124, 161 | ModuleKeyword = 125, 162 | NamespaceKeyword = 126, 163 | RequireKeyword = 127, 164 | NumberKeyword = 128, 165 | SetKeyword = 129, 166 | StringKeyword = 130, 167 | SymbolKeyword = 131, 168 | TypeKeyword = 132, 169 | FromKeyword = 133, 170 | GlobalKeyword = 134, 171 | OfKeyword = 135, 172 | QualifiedName = 136, 173 | ComputedPropertyName = 137, 174 | TypeParameter = 138, 175 | Parameter = 139, 176 | Decorator = 140, 177 | PropertySignature = 141, 178 | PropertyDeclaration = 142, 179 | MethodSignature = 143, 180 | MethodDeclaration = 144, 181 | Constructor = 145, 182 | GetAccessor = 146, 183 | SetAccessor = 147, 184 | CallSignature = 148, 185 | ConstructSignature = 149, 186 | IndexSignature = 150, 187 | TypePredicate = 151, 188 | TypeReference = 152, 189 | FunctionType = 153, 190 | ConstructorType = 154, 191 | TypeQuery = 155, 192 | TypeLiteral = 156, 193 | ArrayType = 157, 194 | TupleType = 158, 195 | UnionType = 159, 196 | IntersectionType = 160, 197 | ParenthesizedType = 161, 198 | ThisType = 162, 199 | StringLiteralType = 163, 200 | ObjectBindingPattern = 164, 201 | ArrayBindingPattern = 165, 202 | BindingElement = 166, 203 | ArrayLiteralExpression = 167, 204 | ObjectLiteralExpression = 168, 205 | PropertyAccessExpression = 169, 206 | ElementAccessExpression = 170, 207 | CallExpression = 171, 208 | NewExpression = 172, 209 | TaggedTemplateExpression = 173, 210 | TypeAssertionExpression = 174, 211 | ParenthesizedExpression = 175, 212 | FunctionExpression = 176, 213 | ArrowFunction = 177, 214 | DeleteExpression = 178, 215 | TypeOfExpression = 179, 216 | VoidExpression = 180, 217 | AwaitExpression = 181, 218 | PrefixUnaryExpression = 182, 219 | PostfixUnaryExpression = 183, 220 | BinaryExpression = 184, 221 | ConditionalExpression = 185, 222 | TemplateExpression = 186, 223 | YieldExpression = 187, 224 | SpreadElementExpression = 188, 225 | ClassExpression = 189, 226 | OmittedExpression = 190, 227 | ExpressionWithTypeArguments = 191, 228 | AsExpression = 192, 229 | TemplateSpan = 193, 230 | SemicolonClassElement = 194, 231 | Block = 195, 232 | VariableStatement = 196, 233 | EmptyStatement = 197, 234 | ExpressionStatement = 198, 235 | IfStatement = 199, 236 | DoStatement = 200, 237 | WhileStatement = 201, 238 | ForStatement = 202, 239 | ForInStatement = 203, 240 | ForOfStatement = 204, 241 | ContinueStatement = 205, 242 | BreakStatement = 206, 243 | ReturnStatement = 207, 244 | WithStatement = 208, 245 | SwitchStatement = 209, 246 | LabeledStatement = 210, 247 | ThrowStatement = 211, 248 | TryStatement = 212, 249 | DebuggerStatement = 213, 250 | VariableDeclaration = 214, 251 | VariableDeclarationList = 215, 252 | FunctionDeclaration = 216, 253 | ClassDeclaration = 217, 254 | InterfaceDeclaration = 218, 255 | TypeAliasDeclaration = 219, 256 | EnumDeclaration = 220, 257 | ModuleDeclaration = 221, 258 | ModuleBlock = 222, 259 | CaseBlock = 223, 260 | ImportEqualsDeclaration = 224, 261 | ImportDeclaration = 225, 262 | ImportClause = 226, 263 | NamespaceImport = 227, 264 | NamedImports = 228, 265 | ImportSpecifier = 229, 266 | ExportAssignment = 230, 267 | ExportDeclaration = 231, 268 | NamedExports = 232, 269 | ExportSpecifier = 233, 270 | MissingDeclaration = 234, 271 | ExternalModuleReference = 235, 272 | JsxElement = 236, 273 | JsxSelfClosingElement = 237, 274 | JsxOpeningElement = 238, 275 | JsxText = 239, 276 | JsxClosingElement = 240, 277 | JsxAttribute = 241, 278 | JsxSpreadAttribute = 242, 279 | JsxExpression = 243, 280 | CaseClause = 244, 281 | DefaultClause = 245, 282 | HeritageClause = 246, 283 | CatchClause = 247, 284 | PropertyAssignment = 248, 285 | ShorthandPropertyAssignment = 249, 286 | EnumMember = 250, 287 | SourceFile = 251, 288 | JSDocTypeExpression = 252, 289 | JSDocAllType = 253, 290 | JSDocUnknownType = 254, 291 | JSDocArrayType = 255, 292 | JSDocUnionType = 256, 293 | JSDocTupleType = 257, 294 | JSDocNullableType = 258, 295 | JSDocNonNullableType = 259, 296 | JSDocRecordType = 260, 297 | JSDocRecordMember = 261, 298 | JSDocTypeReference = 262, 299 | JSDocOptionalType = 263, 300 | JSDocFunctionType = 264, 301 | JSDocVariadicType = 265, 302 | JSDocConstructorType = 266, 303 | JSDocThisType = 267, 304 | JSDocComment = 268, 305 | JSDocTag = 269, 306 | JSDocParameterTag = 270, 307 | JSDocReturnTag = 271, 308 | JSDocTypeTag = 272, 309 | JSDocTemplateTag = 273, 310 | SyntaxList = 274, 311 | Count = 275, 312 | FirstAssignment = 56, 313 | LastAssignment = 68, 314 | FirstReservedWord = 70, 315 | LastReservedWord = 105, 316 | FirstKeyword = 70, 317 | LastKeyword = 135, 318 | FirstFutureReservedWord = 106, 319 | LastFutureReservedWord = 114, 320 | FirstTypeNode = 151, 321 | LastTypeNode = 163, 322 | FirstPunctuation = 15, 323 | LastPunctuation = 68, 324 | FirstToken = 0, 325 | LastToken = 135, 326 | FirstTriviaToken = 2, 327 | LastTriviaToken = 7, 328 | FirstLiteralToken = 8, 329 | LastLiteralToken = 11, 330 | FirstTemplateToken = 11, 331 | LastTemplateToken = 14, 332 | FirstBinaryOperator = 25, 333 | LastBinaryOperator = 68, 334 | FirstNode = 136, 335 | } 336 | enum NodeFlags { 337 | None = 0, 338 | Export = 2, 339 | Ambient = 4, 340 | Public = 8, 341 | Private = 16, 342 | Protected = 32, 343 | Static = 64, 344 | Abstract = 128, 345 | Async = 256, 346 | Default = 512, 347 | MultiLine = 1024, 348 | Synthetic = 2048, 349 | DeclarationFile = 4096, 350 | Let = 8192, 351 | Const = 16384, 352 | OctalLiteral = 32768, 353 | Namespace = 65536, 354 | ExportContext = 131072, 355 | ContainsThis = 262144, 356 | HasImplicitReturn = 524288, 357 | HasExplicitReturn = 1048576, 358 | GlobalAugmentation = 2097152, 359 | HasClassExtends = 4194304, 360 | HasDecorators = 8388608, 361 | HasParamDecorators = 16777216, 362 | HasAsyncFunctions = 33554432, 363 | HasJsxSpreadAttribute = 1073741824, 364 | Modifier = 1022, 365 | AccessibilityModifier = 56, 366 | BlockScoped = 24576, 367 | ReachabilityCheckFlags = 1572864, 368 | EmitHelperFlags = 62914560, 369 | } 370 | enum JsxFlags { 371 | None = 0, 372 | /** An element from a named property of the JSX.IntrinsicElements interface */ 373 | IntrinsicNamedElement = 1, 374 | /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ 375 | IntrinsicIndexedElement = 2, 376 | /** An element backed by a class, class-like, or function value */ 377 | ValueElement = 4, 378 | /** Element resolution failed */ 379 | UnknownElement = 16, 380 | IntrinsicElement = 3, 381 | } 382 | interface Node extends TextRange { 383 | kind: SyntaxKind; 384 | flags: NodeFlags; 385 | decorators?: NodeArray; 386 | modifiers?: ModifiersArray; 387 | parent?: Node; 388 | } 389 | interface NodeArray extends Array, TextRange { 390 | hasTrailingComma?: boolean; 391 | } 392 | interface ModifiersArray extends NodeArray { 393 | flags: number; 394 | } 395 | interface Modifier extends Node { 396 | } 397 | interface Identifier extends PrimaryExpression { 398 | text: string; 399 | originalKeywordKind?: SyntaxKind; 400 | } 401 | interface QualifiedName extends Node { 402 | left: EntityName; 403 | right: Identifier; 404 | } 405 | type EntityName = Identifier | QualifiedName; 406 | type PropertyName = Identifier | LiteralExpression | ComputedPropertyName; 407 | type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName | BindingPattern; 408 | interface Declaration extends Node { 409 | _declarationBrand: any; 410 | name?: DeclarationName; 411 | } 412 | interface DeclarationStatement extends Declaration, Statement { 413 | name?: Identifier; 414 | } 415 | interface ComputedPropertyName extends Node { 416 | expression: Expression; 417 | } 418 | interface Decorator extends Node { 419 | expression: LeftHandSideExpression; 420 | } 421 | interface TypeParameterDeclaration extends Declaration { 422 | name: Identifier; 423 | constraint?: TypeNode; 424 | expression?: Expression; 425 | } 426 | interface SignatureDeclaration extends Declaration { 427 | name?: PropertyName; 428 | typeParameters?: NodeArray; 429 | parameters: NodeArray; 430 | type?: TypeNode; 431 | } 432 | interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { 433 | } 434 | interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { 435 | } 436 | interface VariableDeclaration extends Declaration { 437 | parent?: VariableDeclarationList; 438 | name: Identifier | BindingPattern; 439 | type?: TypeNode; 440 | initializer?: Expression; 441 | } 442 | interface VariableDeclarationList extends Node { 443 | declarations: NodeArray; 444 | } 445 | interface ParameterDeclaration extends Declaration { 446 | dotDotDotToken?: Node; 447 | name: Identifier | BindingPattern; 448 | questionToken?: Node; 449 | type?: TypeNode; 450 | initializer?: Expression; 451 | } 452 | interface BindingElement extends Declaration { 453 | propertyName?: PropertyName; 454 | dotDotDotToken?: Node; 455 | name: Identifier | BindingPattern; 456 | initializer?: Expression; 457 | } 458 | interface PropertySignature extends TypeElement { 459 | name: PropertyName; 460 | questionToken?: Node; 461 | type?: TypeNode; 462 | initializer?: Expression; 463 | } 464 | interface PropertyDeclaration extends ClassElement { 465 | questionToken?: Node; 466 | name: PropertyName; 467 | type?: TypeNode; 468 | initializer?: Expression; 469 | } 470 | interface ObjectLiteralElement extends Declaration { 471 | _objectLiteralBrandBrand: any; 472 | name?: PropertyName; 473 | } 474 | interface PropertyAssignment extends ObjectLiteralElement { 475 | _propertyAssignmentBrand: any; 476 | name: PropertyName; 477 | questionToken?: Node; 478 | initializer: Expression; 479 | } 480 | interface ShorthandPropertyAssignment extends ObjectLiteralElement { 481 | name: Identifier; 482 | questionToken?: Node; 483 | equalsToken?: Node; 484 | objectAssignmentInitializer?: Expression; 485 | } 486 | interface VariableLikeDeclaration extends Declaration { 487 | propertyName?: PropertyName; 488 | dotDotDotToken?: Node; 489 | name: DeclarationName; 490 | questionToken?: Node; 491 | type?: TypeNode; 492 | initializer?: Expression; 493 | } 494 | interface PropertyLikeDeclaration extends Declaration { 495 | name: PropertyName; 496 | } 497 | interface BindingPattern extends Node { 498 | elements: NodeArray; 499 | } 500 | interface ObjectBindingPattern extends BindingPattern { 501 | } 502 | interface ArrayBindingPattern extends BindingPattern { 503 | } 504 | /** 505 | * Several node kinds share function-like features such as a signature, 506 | * a name, and a body. These nodes should extend FunctionLikeDeclaration. 507 | * Examples: 508 | * - FunctionDeclaration 509 | * - MethodDeclaration 510 | * - AccessorDeclaration 511 | */ 512 | interface FunctionLikeDeclaration extends SignatureDeclaration { 513 | _functionLikeDeclarationBrand: any; 514 | asteriskToken?: Node; 515 | questionToken?: Node; 516 | body?: Block | Expression; 517 | } 518 | interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement { 519 | name?: Identifier; 520 | body?: FunctionBody; 521 | } 522 | interface MethodSignature extends SignatureDeclaration, TypeElement { 523 | name: PropertyName; 524 | } 525 | interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { 526 | name: PropertyName; 527 | body?: FunctionBody; 528 | } 529 | interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { 530 | body?: FunctionBody; 531 | } 532 | interface SemicolonClassElement extends ClassElement { 533 | _semicolonClassElementBrand: any; 534 | } 535 | interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { 536 | _accessorDeclarationBrand: any; 537 | name: PropertyName; 538 | body: FunctionBody; 539 | } 540 | interface GetAccessorDeclaration extends AccessorDeclaration { 541 | } 542 | interface SetAccessorDeclaration extends AccessorDeclaration { 543 | } 544 | interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { 545 | _indexSignatureDeclarationBrand: any; 546 | } 547 | interface TypeNode extends Node { 548 | _typeNodeBrand: any; 549 | } 550 | interface ThisTypeNode extends TypeNode { 551 | _thisTypeNodeBrand: any; 552 | } 553 | interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { 554 | _functionOrConstructorTypeNodeBrand: any; 555 | } 556 | interface FunctionTypeNode extends FunctionOrConstructorTypeNode { 557 | } 558 | interface ConstructorTypeNode extends FunctionOrConstructorTypeNode { 559 | } 560 | interface TypeReferenceNode extends TypeNode { 561 | typeName: EntityName; 562 | typeArguments?: NodeArray; 563 | } 564 | interface TypePredicateNode extends TypeNode { 565 | parameterName: Identifier | ThisTypeNode; 566 | type: TypeNode; 567 | } 568 | interface TypeQueryNode extends TypeNode { 569 | exprName: EntityName; 570 | } 571 | interface TypeLiteralNode extends TypeNode, Declaration { 572 | members: NodeArray; 573 | } 574 | interface ArrayTypeNode extends TypeNode { 575 | elementType: TypeNode; 576 | } 577 | interface TupleTypeNode extends TypeNode { 578 | elementTypes: NodeArray; 579 | } 580 | interface UnionOrIntersectionTypeNode extends TypeNode { 581 | types: NodeArray; 582 | } 583 | interface UnionTypeNode extends UnionOrIntersectionTypeNode { 584 | } 585 | interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { 586 | } 587 | interface ParenthesizedTypeNode extends TypeNode { 588 | type: TypeNode; 589 | } 590 | interface StringLiteralTypeNode extends LiteralLikeNode, TypeNode { 591 | _stringLiteralTypeBrand: any; 592 | } 593 | interface StringLiteral extends LiteralExpression { 594 | _stringLiteralBrand: any; 595 | } 596 | interface Expression extends Node { 597 | _expressionBrand: any; 598 | contextualType?: Type; 599 | } 600 | interface OmittedExpression extends Expression { 601 | } 602 | interface UnaryExpression extends Expression { 603 | _unaryExpressionBrand: any; 604 | } 605 | interface IncrementExpression extends UnaryExpression { 606 | _incrementExpressionBrand: any; 607 | } 608 | interface PrefixUnaryExpression extends IncrementExpression { 609 | operator: SyntaxKind; 610 | operand: UnaryExpression; 611 | } 612 | interface PostfixUnaryExpression extends IncrementExpression { 613 | operand: LeftHandSideExpression; 614 | operator: SyntaxKind; 615 | } 616 | interface PostfixExpression extends UnaryExpression { 617 | _postfixExpressionBrand: any; 618 | } 619 | interface LeftHandSideExpression extends IncrementExpression { 620 | _leftHandSideExpressionBrand: any; 621 | } 622 | interface MemberExpression extends LeftHandSideExpression { 623 | _memberExpressionBrand: any; 624 | } 625 | interface PrimaryExpression extends MemberExpression { 626 | _primaryExpressionBrand: any; 627 | } 628 | interface DeleteExpression extends UnaryExpression { 629 | expression: UnaryExpression; 630 | } 631 | interface TypeOfExpression extends UnaryExpression { 632 | expression: UnaryExpression; 633 | } 634 | interface VoidExpression extends UnaryExpression { 635 | expression: UnaryExpression; 636 | } 637 | interface AwaitExpression extends UnaryExpression { 638 | expression: UnaryExpression; 639 | } 640 | interface YieldExpression extends Expression { 641 | asteriskToken?: Node; 642 | expression?: Expression; 643 | } 644 | interface BinaryExpression extends Expression, Declaration { 645 | left: Expression; 646 | operatorToken: Node; 647 | right: Expression; 648 | } 649 | interface ConditionalExpression extends Expression { 650 | condition: Expression; 651 | questionToken: Node; 652 | whenTrue: Expression; 653 | colonToken: Node; 654 | whenFalse: Expression; 655 | } 656 | type FunctionBody = Block; 657 | type ConciseBody = FunctionBody | Expression; 658 | interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { 659 | name?: Identifier; 660 | body: FunctionBody; 661 | } 662 | interface ArrowFunction extends Expression, FunctionLikeDeclaration { 663 | equalsGreaterThanToken: Node; 664 | body: ConciseBody; 665 | } 666 | interface LiteralLikeNode extends Node { 667 | text: string; 668 | isUnterminated?: boolean; 669 | hasExtendedUnicodeEscape?: boolean; 670 | } 671 | interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { 672 | _literalExpressionBrand: any; 673 | } 674 | interface TemplateLiteralFragment extends LiteralLikeNode { 675 | _templateLiteralFragmentBrand: any; 676 | } 677 | interface TemplateExpression extends PrimaryExpression { 678 | head: TemplateLiteralFragment; 679 | templateSpans: NodeArray; 680 | } 681 | interface TemplateSpan extends Node { 682 | expression: Expression; 683 | literal: TemplateLiteralFragment; 684 | } 685 | interface ParenthesizedExpression extends PrimaryExpression { 686 | expression: Expression; 687 | } 688 | interface ArrayLiteralExpression extends PrimaryExpression { 689 | elements: NodeArray; 690 | } 691 | interface SpreadElementExpression extends Expression { 692 | expression: Expression; 693 | } 694 | interface ObjectLiteralExpression extends PrimaryExpression, Declaration { 695 | properties: NodeArray; 696 | } 697 | interface PropertyAccessExpression extends MemberExpression, Declaration { 698 | expression: LeftHandSideExpression; 699 | dotToken: Node; 700 | name: Identifier; 701 | } 702 | interface ElementAccessExpression extends MemberExpression { 703 | expression: LeftHandSideExpression; 704 | argumentExpression?: Expression; 705 | } 706 | interface CallExpression extends LeftHandSideExpression, Declaration { 707 | expression: LeftHandSideExpression; 708 | typeArguments?: NodeArray; 709 | arguments: NodeArray; 710 | } 711 | interface ExpressionWithTypeArguments extends TypeNode { 712 | expression: LeftHandSideExpression; 713 | typeArguments?: NodeArray; 714 | } 715 | interface NewExpression extends CallExpression, PrimaryExpression { 716 | } 717 | interface TaggedTemplateExpression extends MemberExpression { 718 | tag: LeftHandSideExpression; 719 | template: LiteralExpression | TemplateExpression; 720 | } 721 | type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; 722 | interface AsExpression extends Expression { 723 | expression: Expression; 724 | type: TypeNode; 725 | } 726 | interface TypeAssertion extends UnaryExpression { 727 | type: TypeNode; 728 | expression: UnaryExpression; 729 | } 730 | type AssertionExpression = TypeAssertion | AsExpression; 731 | interface JsxElement extends PrimaryExpression { 732 | openingElement: JsxOpeningElement; 733 | children: NodeArray; 734 | closingElement: JsxClosingElement; 735 | } 736 | interface JsxOpeningElement extends Expression { 737 | _openingElementBrand?: any; 738 | tagName: EntityName; 739 | attributes: NodeArray; 740 | } 741 | interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { 742 | _selfClosingElementBrand?: any; 743 | } 744 | type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; 745 | interface JsxAttribute extends Node { 746 | name: Identifier; 747 | initializer?: Expression; 748 | } 749 | interface JsxSpreadAttribute extends Node { 750 | expression: Expression; 751 | } 752 | interface JsxClosingElement extends Node { 753 | tagName: EntityName; 754 | } 755 | interface JsxExpression extends Expression { 756 | expression?: Expression; 757 | } 758 | interface JsxText extends Node { 759 | _jsxTextExpressionBrand: any; 760 | } 761 | type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; 762 | interface Statement extends Node { 763 | _statementBrand: any; 764 | } 765 | interface EmptyStatement extends Statement { 766 | } 767 | interface DebuggerStatement extends Statement { 768 | } 769 | interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement { 770 | name?: Identifier; 771 | } 772 | type BlockLike = SourceFile | Block | ModuleBlock | CaseClause; 773 | interface Block extends Statement { 774 | statements: NodeArray; 775 | } 776 | interface VariableStatement extends Statement { 777 | declarationList: VariableDeclarationList; 778 | } 779 | interface ExpressionStatement extends Statement { 780 | expression: Expression; 781 | } 782 | interface IfStatement extends Statement { 783 | expression: Expression; 784 | thenStatement: Statement; 785 | elseStatement?: Statement; 786 | } 787 | interface IterationStatement extends Statement { 788 | statement: Statement; 789 | } 790 | interface DoStatement extends IterationStatement { 791 | expression: Expression; 792 | } 793 | interface WhileStatement extends IterationStatement { 794 | expression: Expression; 795 | } 796 | interface ForStatement extends IterationStatement { 797 | initializer?: VariableDeclarationList | Expression; 798 | condition?: Expression; 799 | incrementor?: Expression; 800 | } 801 | interface ForInStatement extends IterationStatement { 802 | initializer: VariableDeclarationList | Expression; 803 | expression: Expression; 804 | } 805 | interface ForOfStatement extends IterationStatement { 806 | initializer: VariableDeclarationList | Expression; 807 | expression: Expression; 808 | } 809 | interface BreakStatement extends Statement { 810 | label?: Identifier; 811 | } 812 | interface ContinueStatement extends Statement { 813 | label?: Identifier; 814 | } 815 | type BreakOrContinueStatement = BreakStatement | ContinueStatement; 816 | interface ReturnStatement extends Statement { 817 | expression?: Expression; 818 | } 819 | interface WithStatement extends Statement { 820 | expression: Expression; 821 | statement: Statement; 822 | } 823 | interface SwitchStatement extends Statement { 824 | expression: Expression; 825 | caseBlock: CaseBlock; 826 | } 827 | interface CaseBlock extends Node { 828 | clauses: NodeArray; 829 | } 830 | interface CaseClause extends Node { 831 | expression: Expression; 832 | statements: NodeArray; 833 | } 834 | interface DefaultClause extends Node { 835 | statements: NodeArray; 836 | } 837 | type CaseOrDefaultClause = CaseClause | DefaultClause; 838 | interface LabeledStatement extends Statement { 839 | label: Identifier; 840 | statement: Statement; 841 | } 842 | interface ThrowStatement extends Statement { 843 | expression: Expression; 844 | } 845 | interface TryStatement extends Statement { 846 | tryBlock: Block; 847 | catchClause?: CatchClause; 848 | finallyBlock?: Block; 849 | } 850 | interface CatchClause extends Node { 851 | variableDeclaration: VariableDeclaration; 852 | block: Block; 853 | } 854 | interface ClassLikeDeclaration extends Declaration { 855 | name?: Identifier; 856 | typeParameters?: NodeArray; 857 | heritageClauses?: NodeArray; 858 | members: NodeArray; 859 | } 860 | interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement { 861 | name?: Identifier; 862 | } 863 | interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { 864 | } 865 | interface ClassElement extends Declaration { 866 | _classElementBrand: any; 867 | name?: PropertyName; 868 | } 869 | interface TypeElement extends Declaration { 870 | _typeElementBrand: any; 871 | name?: PropertyName; 872 | questionToken?: Node; 873 | } 874 | interface InterfaceDeclaration extends DeclarationStatement { 875 | name: Identifier; 876 | typeParameters?: NodeArray; 877 | heritageClauses?: NodeArray; 878 | members: NodeArray; 879 | } 880 | interface HeritageClause extends Node { 881 | token: SyntaxKind; 882 | types?: NodeArray; 883 | } 884 | interface TypeAliasDeclaration extends DeclarationStatement { 885 | name: Identifier; 886 | typeParameters?: NodeArray; 887 | type: TypeNode; 888 | } 889 | interface EnumMember extends Declaration { 890 | name: DeclarationName; 891 | initializer?: Expression; 892 | } 893 | interface EnumDeclaration extends DeclarationStatement { 894 | name: Identifier; 895 | members: NodeArray; 896 | } 897 | type ModuleBody = ModuleBlock | ModuleDeclaration; 898 | interface ModuleDeclaration extends DeclarationStatement { 899 | name: Identifier | LiteralExpression; 900 | body: ModuleBlock | ModuleDeclaration; 901 | } 902 | interface ModuleBlock extends Node, Statement { 903 | statements: NodeArray; 904 | } 905 | interface ImportEqualsDeclaration extends DeclarationStatement { 906 | name: Identifier; 907 | moduleReference: EntityName | ExternalModuleReference; 908 | } 909 | interface ExternalModuleReference extends Node { 910 | expression?: Expression; 911 | } 912 | interface ImportDeclaration extends Statement { 913 | importClause?: ImportClause; 914 | moduleSpecifier: Expression; 915 | } 916 | interface ImportClause extends Declaration { 917 | name?: Identifier; 918 | namedBindings?: NamespaceImport | NamedImports; 919 | } 920 | interface NamespaceImport extends Declaration { 921 | name: Identifier; 922 | } 923 | interface ExportDeclaration extends DeclarationStatement { 924 | exportClause?: NamedExports; 925 | moduleSpecifier?: Expression; 926 | } 927 | interface NamedImports extends Node { 928 | elements: NodeArray; 929 | } 930 | interface NamedExports extends Node { 931 | elements: NodeArray; 932 | } 933 | type NamedImportsOrExports = NamedImports | NamedExports; 934 | interface ImportSpecifier extends Declaration { 935 | propertyName?: Identifier; 936 | name: Identifier; 937 | } 938 | interface ExportSpecifier extends Declaration { 939 | propertyName?: Identifier; 940 | name: Identifier; 941 | } 942 | type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; 943 | interface ExportAssignment extends DeclarationStatement { 944 | isExportEquals?: boolean; 945 | expression: Expression; 946 | } 947 | interface FileReference extends TextRange { 948 | fileName: string; 949 | } 950 | interface CommentRange extends TextRange { 951 | hasTrailingNewLine?: boolean; 952 | kind: SyntaxKind; 953 | } 954 | interface JSDocTypeExpression extends Node { 955 | type: JSDocType; 956 | } 957 | interface JSDocType extends TypeNode { 958 | _jsDocTypeBrand: any; 959 | } 960 | interface JSDocAllType extends JSDocType { 961 | _JSDocAllTypeBrand: any; 962 | } 963 | interface JSDocUnknownType extends JSDocType { 964 | _JSDocUnknownTypeBrand: any; 965 | } 966 | interface JSDocArrayType extends JSDocType { 967 | elementType: JSDocType; 968 | } 969 | interface JSDocUnionType extends JSDocType { 970 | types: NodeArray; 971 | } 972 | interface JSDocTupleType extends JSDocType { 973 | types: NodeArray; 974 | } 975 | interface JSDocNonNullableType extends JSDocType { 976 | type: JSDocType; 977 | } 978 | interface JSDocNullableType extends JSDocType { 979 | type: JSDocType; 980 | } 981 | interface JSDocRecordType extends JSDocType, TypeLiteralNode { 982 | members: NodeArray; 983 | } 984 | interface JSDocTypeReference extends JSDocType { 985 | name: EntityName; 986 | typeArguments: NodeArray; 987 | } 988 | interface JSDocOptionalType extends JSDocType { 989 | type: JSDocType; 990 | } 991 | interface JSDocFunctionType extends JSDocType, SignatureDeclaration { 992 | parameters: NodeArray; 993 | type: JSDocType; 994 | } 995 | interface JSDocVariadicType extends JSDocType { 996 | type: JSDocType; 997 | } 998 | interface JSDocConstructorType extends JSDocType { 999 | type: JSDocType; 1000 | } 1001 | interface JSDocThisType extends JSDocType { 1002 | type: JSDocType; 1003 | } 1004 | type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; 1005 | interface JSDocRecordMember extends PropertySignature { 1006 | name: Identifier | LiteralExpression; 1007 | type?: JSDocType; 1008 | } 1009 | interface JSDocComment extends Node { 1010 | tags: NodeArray; 1011 | } 1012 | interface JSDocTag extends Node { 1013 | atToken: Node; 1014 | tagName: Identifier; 1015 | } 1016 | interface JSDocTemplateTag extends JSDocTag { 1017 | typeParameters: NodeArray; 1018 | } 1019 | interface JSDocReturnTag extends JSDocTag { 1020 | typeExpression: JSDocTypeExpression; 1021 | } 1022 | interface JSDocTypeTag extends JSDocTag { 1023 | typeExpression: JSDocTypeExpression; 1024 | } 1025 | interface JSDocParameterTag extends JSDocTag { 1026 | preParameterName?: Identifier; 1027 | typeExpression?: JSDocTypeExpression; 1028 | postParameterName?: Identifier; 1029 | isBracketed: boolean; 1030 | } 1031 | interface AmdDependency { 1032 | path: string; 1033 | name: string; 1034 | } 1035 | interface SourceFile extends Declaration { 1036 | statements: NodeArray; 1037 | endOfFileToken: Node; 1038 | fileName: string; 1039 | path: Path; 1040 | text: string; 1041 | amdDependencies: AmdDependency[]; 1042 | moduleName: string; 1043 | referencedFiles: FileReference[]; 1044 | languageVariant: LanguageVariant; 1045 | /** 1046 | * lib.d.ts should have a reference comment like 1047 | * 1048 | * /// 1049 | * 1050 | * If any other file has this comment, it signals not to include lib.d.ts 1051 | * because this containing file is intended to act as a default library. 1052 | */ 1053 | hasNoDefaultLib: boolean; 1054 | languageVersion: ScriptTarget; 1055 | } 1056 | interface ScriptReferenceHost { 1057 | getCompilerOptions(): CompilerOptions; 1058 | getSourceFile(fileName: string): SourceFile; 1059 | getCurrentDirectory(): string; 1060 | } 1061 | interface ParseConfigHost { 1062 | readDirectory(rootDir: string, extension: string, exclude: string[]): string[]; 1063 | } 1064 | interface WriteFileCallback { 1065 | (fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void; 1066 | } 1067 | class OperationCanceledException { 1068 | } 1069 | interface CancellationToken { 1070 | isCancellationRequested(): boolean; 1071 | /** @throws OperationCanceledException if isCancellationRequested is true */ 1072 | throwIfCancellationRequested(): void; 1073 | } 1074 | interface Program extends ScriptReferenceHost { 1075 | /** 1076 | * Get a list of root file names that were passed to a 'createProgram' 1077 | */ 1078 | getRootFileNames(): string[]; 1079 | /** 1080 | * Get a list of files in the program 1081 | */ 1082 | getSourceFiles(): SourceFile[]; 1083 | /** 1084 | * Emits the JavaScript and declaration files. If targetSourceFile is not specified, then 1085 | * the JavaScript and declaration files will be produced for all the files in this program. 1086 | * If targetSourceFile is specified, then only the JavaScript and declaration for that 1087 | * specific file will be generated. 1088 | * 1089 | * If writeFile is not specified then the writeFile callback from the compiler host will be 1090 | * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter 1091 | * will be invoked when writing the JavaScript and declaration files. 1092 | */ 1093 | emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; 1094 | getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; 1095 | getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; 1096 | getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; 1097 | getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; 1098 | getDeclarationDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; 1099 | /** 1100 | * Gets a type checker that can be used to semantically analyze source fils in the program. 1101 | */ 1102 | getTypeChecker(): TypeChecker; 1103 | } 1104 | interface SourceMapSpan { 1105 | /** Line number in the .js file. */ 1106 | emittedLine: number; 1107 | /** Column number in the .js file. */ 1108 | emittedColumn: number; 1109 | /** Line number in the .ts file. */ 1110 | sourceLine: number; 1111 | /** Column number in the .ts file. */ 1112 | sourceColumn: number; 1113 | /** Optional name (index into names array) associated with this span. */ 1114 | nameIndex?: number; 1115 | /** .ts file (index into sources array) associated with this span */ 1116 | sourceIndex: number; 1117 | } 1118 | interface SourceMapData { 1119 | sourceMapFilePath: string; 1120 | jsSourceMappingURL: string; 1121 | sourceMapFile: string; 1122 | sourceMapSourceRoot: string; 1123 | sourceMapSources: string[]; 1124 | sourceMapSourcesContent?: string[]; 1125 | inputSourceFileNames: string[]; 1126 | sourceMapNames?: string[]; 1127 | sourceMapMappings: string; 1128 | sourceMapDecodedMappings: SourceMapSpan[]; 1129 | } 1130 | /** Return code used by getEmitOutput function to indicate status of the function */ 1131 | enum ExitStatus { 1132 | Success = 0, 1133 | DiagnosticsPresent_OutputsSkipped = 1, 1134 | DiagnosticsPresent_OutputsGenerated = 2, 1135 | } 1136 | interface EmitResult { 1137 | emitSkipped: boolean; 1138 | diagnostics: Diagnostic[]; 1139 | } 1140 | interface TypeChecker { 1141 | getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type; 1142 | getDeclaredTypeOfSymbol(symbol: Symbol): Type; 1143 | getPropertiesOfType(type: Type): Symbol[]; 1144 | getPropertyOfType(type: Type, propertyName: string): Symbol; 1145 | getSignaturesOfType(type: Type, kind: SignatureKind): Signature[]; 1146 | getIndexTypeOfType(type: Type, kind: IndexKind): Type; 1147 | getBaseTypes(type: InterfaceType): ObjectType[]; 1148 | getReturnTypeOfSignature(signature: Signature): Type; 1149 | getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; 1150 | getSymbolAtLocation(node: Node): Symbol; 1151 | getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; 1152 | getShorthandAssignmentValueSymbol(location: Node): Symbol; 1153 | getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol; 1154 | getTypeAtLocation(node: Node): Type; 1155 | typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; 1156 | symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; 1157 | getSymbolDisplayBuilder(): SymbolDisplayBuilder; 1158 | getFullyQualifiedName(symbol: Symbol): string; 1159 | getAugmentedPropertiesOfType(type: Type): Symbol[]; 1160 | getRootSymbols(symbol: Symbol): Symbol[]; 1161 | getContextualType(node: Expression): Type; 1162 | getResolvedSignature(node: CallLikeExpression, candidatesOutArray?: Signature[]): Signature; 1163 | getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature; 1164 | isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; 1165 | isUndefinedSymbol(symbol: Symbol): boolean; 1166 | isArgumentsSymbol(symbol: Symbol): boolean; 1167 | isUnknownSymbol(symbol: Symbol): boolean; 1168 | getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; 1169 | isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean; 1170 | getAliasedSymbol(symbol: Symbol): Symbol; 1171 | getExportsOfModule(moduleSymbol: Symbol): Symbol[]; 1172 | getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type; 1173 | getJsxIntrinsicTagNames(): Symbol[]; 1174 | isOptionalParameter(node: ParameterDeclaration): boolean; 1175 | } 1176 | interface SymbolDisplayBuilder { 1177 | buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; 1178 | buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; 1179 | buildSignatureDisplay(signatures: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; 1180 | buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; 1181 | buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; 1182 | buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; 1183 | buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; 1184 | buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; 1185 | buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; 1186 | buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; 1187 | } 1188 | interface SymbolWriter { 1189 | writeKeyword(text: string): void; 1190 | writeOperator(text: string): void; 1191 | writePunctuation(text: string): void; 1192 | writeSpace(text: string): void; 1193 | writeStringLiteral(text: string): void; 1194 | writeParameter(text: string): void; 1195 | writeSymbol(text: string, symbol: Symbol): void; 1196 | writeLine(): void; 1197 | increaseIndent(): void; 1198 | decreaseIndent(): void; 1199 | clear(): void; 1200 | trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; 1201 | reportInaccessibleThisError(): void; 1202 | } 1203 | enum TypeFormatFlags { 1204 | None = 0, 1205 | WriteArrayAsGenericType = 1, 1206 | UseTypeOfFunction = 2, 1207 | NoTruncation = 4, 1208 | WriteArrowStyleSignature = 8, 1209 | WriteOwnNameForAnyLike = 16, 1210 | WriteTypeArgumentsOfSignature = 32, 1211 | InElementType = 64, 1212 | UseFullyQualifiedType = 128, 1213 | } 1214 | enum SymbolFormatFlags { 1215 | None = 0, 1216 | WriteTypeParametersOrArguments = 1, 1217 | UseOnlyExternalAliasing = 2, 1218 | } 1219 | enum TypePredicateKind { 1220 | This = 0, 1221 | Identifier = 1, 1222 | } 1223 | interface TypePredicateBase { 1224 | kind: TypePredicateKind; 1225 | type: Type; 1226 | } 1227 | interface ThisTypePredicate extends TypePredicateBase { 1228 | _thisTypePredicateBrand: any; 1229 | } 1230 | interface IdentifierTypePredicate extends TypePredicateBase { 1231 | parameterName: string; 1232 | parameterIndex: number; 1233 | } 1234 | type TypePredicate = IdentifierTypePredicate | ThisTypePredicate; 1235 | enum SymbolFlags { 1236 | None = 0, 1237 | FunctionScopedVariable = 1, 1238 | BlockScopedVariable = 2, 1239 | Property = 4, 1240 | EnumMember = 8, 1241 | Function = 16, 1242 | Class = 32, 1243 | Interface = 64, 1244 | ConstEnum = 128, 1245 | RegularEnum = 256, 1246 | ValueModule = 512, 1247 | NamespaceModule = 1024, 1248 | TypeLiteral = 2048, 1249 | ObjectLiteral = 4096, 1250 | Method = 8192, 1251 | Constructor = 16384, 1252 | GetAccessor = 32768, 1253 | SetAccessor = 65536, 1254 | Signature = 131072, 1255 | TypeParameter = 262144, 1256 | TypeAlias = 524288, 1257 | ExportValue = 1048576, 1258 | ExportType = 2097152, 1259 | ExportNamespace = 4194304, 1260 | Alias = 8388608, 1261 | Instantiated = 16777216, 1262 | Merged = 33554432, 1263 | Transient = 67108864, 1264 | Prototype = 134217728, 1265 | SyntheticProperty = 268435456, 1266 | Optional = 536870912, 1267 | ExportStar = 1073741824, 1268 | Enum = 384, 1269 | Variable = 3, 1270 | Value = 107455, 1271 | Type = 793056, 1272 | Namespace = 1536, 1273 | Module = 1536, 1274 | Accessor = 98304, 1275 | FunctionScopedVariableExcludes = 107454, 1276 | BlockScopedVariableExcludes = 107455, 1277 | ParameterExcludes = 107455, 1278 | PropertyExcludes = 107455, 1279 | EnumMemberExcludes = 107455, 1280 | FunctionExcludes = 106927, 1281 | ClassExcludes = 899519, 1282 | InterfaceExcludes = 792960, 1283 | RegularEnumExcludes = 899327, 1284 | ConstEnumExcludes = 899967, 1285 | ValueModuleExcludes = 106639, 1286 | NamespaceModuleExcludes = 0, 1287 | MethodExcludes = 99263, 1288 | GetAccessorExcludes = 41919, 1289 | SetAccessorExcludes = 74687, 1290 | TypeParameterExcludes = 530912, 1291 | TypeAliasExcludes = 793056, 1292 | AliasExcludes = 8388608, 1293 | ModuleMember = 8914931, 1294 | ExportHasLocal = 944, 1295 | HasExports = 1952, 1296 | HasMembers = 6240, 1297 | BlockScoped = 418, 1298 | PropertyOrAccessor = 98308, 1299 | Export = 7340032, 1300 | } 1301 | interface Symbol { 1302 | flags: SymbolFlags; 1303 | name: string; 1304 | declarations?: Declaration[]; 1305 | valueDeclaration?: Declaration; 1306 | members?: SymbolTable; 1307 | exports?: SymbolTable; 1308 | } 1309 | interface SymbolTable { 1310 | [index: string]: Symbol; 1311 | } 1312 | enum TypeFlags { 1313 | Any = 1, 1314 | String = 2, 1315 | Number = 4, 1316 | Boolean = 8, 1317 | Void = 16, 1318 | Undefined = 32, 1319 | Null = 64, 1320 | Enum = 128, 1321 | StringLiteral = 256, 1322 | TypeParameter = 512, 1323 | Class = 1024, 1324 | Interface = 2048, 1325 | Reference = 4096, 1326 | Tuple = 8192, 1327 | Union = 16384, 1328 | Intersection = 32768, 1329 | Anonymous = 65536, 1330 | Instantiated = 131072, 1331 | ObjectLiteral = 524288, 1332 | ESSymbol = 16777216, 1333 | ThisType = 33554432, 1334 | ObjectLiteralPatternWithComputedProperties = 67108864, 1335 | StringLike = 258, 1336 | NumberLike = 132, 1337 | ObjectType = 80896, 1338 | UnionOrIntersection = 49152, 1339 | StructuredType = 130048, 1340 | } 1341 | type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; 1342 | interface Type { 1343 | flags: TypeFlags; 1344 | symbol?: Symbol; 1345 | pattern?: DestructuringPattern; 1346 | } 1347 | interface StringLiteralType extends Type { 1348 | text: string; 1349 | } 1350 | interface ObjectType extends Type { 1351 | } 1352 | interface InterfaceType extends ObjectType { 1353 | typeParameters: TypeParameter[]; 1354 | outerTypeParameters: TypeParameter[]; 1355 | localTypeParameters: TypeParameter[]; 1356 | thisType: TypeParameter; 1357 | } 1358 | interface InterfaceTypeWithDeclaredMembers extends InterfaceType { 1359 | declaredProperties: Symbol[]; 1360 | declaredCallSignatures: Signature[]; 1361 | declaredConstructSignatures: Signature[]; 1362 | declaredStringIndexType: Type; 1363 | declaredNumberIndexType: Type; 1364 | } 1365 | interface TypeReference extends ObjectType { 1366 | target: GenericType; 1367 | typeArguments: Type[]; 1368 | } 1369 | interface GenericType extends InterfaceType, TypeReference { 1370 | } 1371 | interface TupleType extends ObjectType { 1372 | elementTypes: Type[]; 1373 | } 1374 | interface UnionOrIntersectionType extends Type { 1375 | types: Type[]; 1376 | } 1377 | interface UnionType extends UnionOrIntersectionType { 1378 | } 1379 | interface IntersectionType extends UnionOrIntersectionType { 1380 | } 1381 | interface TypeParameter extends Type { 1382 | constraint: Type; 1383 | } 1384 | enum SignatureKind { 1385 | Call = 0, 1386 | Construct = 1, 1387 | } 1388 | interface Signature { 1389 | declaration: SignatureDeclaration; 1390 | typeParameters: TypeParameter[]; 1391 | parameters: Symbol[]; 1392 | } 1393 | enum IndexKind { 1394 | String = 0, 1395 | Number = 1, 1396 | } 1397 | interface DiagnosticMessage { 1398 | key: string; 1399 | category: DiagnosticCategory; 1400 | code: number; 1401 | message: string; 1402 | } 1403 | /** 1404 | * A linked list of formatted diagnostic messages to be used as part of a multiline message. 1405 | * It is built from the bottom up, leaving the head to be the "main" diagnostic. 1406 | * While it seems that DiagnosticMessageChain is structurally similar to DiagnosticMessage, 1407 | * the difference is that messages are all preformatted in DMC. 1408 | */ 1409 | interface DiagnosticMessageChain { 1410 | messageText: string; 1411 | category: DiagnosticCategory; 1412 | code: number; 1413 | next?: DiagnosticMessageChain; 1414 | } 1415 | interface Diagnostic { 1416 | file: SourceFile; 1417 | start: number; 1418 | length: number; 1419 | messageText: string | DiagnosticMessageChain; 1420 | category: DiagnosticCategory; 1421 | code: number; 1422 | } 1423 | enum DiagnosticCategory { 1424 | Warning = 0, 1425 | Error = 1, 1426 | Message = 2, 1427 | } 1428 | enum ModuleResolutionKind { 1429 | Classic = 1, 1430 | NodeJs = 2, 1431 | } 1432 | interface CompilerOptions { 1433 | allowNonTsExtensions?: boolean; 1434 | charset?: string; 1435 | declaration?: boolean; 1436 | diagnostics?: boolean; 1437 | emitBOM?: boolean; 1438 | help?: boolean; 1439 | init?: boolean; 1440 | inlineSourceMap?: boolean; 1441 | inlineSources?: boolean; 1442 | jsx?: JsxEmit; 1443 | reactNamespace?: string; 1444 | listFiles?: boolean; 1445 | locale?: string; 1446 | mapRoot?: string; 1447 | module?: ModuleKind; 1448 | newLine?: NewLineKind; 1449 | noEmit?: boolean; 1450 | noEmitHelpers?: boolean; 1451 | noEmitOnError?: boolean; 1452 | noErrorTruncation?: boolean; 1453 | noImplicitAny?: boolean; 1454 | noLib?: boolean; 1455 | noResolve?: boolean; 1456 | out?: string; 1457 | outFile?: string; 1458 | outDir?: string; 1459 | preserveConstEnums?: boolean; 1460 | project?: string; 1461 | removeComments?: boolean; 1462 | rootDir?: string; 1463 | sourceMap?: boolean; 1464 | sourceRoot?: string; 1465 | suppressExcessPropertyErrors?: boolean; 1466 | suppressImplicitAnyIndexErrors?: boolean; 1467 | target?: ScriptTarget; 1468 | version?: boolean; 1469 | watch?: boolean; 1470 | isolatedModules?: boolean; 1471 | experimentalDecorators?: boolean; 1472 | emitDecoratorMetadata?: boolean; 1473 | moduleResolution?: ModuleResolutionKind; 1474 | allowUnusedLabels?: boolean; 1475 | allowUnreachableCode?: boolean; 1476 | noImplicitReturns?: boolean; 1477 | noFallthroughCasesInSwitch?: boolean; 1478 | forceConsistentCasingInFileNames?: boolean; 1479 | allowSyntheticDefaultImports?: boolean; 1480 | allowJs?: boolean; 1481 | noImplicitUseStrict?: boolean; 1482 | disableSizeLimit?: boolean; 1483 | [option: string]: string | number | boolean; 1484 | } 1485 | interface TypingOptions { 1486 | enableAutoDiscovery?: boolean; 1487 | include?: string[]; 1488 | exclude?: string[]; 1489 | [option: string]: string[] | boolean; 1490 | } 1491 | interface DiscoverTypingsInfo { 1492 | fileNames: string[]; 1493 | projectRootPath: string; 1494 | safeListPath: string; 1495 | packageNameToTypingLocation: Map; 1496 | typingOptions: TypingOptions; 1497 | compilerOptions: CompilerOptions; 1498 | } 1499 | enum ModuleKind { 1500 | None = 0, 1501 | CommonJS = 1, 1502 | AMD = 2, 1503 | UMD = 3, 1504 | System = 4, 1505 | ES6 = 5, 1506 | ES2015 = 5, 1507 | } 1508 | enum JsxEmit { 1509 | None = 0, 1510 | Preserve = 1, 1511 | React = 2, 1512 | } 1513 | enum NewLineKind { 1514 | CarriageReturnLineFeed = 0, 1515 | LineFeed = 1, 1516 | } 1517 | interface LineAndCharacter { 1518 | line: number; 1519 | character: number; 1520 | } 1521 | enum ScriptKind { 1522 | Unknown = 0, 1523 | JS = 1, 1524 | JSX = 2, 1525 | TS = 3, 1526 | TSX = 4, 1527 | } 1528 | enum ScriptTarget { 1529 | ES3 = 0, 1530 | ES5 = 1, 1531 | ES6 = 2, 1532 | ES2015 = 2, 1533 | Latest = 2, 1534 | } 1535 | enum LanguageVariant { 1536 | Standard = 0, 1537 | JSX = 1, 1538 | } 1539 | interface ParsedCommandLine { 1540 | options: CompilerOptions; 1541 | typingOptions?: TypingOptions; 1542 | fileNames: string[]; 1543 | errors: Diagnostic[]; 1544 | } 1545 | interface ModuleResolutionHost { 1546 | fileExists(fileName: string): boolean; 1547 | readFile(fileName: string): string; 1548 | directoryExists?(directoryName: string): boolean; 1549 | } 1550 | interface ResolvedModule { 1551 | resolvedFileName: string; 1552 | isExternalLibraryImport?: boolean; 1553 | } 1554 | interface ResolvedModuleWithFailedLookupLocations { 1555 | resolvedModule: ResolvedModule; 1556 | failedLookupLocations: string[]; 1557 | } 1558 | interface CompilerHost extends ModuleResolutionHost { 1559 | getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile; 1560 | getCancellationToken?(): CancellationToken; 1561 | getDefaultLibFileName(options: CompilerOptions): string; 1562 | writeFile: WriteFileCallback; 1563 | getCurrentDirectory(): string; 1564 | getCanonicalFileName(fileName: string): string; 1565 | useCaseSensitiveFileNames(): boolean; 1566 | getNewLine(): string; 1567 | resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; 1568 | } 1569 | interface TextSpan { 1570 | start: number; 1571 | length: number; 1572 | } 1573 | interface TextChangeRange { 1574 | span: TextSpan; 1575 | newLength: number; 1576 | } 1577 | } 1578 | declare namespace ts { 1579 | type FileWatcherCallback = (path: string, removed?: boolean) => void; 1580 | type DirectoryWatcherCallback = (path: string) => void; 1581 | interface System { 1582 | args: string[]; 1583 | newLine: string; 1584 | useCaseSensitiveFileNames: boolean; 1585 | write(s: string): void; 1586 | readFile(path: string, encoding?: string): string; 1587 | writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; 1588 | watchFile?(path: Path, callback: FileWatcherCallback): FileWatcher; 1589 | watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; 1590 | resolvePath(path: string): string; 1591 | fileExists(path: string): boolean; 1592 | directoryExists(path: string): boolean; 1593 | createDirectory(path: string): void; 1594 | getExecutingFilePath(): string; 1595 | getCurrentDirectory(): string; 1596 | readDirectory(path: string, extension?: string, exclude?: string[]): string[]; 1597 | getMemoryUsage?(): number; 1598 | exit(exitCode?: number): void; 1599 | } 1600 | interface FileWatcher { 1601 | close(): void; 1602 | } 1603 | interface DirectoryWatcher extends FileWatcher { 1604 | directoryPath: Path; 1605 | referenceCount: number; 1606 | } 1607 | var sys: System; 1608 | } 1609 | declare namespace ts { 1610 | interface ErrorCallback { 1611 | (message: DiagnosticMessage, length: number): void; 1612 | } 1613 | interface Scanner { 1614 | getStartPos(): number; 1615 | getToken(): SyntaxKind; 1616 | getTextPos(): number; 1617 | getTokenPos(): number; 1618 | getTokenText(): string; 1619 | getTokenValue(): string; 1620 | hasExtendedUnicodeEscape(): boolean; 1621 | hasPrecedingLineBreak(): boolean; 1622 | isIdentifier(): boolean; 1623 | isReservedWord(): boolean; 1624 | isUnterminated(): boolean; 1625 | reScanGreaterToken(): SyntaxKind; 1626 | reScanSlashToken(): SyntaxKind; 1627 | reScanTemplateToken(): SyntaxKind; 1628 | scanJsxIdentifier(): SyntaxKind; 1629 | reScanJsxToken(): SyntaxKind; 1630 | scanJsxToken(): SyntaxKind; 1631 | scanJSDocToken(): SyntaxKind; 1632 | scan(): SyntaxKind; 1633 | setText(text: string, start?: number, length?: number): void; 1634 | setOnError(onError: ErrorCallback): void; 1635 | setScriptTarget(scriptTarget: ScriptTarget): void; 1636 | setLanguageVariant(variant: LanguageVariant): void; 1637 | setTextPos(textPos: number): void; 1638 | lookAhead(callback: () => T): T; 1639 | scanRange(start: number, length: number, callback: () => T): T; 1640 | tryScan(callback: () => T): T; 1641 | } 1642 | function tokenToString(t: SyntaxKind): string; 1643 | function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; 1644 | function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter; 1645 | function isWhiteSpace(ch: number): boolean; 1646 | function isLineBreak(ch: number): boolean; 1647 | function couldStartTrivia(text: string, pos: number): boolean; 1648 | function getLeadingCommentRanges(text: string, pos: number): CommentRange[]; 1649 | function getTrailingCommentRanges(text: string, pos: number): CommentRange[]; 1650 | /** Optionally, get the shebang */ 1651 | function getShebang(text: string): string; 1652 | function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; 1653 | function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; 1654 | function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; 1655 | } 1656 | declare namespace ts { 1657 | function getDefaultLibFileName(options: CompilerOptions): string; 1658 | function textSpanEnd(span: TextSpan): number; 1659 | function textSpanIsEmpty(span: TextSpan): boolean; 1660 | function textSpanContainsPosition(span: TextSpan, position: number): boolean; 1661 | function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean; 1662 | function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean; 1663 | function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan; 1664 | function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean; 1665 | function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean; 1666 | function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean; 1667 | function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean; 1668 | function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan; 1669 | function createTextSpan(start: number, length: number): TextSpan; 1670 | function createTextSpanFromBounds(start: number, end: number): TextSpan; 1671 | function textChangeRangeNewSpan(range: TextChangeRange): TextSpan; 1672 | function textChangeRangeIsUnchanged(range: TextChangeRange): boolean; 1673 | function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange; 1674 | let unchangedTextChangeRange: TextChangeRange; 1675 | /** 1676 | * Called to merge all the changes that occurred across several versions of a script snapshot 1677 | * into a single change. i.e. if a user keeps making successive edits to a script we will 1678 | * have a text change from V1 to V2, V2 to V3, ..., Vn. 1679 | * 1680 | * This function will then merge those changes into a single change range valid between V1 and 1681 | * Vn. 1682 | */ 1683 | function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange; 1684 | function getTypeParameterOwner(d: Declaration): Declaration; 1685 | function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean; 1686 | } 1687 | declare namespace ts { 1688 | function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; 1689 | function forEachChild(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T; 1690 | function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile; 1691 | function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; 1692 | } 1693 | declare namespace ts { 1694 | const version: string; 1695 | function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string; 1696 | function resolveTripleslashReference(moduleName: string, containingFile: string): string; 1697 | function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; 1698 | function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; 1699 | function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; 1700 | function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; 1701 | function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; 1702 | function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; 1703 | function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; 1704 | } 1705 | declare namespace ts { 1706 | function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine; 1707 | /** 1708 | * Read tsconfig.json file 1709 | * @param fileName The path to the config file 1710 | */ 1711 | function readConfigFile(fileName: string, readFile: (path: string) => string): { 1712 | config?: any; 1713 | error?: Diagnostic; 1714 | }; 1715 | /** 1716 | * Parse the text of the tsconfig.json file 1717 | * @param fileName The path to the config file 1718 | * @param jsonText The text of the config file 1719 | */ 1720 | function parseConfigFileTextToJson(fileName: string, jsonText: string): { 1721 | config?: any; 1722 | error?: Diagnostic; 1723 | }; 1724 | /** 1725 | * Parse the contents of a config file (tsconfig.json). 1726 | * @param json The contents of the config file to parse 1727 | * @param host Instance of ParseConfigHost used to enumerate files in folder. 1728 | * @param basePath A root directory to resolve relative path entries in the config 1729 | * file to. e.g. outDir 1730 | */ 1731 | function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string): ParsedCommandLine; 1732 | function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { 1733 | options: CompilerOptions; 1734 | errors: Diagnostic[]; 1735 | }; 1736 | } 1737 | declare namespace ts { 1738 | /** The version of the language service API */ 1739 | const servicesVersion: string; 1740 | interface Node { 1741 | getSourceFile(): SourceFile; 1742 | getChildCount(sourceFile?: SourceFile): number; 1743 | getChildAt(index: number, sourceFile?: SourceFile): Node; 1744 | getChildren(sourceFile?: SourceFile): Node[]; 1745 | getStart(sourceFile?: SourceFile): number; 1746 | getFullStart(): number; 1747 | getEnd(): number; 1748 | getWidth(sourceFile?: SourceFile): number; 1749 | getFullWidth(): number; 1750 | getLeadingTriviaWidth(sourceFile?: SourceFile): number; 1751 | getFullText(sourceFile?: SourceFile): string; 1752 | getText(sourceFile?: SourceFile): string; 1753 | getFirstToken(sourceFile?: SourceFile): Node; 1754 | getLastToken(sourceFile?: SourceFile): Node; 1755 | } 1756 | interface Symbol { 1757 | getFlags(): SymbolFlags; 1758 | getName(): string; 1759 | getDeclarations(): Declaration[]; 1760 | getDocumentationComment(): SymbolDisplayPart[]; 1761 | } 1762 | interface Type { 1763 | getFlags(): TypeFlags; 1764 | getSymbol(): Symbol; 1765 | getProperties(): Symbol[]; 1766 | getProperty(propertyName: string): Symbol; 1767 | getApparentProperties(): Symbol[]; 1768 | getCallSignatures(): Signature[]; 1769 | getConstructSignatures(): Signature[]; 1770 | getStringIndexType(): Type; 1771 | getNumberIndexType(): Type; 1772 | getBaseTypes(): ObjectType[]; 1773 | } 1774 | interface Signature { 1775 | getDeclaration(): SignatureDeclaration; 1776 | getTypeParameters(): Type[]; 1777 | getParameters(): Symbol[]; 1778 | getReturnType(): Type; 1779 | getDocumentationComment(): SymbolDisplayPart[]; 1780 | } 1781 | interface SourceFile { 1782 | getLineAndCharacterOfPosition(pos: number): LineAndCharacter; 1783 | getLineStarts(): number[]; 1784 | getPositionOfLineAndCharacter(line: number, character: number): number; 1785 | update(newText: string, textChangeRange: TextChangeRange): SourceFile; 1786 | } 1787 | /** 1788 | * Represents an immutable snapshot of a script at a specified time.Once acquired, the 1789 | * snapshot is observably immutable. i.e. the same calls with the same parameters will return 1790 | * the same values. 1791 | */ 1792 | interface IScriptSnapshot { 1793 | /** Gets a portion of the script snapshot specified by [start, end). */ 1794 | getText(start: number, end: number): string; 1795 | /** Gets the length of this script snapshot. */ 1796 | getLength(): number; 1797 | /** 1798 | * Gets the TextChangeRange that describe how the text changed between this text and 1799 | * an older version. This information is used by the incremental parser to determine 1800 | * what sections of the script need to be re-parsed. 'undefined' can be returned if the 1801 | * change range cannot be determined. However, in that case, incremental parsing will 1802 | * not happen and the entire document will be re - parsed. 1803 | */ 1804 | getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange; 1805 | /** Releases all resources held by this script snapshot */ 1806 | dispose?(): void; 1807 | } 1808 | namespace ScriptSnapshot { 1809 | function fromString(text: string): IScriptSnapshot; 1810 | } 1811 | interface PreProcessedFileInfo { 1812 | referencedFiles: FileReference[]; 1813 | importedFiles: FileReference[]; 1814 | ambientExternalModules: string[]; 1815 | isLibFile: boolean; 1816 | } 1817 | interface HostCancellationToken { 1818 | isCancellationRequested(): boolean; 1819 | } 1820 | interface LanguageServiceHost { 1821 | getCompilationSettings(): CompilerOptions; 1822 | getNewLine?(): string; 1823 | getProjectVersion?(): string; 1824 | getScriptFileNames(): string[]; 1825 | getScriptKind?(fileName: string): ScriptKind; 1826 | getScriptVersion(fileName: string): string; 1827 | getScriptSnapshot(fileName: string): IScriptSnapshot; 1828 | getLocalizedDiagnosticMessages?(): any; 1829 | getCancellationToken?(): HostCancellationToken; 1830 | getCurrentDirectory(): string; 1831 | getDefaultLibFileName(options: CompilerOptions): string; 1832 | log?(s: string): void; 1833 | trace?(s: string): void; 1834 | error?(s: string): void; 1835 | useCaseSensitiveFileNames?(): boolean; 1836 | resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; 1837 | directoryExists?(directoryName: string): boolean; 1838 | } 1839 | interface LanguageService { 1840 | cleanupSemanticCache(): void; 1841 | getSyntacticDiagnostics(fileName: string): Diagnostic[]; 1842 | getSemanticDiagnostics(fileName: string): Diagnostic[]; 1843 | getCompilerOptionsDiagnostics(): Diagnostic[]; 1844 | /** 1845 | * @deprecated Use getEncodedSyntacticClassifications instead. 1846 | */ 1847 | getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; 1848 | /** 1849 | * @deprecated Use getEncodedSemanticClassifications instead. 1850 | */ 1851 | getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]; 1852 | getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications; 1853 | getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications; 1854 | getCompletionsAtPosition(fileName: string, position: number): CompletionInfo; 1855 | getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails; 1856 | getQuickInfoAtPosition(fileName: string, position: number): QuickInfo; 1857 | getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan; 1858 | getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan; 1859 | getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems; 1860 | getRenameInfo(fileName: string, position: number): RenameInfo; 1861 | findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; 1862 | getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; 1863 | getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; 1864 | getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; 1865 | findReferences(fileName: string, position: number): ReferencedSymbol[]; 1866 | getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; 1867 | /** @deprecated */ 1868 | getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; 1869 | getNavigateToItems(searchValue: string, maxResultCount?: number): NavigateToItem[]; 1870 | getNavigationBarItems(fileName: string): NavigationBarItem[]; 1871 | getOutliningSpans(fileName: string): OutliningSpan[]; 1872 | getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; 1873 | getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; 1874 | getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; 1875 | getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; 1876 | getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; 1877 | getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; 1878 | getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; 1879 | getEmitOutput(fileName: string): EmitOutput; 1880 | getProgram(): Program; 1881 | getSourceFile(fileName: string): SourceFile; 1882 | dispose(): void; 1883 | } 1884 | interface Classifications { 1885 | spans: number[]; 1886 | endOfLineState: EndOfLineState; 1887 | } 1888 | interface ClassifiedSpan { 1889 | textSpan: TextSpan; 1890 | classificationType: string; 1891 | } 1892 | interface NavigationBarItem { 1893 | text: string; 1894 | kind: string; 1895 | kindModifiers: string; 1896 | spans: TextSpan[]; 1897 | childItems: NavigationBarItem[]; 1898 | indent: number; 1899 | bolded: boolean; 1900 | grayed: boolean; 1901 | } 1902 | interface TodoCommentDescriptor { 1903 | text: string; 1904 | priority: number; 1905 | } 1906 | interface TodoComment { 1907 | descriptor: TodoCommentDescriptor; 1908 | message: string; 1909 | position: number; 1910 | } 1911 | class TextChange { 1912 | span: TextSpan; 1913 | newText: string; 1914 | } 1915 | interface TextInsertion { 1916 | newText: string; 1917 | /** The position in newText the caret should point to after the insertion. */ 1918 | caretOffset: number; 1919 | } 1920 | interface RenameLocation { 1921 | textSpan: TextSpan; 1922 | fileName: string; 1923 | } 1924 | interface ReferenceEntry { 1925 | textSpan: TextSpan; 1926 | fileName: string; 1927 | isWriteAccess: boolean; 1928 | } 1929 | interface DocumentHighlights { 1930 | fileName: string; 1931 | highlightSpans: HighlightSpan[]; 1932 | } 1933 | namespace HighlightSpanKind { 1934 | const none: string; 1935 | const definition: string; 1936 | const reference: string; 1937 | const writtenReference: string; 1938 | } 1939 | interface HighlightSpan { 1940 | fileName?: string; 1941 | textSpan: TextSpan; 1942 | kind: string; 1943 | } 1944 | interface NavigateToItem { 1945 | name: string; 1946 | kind: string; 1947 | kindModifiers: string; 1948 | matchKind: string; 1949 | isCaseSensitive: boolean; 1950 | fileName: string; 1951 | textSpan: TextSpan; 1952 | containerName: string; 1953 | containerKind: string; 1954 | } 1955 | interface EditorOptions { 1956 | IndentSize: number; 1957 | TabSize: number; 1958 | NewLineCharacter: string; 1959 | ConvertTabsToSpaces: boolean; 1960 | IndentStyle: IndentStyle; 1961 | } 1962 | enum IndentStyle { 1963 | None = 0, 1964 | Block = 1, 1965 | Smart = 2, 1966 | } 1967 | interface FormatCodeOptions extends EditorOptions { 1968 | InsertSpaceAfterCommaDelimiter: boolean; 1969 | InsertSpaceAfterSemicolonInForStatements: boolean; 1970 | InsertSpaceBeforeAndAfterBinaryOperators: boolean; 1971 | InsertSpaceAfterKeywordsInControlFlowStatements: boolean; 1972 | InsertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; 1973 | InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; 1974 | InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; 1975 | InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; 1976 | PlaceOpenBraceOnNewLineForFunctions: boolean; 1977 | PlaceOpenBraceOnNewLineForControlBlocks: boolean; 1978 | [s: string]: boolean | number | string; 1979 | } 1980 | interface DefinitionInfo { 1981 | fileName: string; 1982 | textSpan: TextSpan; 1983 | kind: string; 1984 | name: string; 1985 | containerKind: string; 1986 | containerName: string; 1987 | } 1988 | interface ReferencedSymbol { 1989 | definition: DefinitionInfo; 1990 | references: ReferenceEntry[]; 1991 | } 1992 | enum SymbolDisplayPartKind { 1993 | aliasName = 0, 1994 | className = 1, 1995 | enumName = 2, 1996 | fieldName = 3, 1997 | interfaceName = 4, 1998 | keyword = 5, 1999 | lineBreak = 6, 2000 | numericLiteral = 7, 2001 | stringLiteral = 8, 2002 | localName = 9, 2003 | methodName = 10, 2004 | moduleName = 11, 2005 | operator = 12, 2006 | parameterName = 13, 2007 | propertyName = 14, 2008 | punctuation = 15, 2009 | space = 16, 2010 | text = 17, 2011 | typeParameterName = 18, 2012 | enumMemberName = 19, 2013 | functionName = 20, 2014 | regularExpressionLiteral = 21, 2015 | } 2016 | interface SymbolDisplayPart { 2017 | text: string; 2018 | kind: string; 2019 | } 2020 | interface QuickInfo { 2021 | kind: string; 2022 | kindModifiers: string; 2023 | textSpan: TextSpan; 2024 | displayParts: SymbolDisplayPart[]; 2025 | documentation: SymbolDisplayPart[]; 2026 | } 2027 | interface RenameInfo { 2028 | canRename: boolean; 2029 | localizedErrorMessage: string; 2030 | displayName: string; 2031 | fullDisplayName: string; 2032 | kind: string; 2033 | kindModifiers: string; 2034 | triggerSpan: TextSpan; 2035 | } 2036 | interface SignatureHelpParameter { 2037 | name: string; 2038 | documentation: SymbolDisplayPart[]; 2039 | displayParts: SymbolDisplayPart[]; 2040 | isOptional: boolean; 2041 | } 2042 | /** 2043 | * Represents a single signature to show in signature help. 2044 | * The id is used for subsequent calls into the language service to ask questions about the 2045 | * signature help item in the context of any documents that have been updated. i.e. after 2046 | * an edit has happened, while signature help is still active, the host can ask important 2047 | * questions like 'what parameter is the user currently contained within?'. 2048 | */ 2049 | interface SignatureHelpItem { 2050 | isVariadic: boolean; 2051 | prefixDisplayParts: SymbolDisplayPart[]; 2052 | suffixDisplayParts: SymbolDisplayPart[]; 2053 | separatorDisplayParts: SymbolDisplayPart[]; 2054 | parameters: SignatureHelpParameter[]; 2055 | documentation: SymbolDisplayPart[]; 2056 | } 2057 | /** 2058 | * Represents a set of signature help items, and the preferred item that should be selected. 2059 | */ 2060 | interface SignatureHelpItems { 2061 | items: SignatureHelpItem[]; 2062 | applicableSpan: TextSpan; 2063 | selectedItemIndex: number; 2064 | argumentIndex: number; 2065 | argumentCount: number; 2066 | } 2067 | interface CompletionInfo { 2068 | isMemberCompletion: boolean; 2069 | isNewIdentifierLocation: boolean; 2070 | entries: CompletionEntry[]; 2071 | } 2072 | interface CompletionEntry { 2073 | name: string; 2074 | kind: string; 2075 | kindModifiers: string; 2076 | sortText: string; 2077 | } 2078 | interface CompletionEntryDetails { 2079 | name: string; 2080 | kind: string; 2081 | kindModifiers: string; 2082 | displayParts: SymbolDisplayPart[]; 2083 | documentation: SymbolDisplayPart[]; 2084 | } 2085 | interface OutliningSpan { 2086 | /** The span of the document to actually collapse. */ 2087 | textSpan: TextSpan; 2088 | /** The span of the document to display when the user hovers over the collapsed span. */ 2089 | hintSpan: TextSpan; 2090 | /** The text to display in the editor for the collapsed region. */ 2091 | bannerText: string; 2092 | /** 2093 | * Whether or not this region should be automatically collapsed when 2094 | * the 'Collapse to Definitions' command is invoked. 2095 | */ 2096 | autoCollapse: boolean; 2097 | } 2098 | interface EmitOutput { 2099 | outputFiles: OutputFile[]; 2100 | emitSkipped: boolean; 2101 | } 2102 | enum OutputFileType { 2103 | JavaScript = 0, 2104 | SourceMap = 1, 2105 | Declaration = 2, 2106 | } 2107 | interface OutputFile { 2108 | name: string; 2109 | writeByteOrderMark: boolean; 2110 | text: string; 2111 | } 2112 | enum EndOfLineState { 2113 | None = 0, 2114 | InMultiLineCommentTrivia = 1, 2115 | InSingleQuoteStringLiteral = 2, 2116 | InDoubleQuoteStringLiteral = 3, 2117 | InTemplateHeadOrNoSubstitutionTemplate = 4, 2118 | InTemplateMiddleOrTail = 5, 2119 | InTemplateSubstitutionPosition = 6, 2120 | } 2121 | enum TokenClass { 2122 | Punctuation = 0, 2123 | Keyword = 1, 2124 | Operator = 2, 2125 | Comment = 3, 2126 | Whitespace = 4, 2127 | Identifier = 5, 2128 | NumberLiteral = 6, 2129 | StringLiteral = 7, 2130 | RegExpLiteral = 8, 2131 | } 2132 | interface ClassificationResult { 2133 | finalLexState: EndOfLineState; 2134 | entries: ClassificationInfo[]; 2135 | } 2136 | interface ClassificationInfo { 2137 | length: number; 2138 | classification: TokenClass; 2139 | } 2140 | interface Classifier { 2141 | /** 2142 | * Gives lexical classifications of tokens on a line without any syntactic context. 2143 | * For instance, a token consisting of the text 'string' can be either an identifier 2144 | * named 'string' or the keyword 'string', however, because this classifier is not aware, 2145 | * it relies on certain heuristics to give acceptable results. For classifications where 2146 | * speed trumps accuracy, this function is preferable; however, for true accuracy, the 2147 | * syntactic classifier is ideal. In fact, in certain editing scenarios, combining the 2148 | * lexical, syntactic, and semantic classifiers may issue the best user experience. 2149 | * 2150 | * @param text The text of a line to classify. 2151 | * @param lexState The state of the lexical classifier at the end of the previous line. 2152 | * @param syntacticClassifierAbsent Whether the client is *not* using a syntactic classifier. 2153 | * If there is no syntactic classifier (syntacticClassifierAbsent=true), 2154 | * certain heuristics may be used in its place; however, if there is a 2155 | * syntactic classifier (syntacticClassifierAbsent=false), certain 2156 | * classifications which may be incorrectly categorized will be given 2157 | * back as Identifiers in order to allow the syntactic classifier to 2158 | * subsume the classification. 2159 | * @deprecated Use getLexicalClassifications instead. 2160 | */ 2161 | getClassificationsForLine(text: string, lexState: EndOfLineState, syntacticClassifierAbsent: boolean): ClassificationResult; 2162 | getEncodedLexicalClassifications(text: string, endOfLineState: EndOfLineState, syntacticClassifierAbsent: boolean): Classifications; 2163 | } 2164 | /** 2165 | * The document registry represents a store of SourceFile objects that can be shared between 2166 | * multiple LanguageService instances. A LanguageService instance holds on the SourceFile (AST) 2167 | * of files in the context. 2168 | * SourceFile objects account for most of the memory usage by the language service. Sharing 2169 | * the same DocumentRegistry instance between different instances of LanguageService allow 2170 | * for more efficient memory utilization since all projects will share at least the library 2171 | * file (lib.d.ts). 2172 | * 2173 | * A more advanced use of the document registry is to serialize sourceFile objects to disk 2174 | * and re-hydrate them when needed. 2175 | * 2176 | * To create a default DocumentRegistry, use createDocumentRegistry to create one, and pass it 2177 | * to all subsequent createLanguageService calls. 2178 | */ 2179 | interface DocumentRegistry { 2180 | /** 2181 | * Request a stored SourceFile with a given fileName and compilationSettings. 2182 | * The first call to acquire will call createLanguageServiceSourceFile to generate 2183 | * the SourceFile if was not found in the registry. 2184 | * 2185 | * @param fileName The name of the file requested 2186 | * @param compilationSettings Some compilation settings like target affects the 2187 | * shape of a the resulting SourceFile. This allows the DocumentRegistry to store 2188 | * multiple copies of the same file for different compilation settings. 2189 | * @parm scriptSnapshot Text of the file. Only used if the file was not found 2190 | * in the registry and a new one was created. 2191 | * @parm version Current version of the file. Only used if the file was not found 2192 | * in the registry and a new one was created. 2193 | */ 2194 | acquireDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; 2195 | /** 2196 | * Request an updated version of an already existing SourceFile with a given fileName 2197 | * and compilationSettings. The update will in-turn call updateLanguageServiceSourceFile 2198 | * to get an updated SourceFile. 2199 | * 2200 | * @param fileName The name of the file requested 2201 | * @param compilationSettings Some compilation settings like target affects the 2202 | * shape of a the resulting SourceFile. This allows the DocumentRegistry to store 2203 | * multiple copies of the same file for different compilation settings. 2204 | * @param scriptSnapshot Text of the file. 2205 | * @param version Current version of the file. 2206 | */ 2207 | updateDocument(fileName: string, compilationSettings: CompilerOptions, scriptSnapshot: IScriptSnapshot, version: string, scriptKind?: ScriptKind): SourceFile; 2208 | /** 2209 | * Informs the DocumentRegistry that a file is not needed any longer. 2210 | * 2211 | * Note: It is not allowed to call release on a SourceFile that was not acquired from 2212 | * this registry originally. 2213 | * 2214 | * @param fileName The name of the file to be released 2215 | * @param compilationSettings The compilation settings used to acquire the file 2216 | */ 2217 | releaseDocument(fileName: string, compilationSettings: CompilerOptions): void; 2218 | reportStats(): string; 2219 | } 2220 | namespace ScriptElementKind { 2221 | const unknown: string; 2222 | const warning: string; 2223 | const keyword: string; 2224 | const scriptElement: string; 2225 | const moduleElement: string; 2226 | const classElement: string; 2227 | const localClassElement: string; 2228 | const interfaceElement: string; 2229 | const typeElement: string; 2230 | const enumElement: string; 2231 | const variableElement: string; 2232 | const localVariableElement: string; 2233 | const functionElement: string; 2234 | const localFunctionElement: string; 2235 | const memberFunctionElement: string; 2236 | const memberGetAccessorElement: string; 2237 | const memberSetAccessorElement: string; 2238 | const memberVariableElement: string; 2239 | const constructorImplementationElement: string; 2240 | const callSignatureElement: string; 2241 | const indexSignatureElement: string; 2242 | const constructSignatureElement: string; 2243 | const parameterElement: string; 2244 | const typeParameterElement: string; 2245 | const primitiveType: string; 2246 | const label: string; 2247 | const alias: string; 2248 | const constElement: string; 2249 | const letElement: string; 2250 | } 2251 | namespace ScriptElementKindModifier { 2252 | const none: string; 2253 | const publicMemberModifier: string; 2254 | const privateMemberModifier: string; 2255 | const protectedMemberModifier: string; 2256 | const exportedModifier: string; 2257 | const ambientModifier: string; 2258 | const staticModifier: string; 2259 | const abstractModifier: string; 2260 | } 2261 | class ClassificationTypeNames { 2262 | static comment: string; 2263 | static identifier: string; 2264 | static keyword: string; 2265 | static numericLiteral: string; 2266 | static operator: string; 2267 | static stringLiteral: string; 2268 | static whiteSpace: string; 2269 | static text: string; 2270 | static punctuation: string; 2271 | static className: string; 2272 | static enumName: string; 2273 | static interfaceName: string; 2274 | static moduleName: string; 2275 | static typeParameterName: string; 2276 | static typeAliasName: string; 2277 | static parameterName: string; 2278 | static docCommentTagName: string; 2279 | static jsxOpenTagName: string; 2280 | static jsxCloseTagName: string; 2281 | static jsxSelfClosingTagName: string; 2282 | static jsxAttribute: string; 2283 | static jsxText: string; 2284 | static jsxAttributeStringLiteralValue: string; 2285 | } 2286 | enum ClassificationType { 2287 | comment = 1, 2288 | identifier = 2, 2289 | keyword = 3, 2290 | numericLiteral = 4, 2291 | operator = 5, 2292 | stringLiteral = 6, 2293 | regularExpressionLiteral = 7, 2294 | whiteSpace = 8, 2295 | text = 9, 2296 | punctuation = 10, 2297 | className = 11, 2298 | enumName = 12, 2299 | interfaceName = 13, 2300 | moduleName = 14, 2301 | typeParameterName = 15, 2302 | typeAliasName = 16, 2303 | parameterName = 17, 2304 | docCommentTagName = 18, 2305 | jsxOpenTagName = 19, 2306 | jsxCloseTagName = 20, 2307 | jsxSelfClosingTagName = 21, 2308 | jsxAttribute = 22, 2309 | jsxText = 23, 2310 | jsxAttributeStringLiteralValue = 24, 2311 | } 2312 | interface DisplayPartsSymbolWriter extends SymbolWriter { 2313 | displayParts(): SymbolDisplayPart[]; 2314 | } 2315 | function displayPartsToString(displayParts: SymbolDisplayPart[]): string; 2316 | function getDefaultCompilerOptions(): CompilerOptions; 2317 | interface TranspileOptions { 2318 | compilerOptions?: CompilerOptions; 2319 | fileName?: string; 2320 | reportDiagnostics?: boolean; 2321 | moduleName?: string; 2322 | renamedDependencies?: Map; 2323 | } 2324 | interface TranspileOutput { 2325 | outputText: string; 2326 | diagnostics?: Diagnostic[]; 2327 | sourceMapText?: string; 2328 | } 2329 | function transpileModule(input: string, transpileOptions: TranspileOptions): TranspileOutput; 2330 | function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string; 2331 | function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; 2332 | let disableIncrementalParsing: boolean; 2333 | function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; 2334 | function createDocumentRegistry(useCaseSensitiveFileNames?: boolean, currentDirectory?: string): DocumentRegistry; 2335 | function preProcessFile(sourceText: string, readImportFiles?: boolean, detectJavaScriptImports?: boolean): PreProcessedFileInfo; 2336 | function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService; 2337 | function createClassifier(): Classifier; 2338 | /** 2339 | * Get the path of the default library files (lib.d.ts) as distributed with the typescript 2340 | * node package. 2341 | * The functionality is not supported if the ts module is consumed outside of a node module. 2342 | */ 2343 | function getDefaultLibFilePath(options: CompilerOptions): string; 2344 | } 2345 | 2346 | // MONACOCHANGE 2347 | export = ts; 2348 | // END MONACOCHANGE 2349 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "monaco-typescript", 3 | "version": "0.1.0", 4 | "description": "TypeScript and JavaScript language support for Monaco Editor", 5 | "scripts": { 6 | "test": "node_modules/.bin/mocha", 7 | "watch": "node_modules/.bin/gulp watch", 8 | "prepublish": "node_modules/.bin/gulp release" 9 | }, 10 | "author": "Microsoft Corporation", 11 | "license": "MIT", 12 | "repository": { 13 | "type": "git", 14 | "url": "https://github.com/Microsoft/monaco-typescript" 15 | }, 16 | "bugs": { 17 | "url": "https://github.com/Microsoft/monaco-typescript/issues" 18 | }, 19 | "devDependencies": { 20 | "event-stream": "^3.3.2", 21 | "gulp": "^3.9.1", 22 | "gulp-requirejs": "^0.1.3", 23 | "gulp-tsb": "^1.10.4", 24 | "gulp-uglify": "^1.5.3", 25 | "merge-stream": "^1.0.0", 26 | "mocha": "^2.5.3", 27 | "monaco-editor-core": "^0.3.1", 28 | "object-assign": "^4.1.0", 29 | "rimraf": "^2.5.2", 30 | "typescript": "1.8.10", 31 | "typescript-with-globs": "^0.1.4" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/languageFeatures.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 'use strict'; 6 | 7 | import {LanguageServiceDefaults} from './typescript'; 8 | import * as ts from '../lib/typescriptServices'; 9 | import {TypeScriptWorker} from './worker'; 10 | 11 | import Uri = monaco.Uri; 12 | import Position = monaco.Position; 13 | import Range = monaco.Range; 14 | import Thenable = monaco.Thenable; 15 | import Promise = monaco.Promise; 16 | import CancellationToken = monaco.CancellationToken; 17 | import IDisposable = monaco.IDisposable; 18 | 19 | export abstract class Adapter { 20 | 21 | constructor(protected _worker: (first:Uri, ...more:Uri[]) => Promise) { 22 | } 23 | 24 | protected _positionToOffset(uri: Uri, position: monaco.IPosition): number { 25 | let model = monaco.editor.getModel(uri); 26 | return model.getOffsetAt(position); 27 | } 28 | 29 | protected _offsetToPosition(uri: Uri, offset: number): monaco.IPosition { 30 | let model = monaco.editor.getModel(uri); 31 | return model.getPositionAt(offset); 32 | } 33 | 34 | protected _textSpanToRange(uri: Uri, span: ts.TextSpan): monaco.IRange { 35 | let p1 = this._offsetToPosition(uri, span.start); 36 | let p2 = this._offsetToPosition(uri, span.start + span.length); 37 | let {lineNumber: startLineNumber, column: startColumn} = p1; 38 | let {lineNumber: endLineNumber, column: endColumn} = p2; 39 | return { startLineNumber, startColumn, endLineNumber, endColumn }; 40 | } 41 | } 42 | 43 | // --- diagnostics --- --- 44 | 45 | export class DiagnostcsAdapter extends Adapter { 46 | 47 | private _disposables: IDisposable[] = []; 48 | private _listener: { [uri: string]: IDisposable } = Object.create(null); 49 | 50 | constructor(private _defaults: LanguageServiceDefaults, private _selector: string, 51 | worker: (first: Uri, ...more: Uri[]) => Promise 52 | ) { 53 | super(worker); 54 | 55 | const onModelAdd = (model: monaco.editor.IModel): void => { 56 | if (model.getModeId() !== _selector) { 57 | return; 58 | } 59 | 60 | let handle: number; 61 | this._listener[model.uri.toString()] = model.onDidChangeContent(() => { 62 | clearTimeout(handle); 63 | handle = setTimeout(() => this._doValidate(model.uri), 500); 64 | }); 65 | 66 | this._doValidate(model.uri); 67 | }; 68 | 69 | const onModelRemoved = (model: monaco.editor.IModel): void => { 70 | delete this._listener[model.uri.toString()]; 71 | }; 72 | 73 | this._disposables.push(monaco.editor.onDidCreateModel(onModelAdd)); 74 | this._disposables.push(monaco.editor.onWillDisposeModel(onModelRemoved)); 75 | this._disposables.push(monaco.editor.onDidChangeModelLanguage(event => { 76 | onModelRemoved(event.model); 77 | onModelAdd(event.model); 78 | })); 79 | 80 | this._disposables.push({ 81 | dispose: () => { 82 | for (let key in this._listener) { 83 | this._listener[key].dispose(); 84 | } 85 | } 86 | }); 87 | 88 | monaco.editor.getModels().forEach(onModelAdd); 89 | } 90 | 91 | public dispose(): void { 92 | this._disposables.forEach(d => d && d.dispose()); 93 | this._disposables = []; 94 | } 95 | 96 | private _doValidate(resource: Uri): void { 97 | this._worker(resource).then(worker => { 98 | let promises: Promise[] = []; 99 | if (!this._defaults.diagnosticsOptions.noSyntaxValidation) { 100 | promises.push(worker.getSyntacticDiagnostics(resource.toString())); 101 | } 102 | if (!this._defaults.diagnosticsOptions.noSemanticValidation) { 103 | promises.push(worker.getSemanticDiagnostics(resource.toString())); 104 | } 105 | return Promise.join(promises); 106 | }).then(diagnostics => { 107 | const markers = diagnostics 108 | .reduce((p, c) => c.concat(p), []) 109 | .map(d => this._convertDiagnostics(resource, d)); 110 | 111 | monaco.editor.setModelMarkers(monaco.editor.getModel(resource), this._selector, markers); 112 | }).done(undefined, err => { 113 | console.error(err); 114 | }); 115 | } 116 | 117 | private _convertDiagnostics(resource: Uri, diag: ts.Diagnostic): monaco.editor.IMarkerData { 118 | const {lineNumber: startLineNumber, column: startColumn} = this._offsetToPosition(resource, diag.start); 119 | const {lineNumber: endLineNumber, column: endColumn} = this._offsetToPosition(resource, diag.start + diag.length); 120 | 121 | return { 122 | severity: monaco.Severity.Error, 123 | startLineNumber, 124 | startColumn, 125 | endLineNumber, 126 | endColumn, 127 | message: ts.flattenDiagnosticMessageText(diag.messageText, '\n') 128 | }; 129 | } 130 | } 131 | 132 | // --- suggest ------ 133 | 134 | interface MyCompletionItem extends monaco.languages.CompletionItem { 135 | uri: Uri; 136 | position: Position; 137 | } 138 | 139 | export class SuggestAdapter extends Adapter implements monaco.languages.CompletionItemProvider { 140 | 141 | public get triggerCharacters(): string[] { 142 | return ['.']; 143 | } 144 | 145 | provideCompletionItems(model:monaco.editor.IReadOnlyModel, position:Position, token:CancellationToken): Thenable { 146 | const wordInfo = model.getWordUntilPosition(position); 147 | const resource = model.uri; 148 | const offset = this._positionToOffset(resource, position); 149 | 150 | return wireCancellationToken(token, this._worker(resource).then(worker => { 151 | return worker.getCompletionsAtPosition(resource.toString(), offset); 152 | }).then(info => { 153 | if (!info) { 154 | return; 155 | } 156 | let suggestions: MyCompletionItem[] = info.entries.map(entry => { 157 | return { 158 | uri: resource, 159 | position: position, 160 | label: entry.name, 161 | sortText: entry.sortText, 162 | kind: SuggestAdapter.convertKind(entry.kind) 163 | }; 164 | }); 165 | 166 | return suggestions; 167 | })); 168 | } 169 | 170 | resolveCompletionItem(item: monaco.languages.CompletionItem, token: CancellationToken): Thenable { 171 | let myItem = item; 172 | const resource = myItem.uri; 173 | const position = myItem.position; 174 | 175 | return wireCancellationToken(token, this._worker(resource).then(worker => { 176 | return worker.getCompletionEntryDetails(resource.toString(), 177 | this._positionToOffset(resource, position), 178 | myItem.label); 179 | 180 | }).then(details => { 181 | if (!details) { 182 | return myItem; 183 | } 184 | return { 185 | uri: resource, 186 | position: position, 187 | label: details.name, 188 | kind: SuggestAdapter.convertKind(details.kind), 189 | detail: ts.displayPartsToString(details.displayParts), 190 | documentation: ts.displayPartsToString(details.documentation) 191 | }; 192 | })); 193 | } 194 | 195 | private static convertKind(kind: string): monaco.languages.CompletionItemKind { 196 | switch (kind) { 197 | case Kind.primitiveType: 198 | case Kind.keyword: 199 | return monaco.languages.CompletionItemKind.Keyword; 200 | case Kind.variable: 201 | case Kind.localVariable: 202 | return monaco.languages.CompletionItemKind.Variable; 203 | case Kind.memberVariable: 204 | case Kind.memberGetAccessor: 205 | case Kind.memberSetAccessor: 206 | return monaco.languages.CompletionItemKind.Field; 207 | case Kind.function: 208 | case Kind.memberFunction: 209 | case Kind.constructSignature: 210 | case Kind.callSignature: 211 | case Kind.indexSignature: 212 | return monaco.languages.CompletionItemKind.Function; 213 | case Kind.enum: 214 | return monaco.languages.CompletionItemKind.Enum; 215 | case Kind.module: 216 | return monaco.languages.CompletionItemKind.Module; 217 | case Kind.class: 218 | return monaco.languages.CompletionItemKind.Class; 219 | case Kind.interface: 220 | return monaco.languages.CompletionItemKind.Interface; 221 | case Kind.warning: 222 | return monaco.languages.CompletionItemKind.File; 223 | } 224 | 225 | return monaco.languages.CompletionItemKind.Property; 226 | } 227 | } 228 | 229 | export class SignatureHelpAdapter extends Adapter implements monaco.languages.SignatureHelpProvider { 230 | 231 | public signatureHelpTriggerCharacters = ['(', ',']; 232 | 233 | provideSignatureHelp(model: monaco.editor.IReadOnlyModel, position: Position, token: CancellationToken): Thenable { 234 | let resource = model.uri; 235 | return wireCancellationToken(token, this._worker(resource).then(worker => worker.getSignatureHelpItems(resource.toString(), this._positionToOffset(resource, position))).then(info => { 236 | 237 | if (!info) { 238 | return; 239 | } 240 | 241 | let ret:monaco.languages.SignatureHelp = { 242 | activeSignature: info.selectedItemIndex, 243 | activeParameter: info.argumentIndex, 244 | signatures: [] 245 | }; 246 | 247 | info.items.forEach(item => { 248 | 249 | let signature:monaco.languages.SignatureInformation = { 250 | label: '', 251 | documentation: null, 252 | parameters: [] 253 | }; 254 | 255 | signature.label += ts.displayPartsToString(item.prefixDisplayParts); 256 | item.parameters.forEach((p, i, a) => { 257 | let label = ts.displayPartsToString(p.displayParts); 258 | let parameter:monaco.languages.ParameterInformation = { 259 | label: label, 260 | documentation: ts.displayPartsToString(p.documentation) 261 | }; 262 | signature.label += label; 263 | signature.parameters.push(parameter); 264 | if (i < a.length - 1) { 265 | signature.label += ts.displayPartsToString(item.separatorDisplayParts); 266 | } 267 | }); 268 | signature.label += ts.displayPartsToString(item.suffixDisplayParts); 269 | ret.signatures.push(signature); 270 | }); 271 | 272 | return ret; 273 | 274 | })); 275 | } 276 | } 277 | 278 | // --- hover ------ 279 | 280 | export class QuickInfoAdapter extends Adapter implements monaco.languages.HoverProvider { 281 | 282 | provideHover(model:monaco.editor.IReadOnlyModel, position:Position, token:CancellationToken): Thenable { 283 | let resource = model.uri; 284 | 285 | return wireCancellationToken(token, this._worker(resource).then(worker => { 286 | return worker.getQuickInfoAtPosition(resource.toString(), this._positionToOffset(resource, position)); 287 | }).then(info => { 288 | if (!info) { 289 | return; 290 | } 291 | return { 292 | range: this._textSpanToRange(resource, info.textSpan), 293 | htmlContent: [{ text: ts.displayPartsToString(info.displayParts) }] 294 | }; 295 | })); 296 | } 297 | } 298 | 299 | // --- occurrences ------ 300 | 301 | export class OccurrencesAdapter extends Adapter implements monaco.languages.DocumentHighlightProvider { 302 | 303 | public provideDocumentHighlights(model: monaco.editor.IReadOnlyModel, position: Position, token: CancellationToken): Thenable { 304 | const resource = model.uri; 305 | 306 | return wireCancellationToken(token, this._worker(resource).then(worker => { 307 | return worker.getOccurrencesAtPosition(resource.toString(), this._positionToOffset(resource, position)); 308 | }).then(entries => { 309 | if (!entries) { 310 | return; 311 | } 312 | return entries.map(entry => { 313 | return { 314 | range: this._textSpanToRange(resource, entry.textSpan), 315 | kind: entry.isWriteAccess ? monaco.languages.DocumentHighlightKind.Write : monaco.languages.DocumentHighlightKind.Text 316 | }; 317 | }); 318 | })); 319 | } 320 | } 321 | 322 | // --- definition ------ 323 | 324 | export class DefinitionAdapter extends Adapter { 325 | 326 | public provideDefinition(model:monaco.editor.IReadOnlyModel, position:Position, token:CancellationToken): Thenable { 327 | const resource = model.uri; 328 | 329 | return wireCancellationToken(token, this._worker(resource).then(worker => { 330 | return worker.getDefinitionAtPosition(resource.toString(), this._positionToOffset(resource, position)); 331 | }).then(entries => { 332 | if (!entries) { 333 | return; 334 | } 335 | const result: monaco.languages.Location[] = []; 336 | for (let entry of entries) { 337 | const uri = Uri.parse(entry.fileName); 338 | if (monaco.editor.getModel(uri)) { 339 | result.push({ 340 | uri: uri, 341 | range: this._textSpanToRange(uri, entry.textSpan) 342 | }); 343 | } 344 | } 345 | return result; 346 | })); 347 | } 348 | } 349 | 350 | // --- references ------ 351 | 352 | export class ReferenceAdapter extends Adapter implements monaco.languages.ReferenceProvider { 353 | 354 | provideReferences(model:monaco.editor.IReadOnlyModel, position:Position, context: monaco.languages.ReferenceContext, token: CancellationToken): Thenable { 355 | const resource = model.uri; 356 | 357 | return wireCancellationToken(token, this._worker(resource).then(worker => { 358 | return worker.getReferencesAtPosition(resource.toString(), this._positionToOffset(resource, position)); 359 | }).then(entries => { 360 | if (!entries) { 361 | return; 362 | } 363 | const result: monaco.languages.Location[] = []; 364 | for (let entry of entries) { 365 | const uri = Uri.parse(entry.fileName); 366 | if (monaco.editor.getModel(uri)) { 367 | result.push({ 368 | uri: uri, 369 | range: this._textSpanToRange(uri, entry.textSpan) 370 | }); 371 | } 372 | } 373 | return result; 374 | })); 375 | } 376 | } 377 | 378 | // --- outline ------ 379 | 380 | export class OutlineAdapter extends Adapter implements monaco.languages.DocumentSymbolProvider { 381 | 382 | public provideDocumentSymbols(model:monaco.editor.IReadOnlyModel, token: CancellationToken): Thenable { 383 | const resource = model.uri; 384 | 385 | return wireCancellationToken(token, this._worker(resource).then(worker => worker.getNavigationBarItems(resource.toString())).then(items => { 386 | if (!items) { 387 | return; 388 | } 389 | 390 | function convert(bucket: monaco.languages.SymbolInformation[], item: ts.NavigationBarItem, containerLabel?: string): void { 391 | let result: monaco.languages.SymbolInformation = { 392 | name: item.text, 393 | kind: outlineTypeTable[item.kind] || monaco.languages.SymbolKind.Variable, 394 | location: { 395 | uri: resource, 396 | range: this._textSpanToRange(resource, item.spans[0]) 397 | }, 398 | containerName: containerLabel 399 | }; 400 | 401 | if (item.childItems && item.childItems.length > 0) { 402 | for (let child of item.childItems) { 403 | convert(bucket, child, result.name); 404 | } 405 | } 406 | 407 | bucket.push(result); 408 | } 409 | 410 | let result: monaco.languages.SymbolInformation[] = []; 411 | items.forEach(item => convert(result, item)); 412 | return result; 413 | })); 414 | } 415 | } 416 | 417 | export class Kind { 418 | public static unknown:string = ''; 419 | public static keyword:string = 'keyword'; 420 | public static script:string = 'script'; 421 | public static module:string = 'module'; 422 | public static class:string = 'class'; 423 | public static interface:string = 'interface'; 424 | public static type:string = 'type'; 425 | public static enum:string = 'enum'; 426 | public static variable:string = 'var'; 427 | public static localVariable:string = 'local var'; 428 | public static function:string = 'function'; 429 | public static localFunction:string = 'local function'; 430 | public static memberFunction:string = 'method'; 431 | public static memberGetAccessor:string = 'getter'; 432 | public static memberSetAccessor:string = 'setter'; 433 | public static memberVariable:string = 'property'; 434 | public static constructorImplementation:string = 'constructor'; 435 | public static callSignature:string = 'call'; 436 | public static indexSignature:string = 'index'; 437 | public static constructSignature:string = 'construct'; 438 | public static parameter:string = 'parameter'; 439 | public static typeParameter:string = 'type parameter'; 440 | public static primitiveType:string = 'primitive type'; 441 | public static label:string = 'label'; 442 | public static alias:string = 'alias'; 443 | public static const:string = 'const'; 444 | public static let:string = 'let'; 445 | public static warning:string = 'warning'; 446 | } 447 | 448 | let outlineTypeTable: { [kind: string]: monaco.languages.SymbolKind } = Object.create(null); 449 | outlineTypeTable[Kind.module] = monaco.languages.SymbolKind.Module; 450 | outlineTypeTable[Kind.class] = monaco.languages.SymbolKind.Class; 451 | outlineTypeTable[Kind.enum] = monaco.languages.SymbolKind.Enum; 452 | outlineTypeTable[Kind.interface] = monaco.languages.SymbolKind.Interface; 453 | outlineTypeTable[Kind.memberFunction] = monaco.languages.SymbolKind.Method; 454 | outlineTypeTable[Kind.memberVariable] = monaco.languages.SymbolKind.Property; 455 | outlineTypeTable[Kind.memberGetAccessor] = monaco.languages.SymbolKind.Property; 456 | outlineTypeTable[Kind.memberSetAccessor] = monaco.languages.SymbolKind.Property; 457 | outlineTypeTable[Kind.variable] = monaco.languages.SymbolKind.Variable; 458 | outlineTypeTable[Kind.const] = monaco.languages.SymbolKind.Variable; 459 | outlineTypeTable[Kind.localVariable] = monaco.languages.SymbolKind.Variable; 460 | outlineTypeTable[Kind.variable] = monaco.languages.SymbolKind.Variable; 461 | outlineTypeTable[Kind.function] = monaco.languages.SymbolKind.Function; 462 | outlineTypeTable[Kind.localFunction] = monaco.languages.SymbolKind.Function; 463 | 464 | // --- formatting ---- 465 | 466 | export abstract class FormatHelper extends Adapter { 467 | protected static _convertOptions(options: monaco.languages.IFormattingOptions): ts.FormatCodeOptions { 468 | return { 469 | ConvertTabsToSpaces: options.insertSpaces, 470 | TabSize: options.tabSize, 471 | IndentSize: options.tabSize, 472 | IndentStyle: ts.IndentStyle.Smart, 473 | NewLineCharacter: '\n', 474 | InsertSpaceAfterCommaDelimiter: true, 475 | InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false, 476 | InsertSpaceAfterKeywordsInControlFlowStatements: false, 477 | InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: true, 478 | InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: true, 479 | InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: true, 480 | InsertSpaceAfterSemicolonInForStatements: false, 481 | InsertSpaceBeforeAndAfterBinaryOperators: true, 482 | PlaceOpenBraceOnNewLineForControlBlocks: false, 483 | PlaceOpenBraceOnNewLineForFunctions: false 484 | }; 485 | } 486 | 487 | protected _convertTextChanges(uri: Uri, change: ts.TextChange): monaco.editor.ISingleEditOperation { 488 | return { 489 | text: change.newText, 490 | range: this._textSpanToRange(uri, change.span) 491 | }; 492 | } 493 | } 494 | 495 | export class FormatAdapter extends FormatHelper implements monaco.languages.DocumentRangeFormattingEditProvider { 496 | 497 | provideDocumentRangeFormattingEdits(model: monaco.editor.IReadOnlyModel, range: Range, options: monaco.languages.IFormattingOptions, token: CancellationToken): Thenable { 498 | const resource = model.uri; 499 | 500 | return wireCancellationToken(token, this._worker(resource).then(worker => { 501 | return worker.getFormattingEditsForRange(resource.toString(), 502 | this._positionToOffset(resource, { lineNumber: range.startLineNumber, column: range.startColumn }), 503 | this._positionToOffset(resource, { lineNumber: range.endLineNumber, column: range.endColumn }), 504 | FormatHelper._convertOptions(options)); 505 | }).then(edits => { 506 | if (edits) { 507 | return edits.map(edit => this._convertTextChanges(resource, edit)); 508 | } 509 | })); 510 | } 511 | } 512 | 513 | export class FormatOnTypeAdapter extends FormatHelper implements monaco.languages.OnTypeFormattingEditProvider { 514 | 515 | get autoFormatTriggerCharacters() { 516 | return [';', '}', '\n']; 517 | } 518 | 519 | provideOnTypeFormattingEdits(model: monaco.editor.IReadOnlyModel, position: Position, ch: string, options: monaco.languages.IFormattingOptions, token: CancellationToken): Thenable { 520 | const resource = model.uri; 521 | 522 | return wireCancellationToken(token, this._worker(resource).then(worker => { 523 | return worker.getFormattingEditsAfterKeystroke(resource.toString(), 524 | this._positionToOffset(resource, position), 525 | ch, FormatHelper._convertOptions(options)); 526 | }).then(edits => { 527 | if (edits) { 528 | return edits.map(edit => this._convertTextChanges(resource, edit)); 529 | } 530 | })); 531 | } 532 | } 533 | 534 | /** 535 | * Hook a cancellation token to a WinJS Promise 536 | */ 537 | function wireCancellationToken(token: CancellationToken, promise: Promise): Thenable { 538 | token.onCancellationRequested(() => promise.cancel()); 539 | return promise; 540 | } 541 | -------------------------------------------------------------------------------- /src/mode.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 'use strict'; 6 | 7 | import {Language, createTokenizationSupport} from './tokenization'; 8 | import {LanguageServiceDefaults, typeScriptDefaults, javaScriptDefaults, LanguageServiceMode} from './typescript'; 9 | import {WorkerManager} from './workerManager'; 10 | import {TypeScriptWorker} from './worker'; 11 | import * as languageFeatures from './languageFeatures'; 12 | 13 | import Promise = monaco.Promise; 14 | import Uri = monaco.Uri; 15 | import IDisposable = monaco.IDisposable; 16 | 17 | export function setupTypeScript(): void { 18 | setupMode( 19 | typeScriptDefaults, 20 | 'typescript', 21 | Language.TypeScript 22 | ); 23 | } 24 | 25 | export function setupJavaScript(): void { 26 | setupMode( 27 | javaScriptDefaults, 28 | 'javascript', 29 | Language.EcmaScript5 30 | ); 31 | } 32 | 33 | function setupMode(defaults:LanguageServiceDefaults, modeId:string, language:Language): void { 34 | 35 | let disposables: IDisposable[] = []; 36 | 37 | const client = new WorkerManager(defaults); 38 | disposables.push(client); 39 | 40 | const worker = (first: Uri, ...more: Uri[]): Promise => { 41 | return client.getLanguageServiceWorker(...[first].concat(more)); 42 | }; 43 | 44 | disposables.push(monaco.languages.registerCompletionItemProvider(modeId, new languageFeatures.SuggestAdapter(worker))); 45 | disposables.push(monaco.languages.registerSignatureHelpProvider(modeId, new languageFeatures.SignatureHelpAdapter(worker))); 46 | disposables.push(monaco.languages.registerHoverProvider(modeId, new languageFeatures.QuickInfoAdapter(worker))); 47 | disposables.push(monaco.languages.registerDocumentHighlightProvider(modeId, new languageFeatures.OccurrencesAdapter(worker))); 48 | disposables.push(monaco.languages.registerDefinitionProvider(modeId, new languageFeatures.DefinitionAdapter(worker))); 49 | disposables.push(monaco.languages.registerReferenceProvider(modeId, new languageFeatures.ReferenceAdapter(worker))); 50 | disposables.push(monaco.languages.registerDocumentSymbolProvider(modeId, new languageFeatures.OutlineAdapter(worker))); 51 | disposables.push(monaco.languages.registerDocumentRangeFormattingEditProvider(modeId, new languageFeatures.FormatAdapter(worker))); 52 | disposables.push(monaco.languages.registerOnTypeFormattingEditProvider(modeId, new languageFeatures.FormatOnTypeAdapter(worker))); 53 | disposables.push(new languageFeatures.DiagnostcsAdapter(defaults, modeId, worker)); 54 | disposables.push(monaco.languages.setLanguageConfiguration(modeId, richEditConfiguration)); 55 | disposables.push(monaco.languages.setTokensProvider(modeId, createTokenizationSupport(language))); 56 | } 57 | 58 | const richEditConfiguration:monaco.languages.IRichLanguageConfiguration = { 59 | wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g, 60 | 61 | comments: { 62 | lineComment: '//', 63 | blockComment: ['/*', '*/'] 64 | }, 65 | 66 | brackets: [ 67 | ['{', '}'], 68 | ['[', ']'], 69 | ['(', ')'] 70 | ], 71 | 72 | onEnterRules: [ 73 | { 74 | // e.g. /** | */ 75 | beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/, 76 | afterText: /^\s*\*\/$/, 77 | action: { indentAction: monaco.languages.IndentAction.IndentOutdent, appendText: ' * ' } 78 | }, 79 | { 80 | // e.g. /** ...| 81 | beforeText: /^\s*\/\*\*(?!\/)([^\*]|\*(?!\/))*$/, 82 | action: { indentAction: monaco.languages.IndentAction.None, appendText: ' * ' } 83 | }, 84 | { 85 | // e.g. * ...| 86 | beforeText: /^(\t|(\ \ ))*\ \*(\ ([^\*]|\*(?!\/))*)?$/, 87 | action: { indentAction: monaco.languages.IndentAction.None, appendText: '* ' } 88 | }, 89 | { 90 | // e.g. */| 91 | beforeText: /^(\t|(\ \ ))*\ \*\/\s*$/, 92 | action: { indentAction: monaco.languages.IndentAction.None, removeText: 1 } 93 | } 94 | ], 95 | 96 | __electricCharacterSupport: { 97 | docComment: {scope:'comment.doc', open:'/**', lineStart:' * ', close:' */'} 98 | }, 99 | 100 | autoClosingPairs: [ 101 | { open: '{', close: '}' }, 102 | { open: '[', close: ']' }, 103 | { open: '(', close: ')' }, 104 | { open: '"', close: '"', notIn: ['string'] }, 105 | { open: '\'', close: '\'', notIn: ['string', 'comment'] }, 106 | { open: '`', close: '`' } 107 | ] 108 | }; 109 | 110 | 111 | -------------------------------------------------------------------------------- /src/monaco.contribution.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 'use strict'; 6 | 7 | import * as mode from './mode'; 8 | 9 | declare var require:(moduleId:[string], callback:(module:T)=>void)=>void; 10 | 11 | function withMode(callback:(module:typeof mode)=>void): void { 12 | require(['vs/language/typescript/src/mode'], callback); 13 | } 14 | 15 | monaco.languages.register({ 16 | id: 'typescript', 17 | extensions: ['.ts'], 18 | aliases: ['TypeScript', 'ts', 'typescript'], 19 | mimetypes: ['text/typescript'] 20 | }); 21 | monaco.languages.onLanguage('typescript', () => { 22 | withMode((mode) => mode.setupTypeScript()); 23 | }); 24 | 25 | monaco.languages.register({ 26 | id: 'javascript', 27 | extensions: ['.js', '.es6'], 28 | firstLine: '^#!.*\\bnode', 29 | filenames: ['jakefile'], 30 | aliases: ['JavaScript', 'javascript', 'js'], 31 | mimetypes: ['text/javascript'], 32 | }); 33 | monaco.languages.onLanguage('javascript', () => { 34 | withMode((mode) => mode.setupJavaScript()); 35 | }); 36 | -------------------------------------------------------------------------------- /src/tokenization.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 'use strict'; 6 | 7 | import ts = require('../lib/typescriptServices'); 8 | 9 | export enum Language { 10 | TypeScript, 11 | EcmaScript5 12 | } 13 | 14 | export function createTokenizationSupport(language:Language): monaco.languages.TokensProvider { 15 | 16 | var classifier = ts.createClassifier(), 17 | bracketTypeTable = language === Language.TypeScript ? tsBracketTypeTable : jsBracketTypeTable, 18 | tokenTypeTable = language === Language.TypeScript ? tsTokenTypeTable : jsTokenTypeTable; 19 | 20 | return { 21 | getInitialState: () => new State(language, ts.EndOfLineState.None, false), 22 | tokenize: (line, state) => tokenize(bracketTypeTable, tokenTypeTable, classifier, state, line) 23 | }; 24 | } 25 | 26 | class State implements monaco.languages.IState { 27 | 28 | public language: Language; 29 | public eolState: ts.EndOfLineState; 30 | public inJsDocComment: boolean; 31 | 32 | constructor(language:Language, eolState: ts.EndOfLineState, inJsDocComment: boolean) { 33 | this.language = language; 34 | this.eolState = eolState; 35 | this.inJsDocComment = inJsDocComment; 36 | } 37 | 38 | public clone(): State { 39 | return new State(this.language, this.eolState, this.inJsDocComment); 40 | } 41 | 42 | public equals(other:monaco.languages.IState):boolean { 43 | if(other === this) { 44 | return true; 45 | } 46 | if(!other || !(other instanceof State)) { 47 | return false; 48 | } 49 | if (this.eolState !== ( other).eolState) { 50 | return false; 51 | } 52 | if(this.inJsDocComment !== ( other).inJsDocComment) { 53 | return false; 54 | } 55 | return true; 56 | } 57 | } 58 | 59 | function tokenize(bracketTypeTable: { [i: number]: string }, tokenTypeTable: { [i: number]: string }, 60 | classifier: ts.Classifier, state: State, text: string): monaco.languages.ILineTokens { 61 | 62 | // Create result early and fill in tokens 63 | var ret = { 64 | tokens: [], 65 | endState: new State(state.language, ts.EndOfLineState.None, false) 66 | }; 67 | 68 | function appendFn(startIndex:number, type:string):void { 69 | if(ret.tokens.length === 0 || ret.tokens[ret.tokens.length - 1].scopes !== type) { 70 | ret.tokens.push({ 71 | startIndex: startIndex, 72 | scopes: type 73 | }); 74 | } 75 | } 76 | 77 | var isTypeScript = state.language === Language.TypeScript; 78 | 79 | // shebang statement, #! /bin/node 80 | if (!isTypeScript && checkSheBang(0, text, appendFn)) { 81 | return ret; 82 | } 83 | 84 | var result = classifier.getClassificationsForLine(text, state.eolState, true), 85 | offset = 0; 86 | 87 | ret.endState.eolState = result.finalLexState; 88 | ret.endState.inJsDocComment = result.finalLexState === ts.EndOfLineState.InMultiLineCommentTrivia && (state.inJsDocComment || /\/\*\*.*$/.test(text)); 89 | 90 | for (let entry of result.entries) { 91 | 92 | var type: string; 93 | 94 | if (entry.classification === ts.TokenClass.Punctuation) { 95 | // punctions: check for brackets: (){}[] 96 | var ch = text.charCodeAt(offset); 97 | type = bracketTypeTable[ch] || tokenTypeTable[entry.classification]; 98 | appendFn(offset, type); 99 | 100 | } else if (entry.classification === ts.TokenClass.Comment) { 101 | // comments: check for JSDoc, block, and line comments 102 | if (ret.endState.inJsDocComment || /\/\*\*.*\*\//.test(text.substr(offset, entry.length))) { 103 | appendFn(offset, isTypeScript ? 'comment.doc.ts' : 'comment.doc.js'); 104 | } else { 105 | appendFn(offset, isTypeScript ? 'comment.ts' : 'comment.js'); 106 | } 107 | } else { 108 | // everything else 109 | appendFn(offset, 110 | tokenTypeTable[entry.classification] || ''); 111 | } 112 | 113 | offset += entry.length; 114 | } 115 | 116 | return ret; 117 | } 118 | 119 | interface INumberStringDictionary { 120 | [idx: number]: string; 121 | } 122 | 123 | var tsBracketTypeTable:INumberStringDictionary = Object.create(null); 124 | tsBracketTypeTable['('.charCodeAt(0)] = 'delimiter.parenthesis.ts'; 125 | tsBracketTypeTable[')'.charCodeAt(0)] = 'delimiter.parenthesis.ts'; 126 | tsBracketTypeTable['{'.charCodeAt(0)] = 'delimiter.bracket.ts'; 127 | tsBracketTypeTable['}'.charCodeAt(0)] = 'delimiter.bracket.ts'; 128 | tsBracketTypeTable['['.charCodeAt(0)] = 'delimiter.array.ts'; 129 | tsBracketTypeTable[']'.charCodeAt(0)] = 'delimiter.array.ts'; 130 | 131 | var tsTokenTypeTable:INumberStringDictionary = Object.create(null); 132 | tsTokenTypeTable[ts.TokenClass.Identifier] = 'identifier.ts'; 133 | tsTokenTypeTable[ts.TokenClass.Keyword] = 'keyword.ts'; 134 | tsTokenTypeTable[ts.TokenClass.Operator] = 'delimiter.ts'; 135 | tsTokenTypeTable[ts.TokenClass.Punctuation] = 'delimiter.ts'; 136 | tsTokenTypeTable[ts.TokenClass.NumberLiteral] = 'number.ts'; 137 | tsTokenTypeTable[ts.TokenClass.RegExpLiteral] = 'regexp.ts'; 138 | tsTokenTypeTable[ts.TokenClass.StringLiteral] = 'string.ts'; 139 | 140 | var jsBracketTypeTable:INumberStringDictionary = Object.create(null); 141 | jsBracketTypeTable['('.charCodeAt(0)] = 'delimiter.parenthesis.js'; 142 | jsBracketTypeTable[')'.charCodeAt(0)] = 'delimiter.parenthesis.js'; 143 | jsBracketTypeTable['{'.charCodeAt(0)] = 'delimiter.bracket.js'; 144 | jsBracketTypeTable['}'.charCodeAt(0)] = 'delimiter.bracket.js'; 145 | jsBracketTypeTable['['.charCodeAt(0)] = 'delimiter.array.js'; 146 | jsBracketTypeTable[']'.charCodeAt(0)] = 'delimiter.array.js'; 147 | 148 | var jsTokenTypeTable:INumberStringDictionary = Object.create(null); 149 | jsTokenTypeTable[ts.TokenClass.Identifier] = 'identifier.js'; 150 | jsTokenTypeTable[ts.TokenClass.Keyword] = 'keyword.js'; 151 | jsTokenTypeTable[ts.TokenClass.Operator] = 'delimiter.js'; 152 | jsTokenTypeTable[ts.TokenClass.Punctuation] = 'delimiter.js'; 153 | jsTokenTypeTable[ts.TokenClass.NumberLiteral] = 'number.js'; 154 | jsTokenTypeTable[ts.TokenClass.RegExpLiteral] = 'regexp.js'; 155 | jsTokenTypeTable[ts.TokenClass.StringLiteral] = 'string.js'; 156 | 157 | 158 | function checkSheBang(deltaOffset: number, line: string, appendFn: (startIndex: number, type: string) => void): boolean { 159 | if (line.indexOf('#!') === 0) { 160 | appendFn(deltaOffset, 'comment.shebang'); 161 | return true; 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /src/typescript.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 'use strict'; 6 | 7 | import * as ts from '../lib/typescriptServices'; 8 | import {TypeScriptWorker} from './worker'; 9 | 10 | import Emitter = monaco.Emitter; 11 | import Promise = monaco.Promise; 12 | import Uri = monaco.Uri; 13 | import IDisposable = monaco.IDisposable; 14 | 15 | // --- TypeScript configuration and defaults --------- 16 | 17 | export interface DiagnosticsOptions { 18 | noSemanticValidation?: boolean; 19 | noSyntaxValidation?: boolean; 20 | } 21 | 22 | export class LanguageServiceDefaults { 23 | 24 | private _onDidChange = new Emitter(); 25 | private _extraLibs: { [path: string]: string }; 26 | private _compilerOptions: ts.CompilerOptions; 27 | private _diagnosticsOptions: DiagnosticsOptions; 28 | 29 | constructor(compilerOptions: ts.CompilerOptions, diagnosticsOptions: DiagnosticsOptions) { 30 | this._extraLibs = Object.create(null); 31 | this.setCompilerOptions(compilerOptions); 32 | this.setDiagnosticsOptions(diagnosticsOptions); 33 | } 34 | 35 | get onDidChange(): monaco.IEvent{ 36 | return this._onDidChange.event; 37 | } 38 | 39 | get extraLibs(): { [path: string]: string } { 40 | return Object.freeze(this._extraLibs); 41 | } 42 | 43 | addExtraLib(content: string, filePath?: string): IDisposable { 44 | if (typeof filePath === 'undefined') { 45 | filePath = `ts:extralib-${Date.now()}`; 46 | } 47 | 48 | if (this._extraLibs[filePath]) { 49 | throw new Error(`${filePath} already a extra lib`); 50 | } 51 | 52 | this._extraLibs[filePath] = content; 53 | this._onDidChange.fire(this); 54 | 55 | return { 56 | dispose: () => { 57 | if (delete this._extraLibs[filePath]) { 58 | this._onDidChange.fire(this); 59 | } 60 | } 61 | }; 62 | } 63 | 64 | get compilerOptions(): ts.CompilerOptions { 65 | return this._compilerOptions; 66 | } 67 | 68 | setCompilerOptions(options: ts.CompilerOptions): void { 69 | this._compilerOptions = options || Object.create(null); 70 | this._onDidChange.fire(this); 71 | } 72 | 73 | get diagnosticsOptions(): DiagnosticsOptions { 74 | return this._diagnosticsOptions; 75 | } 76 | 77 | setDiagnosticsOptions(options: DiagnosticsOptions): void { 78 | this._diagnosticsOptions = options || Object.create(null); 79 | this._onDidChange.fire(this); 80 | } 81 | } 82 | 83 | export const typeScriptDefaults = new LanguageServiceDefaults( 84 | { allowNonTsExtensions: true, target: ts.ScriptTarget.Latest }, 85 | { noSemanticValidation: false, noSyntaxValidation: false }); 86 | 87 | export const javaScriptDefaults = new LanguageServiceDefaults( 88 | { allowNonTsExtensions: true, allowJs: true, target: ts.ScriptTarget.Latest }, 89 | { noSemanticValidation: true, noSyntaxValidation: false }); 90 | 91 | 92 | // --- TypeScript worker protocol --------- 93 | 94 | export interface LanguageServiceMode { 95 | getLanguageServiceWorker(...resources: Uri[]): Promise; 96 | } 97 | -------------------------------------------------------------------------------- /src/worker.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 'use strict'; 6 | 7 | import ts = require('../lib/typescriptServices'); 8 | import {contents as libdts} from '../lib/lib-ts'; 9 | import {contents as libes6ts} from '../lib/lib-es6-ts'; 10 | 11 | import Promise = monaco.Promise; 12 | 13 | const DEFAULT_LIB = { 14 | NAME: 'defaultLib:lib.d.ts', 15 | CONTENTS: libdts 16 | }; 17 | 18 | const ES6_LIB = { 19 | NAME: 'defaultLib:lib.es6.d.ts', 20 | CONTENTS: libes6ts 21 | }; 22 | 23 | export class TypeScriptWorker implements ts.LanguageServiceHost { 24 | 25 | // --- model sync ----------------------- 26 | 27 | // private _models: { [uri: string]: MirrorModel2 } = Object.create(null); 28 | private _extraLibs: { [fileName: string]: string } = Object.create(null); 29 | private _languageService = ts.createLanguageService(this); 30 | private _compilerOptions: ts.CompilerOptions; 31 | 32 | // --- default --------- 33 | 34 | acceptDefaults(options:ts.CompilerOptions, extraLibs:{ [path: string]: string }): Promise { 35 | this._compilerOptions = options; 36 | this._extraLibs = extraLibs; 37 | return; 38 | } 39 | 40 | // --- language service host --------------- 41 | 42 | getCompilationSettings(): ts.CompilerOptions { 43 | return this._compilerOptions; 44 | } 45 | 46 | getScriptFileNames(): string[] { 47 | let models = monaco.worker.mirrorModels.map(model => model.uri.toString()); 48 | return models.concat(Object.keys(this._extraLibs)); 49 | } 50 | 51 | private _getModel(fileName:string): monaco.worker.IMirrorModel { 52 | let models = monaco.worker.mirrorModels; 53 | for (let i = 0; i < models.length; i++) { 54 | if (models[i].uri.toString() === fileName) { 55 | return models[i]; 56 | } 57 | } 58 | return null; 59 | } 60 | 61 | getScriptVersion(fileName: string): string { 62 | let model = this._getModel(fileName); 63 | if (model) { 64 | return model.version.toString(); 65 | } else if (this.isDefaultLibFileName(fileName) || fileName in this._extraLibs) { 66 | // extra lib and default lib are static 67 | return '1'; 68 | } 69 | } 70 | 71 | getScriptSnapshot(fileName: string): ts.IScriptSnapshot { 72 | let text: string; 73 | let model = this._getModel(fileName); 74 | if (model) { 75 | // a true editor model 76 | text = model.getText(); 77 | 78 | } else if (fileName in this._extraLibs) { 79 | // static extra lib 80 | text = this._extraLibs[fileName]; 81 | 82 | } else if (fileName === DEFAULT_LIB.NAME) { 83 | text = DEFAULT_LIB.CONTENTS; 84 | } else if (fileName === ES6_LIB.NAME) { 85 | text = ES6_LIB.CONTENTS; 86 | } else { 87 | return; 88 | } 89 | 90 | return { 91 | getText: (start, end) => text.substring(start, end), 92 | getLength: () => text.length, 93 | getChangeRange: () => undefined 94 | }; 95 | } 96 | 97 | getCurrentDirectory(): string { 98 | return ''; 99 | } 100 | 101 | getDefaultLibFileName(options: ts.CompilerOptions): string { 102 | // TODO@joh support lib.es7.d.ts 103 | return options.target > ts.ScriptTarget.ES5 ? DEFAULT_LIB.NAME : ES6_LIB.NAME; 104 | } 105 | 106 | isDefaultLibFileName(fileName: string): boolean { 107 | return fileName === this.getDefaultLibFileName(this._compilerOptions); 108 | } 109 | 110 | // --- language features 111 | 112 | getSyntacticDiagnostics(fileName: string): Promise { 113 | const diagnostics = this._languageService.getSyntacticDiagnostics(fileName); 114 | diagnostics.forEach(diag => diag.file = undefined); // diag.file cannot be JSON'yfied 115 | return Promise.as(diagnostics); 116 | } 117 | 118 | getSemanticDiagnostics(fileName: string): Promise { 119 | const diagnostics = this._languageService.getSemanticDiagnostics(fileName); 120 | diagnostics.forEach(diag => diag.file = undefined); // diag.file cannot be JSON'yfied 121 | return Promise.as(diagnostics); 122 | } 123 | 124 | getCompilerOptionsDiagnostics(fileName: string): Promise { 125 | const diagnostics = this._languageService.getCompilerOptionsDiagnostics(); 126 | diagnostics.forEach(diag => diag.file = undefined); // diag.file cannot be JSON'yfied 127 | return Promise.as(diagnostics); 128 | } 129 | 130 | getCompletionsAtPosition(fileName: string, position:number): Promise { 131 | return Promise.as(this._languageService.getCompletionsAtPosition(fileName, position)); 132 | } 133 | 134 | getCompletionEntryDetails(fileName: string, position: number, entry: string): Promise { 135 | return Promise.as(this._languageService.getCompletionEntryDetails(fileName, position, entry)); 136 | } 137 | 138 | getSignatureHelpItems(fileName: string, position:number): Promise { 139 | return Promise.as(this._languageService.getSignatureHelpItems(fileName, position)); 140 | } 141 | 142 | getQuickInfoAtPosition(fileName: string, position: number): Promise { 143 | return Promise.as(this._languageService.getQuickInfoAtPosition(fileName, position)); 144 | } 145 | 146 | getOccurrencesAtPosition(fileName: string, position: number): Promise { 147 | return Promise.as(this._languageService.getOccurrencesAtPosition(fileName, position)); 148 | } 149 | 150 | getDefinitionAtPosition(fileName: string, position: number): Promise { 151 | return Promise.as(this._languageService.getDefinitionAtPosition(fileName, position)); 152 | } 153 | 154 | getReferencesAtPosition(fileName: string, position: number): Promise { 155 | return Promise.as(this._languageService.getReferencesAtPosition(fileName, position)); 156 | } 157 | 158 | getNavigationBarItems(fileName: string): Promise { 159 | return Promise.as(this._languageService.getNavigationBarItems(fileName)); 160 | } 161 | 162 | getFormattingEditsForDocument(fileName: string, options: ts.FormatCodeOptions): Promise { 163 | return Promise.as(this._languageService.getFormattingEditsForDocument(fileName, options)); 164 | } 165 | 166 | getFormattingEditsForRange(fileName: string, start: number, end: number, options: ts.FormatCodeOptions): Promise { 167 | return Promise.as(this._languageService.getFormattingEditsForRange(fileName, start, end, options)); 168 | } 169 | 170 | getFormattingEditsAfterKeystroke(fileName: string, postion: number, ch: string, options: ts.FormatCodeOptions): Promise { 171 | return Promise.as(this._languageService.getFormattingEditsAfterKeystroke(fileName, postion, ch, options)); 172 | } 173 | 174 | getEmitOutput(fileName: string): Promise { 175 | return Promise.as(this._languageService.getEmitOutput(fileName)); 176 | } 177 | } 178 | 179 | export function create(): TypeScriptWorker { 180 | return new TypeScriptWorker(); 181 | } 182 | -------------------------------------------------------------------------------- /src/workerManager.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 'use strict'; 6 | 7 | import {LanguageServiceMode, LanguageServiceDefaults} from './typescript'; 8 | import {TypeScriptWorker} from './worker'; 9 | 10 | import Promise = monaco.Promise; 11 | import IDisposable = monaco.IDisposable; 12 | import Uri = monaco.Uri; 13 | 14 | const STOP_WHEN_IDLE_FOR = 2 * 60 * 1000; // 2min 15 | 16 | export class WorkerManager { 17 | 18 | private _defaults: LanguageServiceDefaults; 19 | private _idleCheckInterval: number; 20 | private _lastUsedTime: number; 21 | private _configChangeListener: IDisposable; 22 | 23 | private _worker: monaco.editor.MonacoWebWorker; 24 | private _client: Promise; 25 | 26 | constructor(defaults: LanguageServiceDefaults) { 27 | this._defaults = defaults; 28 | this._worker = null; 29 | this._idleCheckInterval = setInterval(() => this._checkIfIdle(), 30 * 1000); 30 | this._lastUsedTime = 0; 31 | this._configChangeListener = this._defaults.onDidChange(() => this._stopWorker()); 32 | } 33 | 34 | private _stopWorker(): void { 35 | if (this._worker) { 36 | this._worker.dispose(); 37 | this._worker = null; 38 | } 39 | this._client = null; 40 | } 41 | 42 | dispose(): void { 43 | clearInterval(this._idleCheckInterval); 44 | this._configChangeListener.dispose(); 45 | this._stopWorker(); 46 | } 47 | 48 | private _checkIfIdle(): void { 49 | if (!this._worker) { 50 | return; 51 | } 52 | let timePassedSinceLastUsed = Date.now() - this._lastUsedTime; 53 | if (timePassedSinceLastUsed > STOP_WHEN_IDLE_FOR) { 54 | this._stopWorker(); 55 | } 56 | } 57 | 58 | private _getClient(): Promise { 59 | this._lastUsedTime = Date.now(); 60 | 61 | if (!this._client) { 62 | this._worker = monaco.editor.createWebWorker({ 63 | moduleId: 'vs/language/typescript/src/worker', 64 | }); 65 | 66 | let _client:TypeScriptWorker = null; 67 | 68 | // avoid cancellation 69 | this._client = toShallowCancelPromise( 70 | this._worker.getProxy().then((client) => { 71 | _client = client; 72 | }).then(_ => { 73 | const {compilerOptions, extraLibs} = this._defaults; 74 | return _client.acceptDefaults(compilerOptions, extraLibs); 75 | }).then(_ => _client) 76 | ); 77 | } 78 | 79 | return this._client; 80 | } 81 | 82 | getLanguageServiceWorker(...resources: Uri[]): Promise { 83 | let _client:TypeScriptWorker; 84 | return this._getClient().then((client) => { 85 | _client = client 86 | }).then(_ => { 87 | return this._worker.withSyncedResources(resources) 88 | }).then(_ => _client); 89 | } 90 | } 91 | 92 | function toShallowCancelPromise(p:Promise): Promise { 93 | let completeCallback: (value:T)=>void; 94 | let errorCallback: (err:any)=>void; 95 | 96 | let r = new Promise((c, e) => { 97 | completeCallback = c; 98 | errorCallback = e; 99 | }, () => { }); 100 | 101 | p.then(completeCallback, errorCallback); 102 | 103 | return r; 104 | } 105 | -------------------------------------------------------------------------------- /test/all.js: -------------------------------------------------------------------------------- 1 | var requirejs = require("requirejs"); 2 | 3 | requirejs.config({ 4 | baseUrl: 'out', 5 | nodeRequire: require 6 | }); 7 | 8 | requirejs([ 9 | 'test/tokenization.test' 10 | ], function() { 11 | run(); // We can launch the tests! 12 | }); -------------------------------------------------------------------------------- /test/assert.d.ts: -------------------------------------------------------------------------------- 1 | declare module "assert" { 2 | function internal (value: any, message?: string): void; 3 | namespace internal { 4 | export class AssertionError implements Error { 5 | name: string; 6 | message: string; 7 | actual: any; 8 | expected: any; 9 | operator: string; 10 | generatedMessage: boolean; 11 | 12 | constructor(options?: {message?: string; actual?: any; expected?: any; 13 | operator?: string; stackStartFunction?: Function}); 14 | } 15 | 16 | export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; 17 | export function ok(value: any, message?: string): void; 18 | export function equal(actual: any, expected: any, message?: string): void; 19 | export function notEqual(actual: any, expected: any, message?: string): void; 20 | export function deepEqual(actual: any, expected: any, message?: string): void; 21 | export function notDeepEqual(acutal: any, expected: any, message?: string): void; 22 | export function strictEqual(actual: any, expected: any, message?: string): void; 23 | export function notStrictEqual(actual: any, expected: any, message?: string): void; 24 | export function deepStrictEqual(actual: any, expected: any, message?: string): void; 25 | export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; 26 | export var throws: { 27 | (block: Function, message?: string): void; 28 | (block: Function, error: Function, message?: string): void; 29 | (block: Function, error: RegExp, message?: string): void; 30 | (block: Function, error: (err: any) => boolean, message?: string): void; 31 | }; 32 | 33 | export var doesNotThrow: { 34 | (block: Function, message?: string): void; 35 | (block: Function, error: Function, message?: string): void; 36 | (block: Function, error: RegExp, message?: string): void; 37 | (block: Function, error: (err: any) => boolean, message?: string): void; 38 | }; 39 | 40 | export function ifError(value: any): void; 41 | } 42 | 43 | export = internal; 44 | } -------------------------------------------------------------------------------- /test/mocha.d.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 6 | declare function run(): void; 7 | 8 | declare function suite(name: string, fn: (err?)=>void); 9 | declare function test(name: string, fn: (done?: (err?)=>void)=>void); 10 | declare function suiteSetup(fn: (done?: (err?)=>void)=>void); 11 | declare function suiteTeardown(fn: (done?: (err?)=>void)=>void); 12 | declare function setup(fn: (done?: (err?)=>void)=>void); 13 | declare function teardown(fn: (done?: (err?)=>void)=>void); 14 | -------------------------------------------------------------------------------- /test/mocha.opts: -------------------------------------------------------------------------------- 1 | --delay 2 | --ui tdd 3 | test/all.js -------------------------------------------------------------------------------- /test/tokenization.test.ts: -------------------------------------------------------------------------------- 1 | /*--------------------------------------------------------------------------------------------- 2 | * Copyright (c) Microsoft Corporation. All rights reserved. 3 | * Licensed under the MIT License. See License.txt in the project root for license information. 4 | *--------------------------------------------------------------------------------------------*/ 5 | 'use strict'; 6 | 7 | import * as assert from 'assert'; 8 | import {createTokenizationSupport, Language} from '../src/tokenization'; 9 | 10 | suite('tokenization', () => { 11 | 12 | interface ITestItem { 13 | line: string; 14 | tokens: monaco.languages.IToken[]; 15 | } 16 | 17 | function executeTokenizationTests(tests:ITestItem[][]): void { 18 | let tokenizationSupport = createTokenizationSupport(Language.EcmaScript5); 19 | for (let i = 0, len = tests.length; i < len; i++) { 20 | assert.ok(true, 'TEST #' + i); 21 | executeTokenizationTest(tokenizationSupport, tests[i]); 22 | } 23 | } 24 | 25 | function executeTokenizationTest(tokenizationSupport: monaco.languages.TokensProvider, tests:ITestItem[]): void { 26 | let state = tokenizationSupport.getInitialState(); 27 | for (let i = 0, len = tests.length; i < len; i++) { 28 | assert.ok(true, tests[i].line); 29 | 30 | let result = tokenizationSupport.tokenize(tests[i].line, state); 31 | 32 | if (tests[i].tokens) { 33 | assert.deepEqual(result.tokens, tests[i].tokens, 'Tokenizing line ' + tests[i].line + ': ' + JSON.stringify(tests[i].tokens, null, '\t')); 34 | } 35 | 36 | state = result.endState; 37 | } 38 | } 39 | 40 | test('', () => { 41 | executeTokenizationTests([ 42 | 43 | // Keywords 44 | [{ 45 | line: 'var x = function() { };', 46 | tokens: [ 47 | { startIndex: 0, scopes: 'keyword.js' }, 48 | { startIndex: 3, scopes: '' }, 49 | { startIndex: 4, scopes: 'identifier.js' }, 50 | { startIndex: 5, scopes: '' }, 51 | { startIndex: 6, scopes: 'delimiter.js' }, 52 | { startIndex: 7, scopes: '' }, 53 | { startIndex: 8, scopes: 'keyword.js' }, 54 | { startIndex: 16, scopes: 'delimiter.parenthesis.js' }, 55 | { startIndex: 18, scopes: '' }, 56 | { startIndex: 19, scopes: 'delimiter.bracket.js' }, 57 | { startIndex: 20, scopes: '' }, 58 | { startIndex: 21, scopes: 'delimiter.bracket.js' }, 59 | { startIndex: 22, scopes: 'delimiter.js' } 60 | ]}], 61 | 62 | [{ 63 | line: ' var ', 64 | tokens: [ 65 | { startIndex: 0, scopes: '' }, 66 | { startIndex: 4, scopes: 'keyword.js' }, 67 | { startIndex: 7, scopes: '' } 68 | ]}], 69 | 70 | // Comments - single line 71 | [{ 72 | line: '//', 73 | tokens: [ 74 | { startIndex: 0, scopes: 'comment.js' } 75 | ]}], 76 | 77 | [{ 78 | line: ' // a comment', 79 | tokens: [ 80 | { startIndex: 0, scopes: '' }, 81 | { startIndex: 4, scopes: 'comment.js' } 82 | ]}], 83 | 84 | [{ 85 | line: '// a comment', 86 | tokens: [ 87 | { startIndex: 0, scopes: 'comment.js' } 88 | ]}], 89 | 90 | [{ 91 | line: '// a comment /*', 92 | tokens: [ 93 | { startIndex: 0, scopes: 'comment.js' } 94 | ]}], 95 | 96 | [{ 97 | line: '// a comment /**', 98 | tokens: [ 99 | { startIndex: 0, scopes: 'comment.js' } 100 | ]}], 101 | 102 | [{ 103 | line: '//sticky comment', 104 | tokens: [ 105 | { startIndex: 0, scopes: 'comment.js' } 106 | ]}], 107 | 108 | [{ 109 | line: 'var x = 1; // my comment // is a nice one', 110 | tokens: [ 111 | { startIndex: 0, scopes: 'keyword.js' }, 112 | { startIndex: 3, scopes: '' }, 113 | { startIndex: 4, scopes: 'identifier.js' }, 114 | { startIndex: 5, scopes: '' }, 115 | { startIndex: 6, scopes: 'delimiter.js' }, 116 | { startIndex: 7, scopes: '' }, 117 | { startIndex: 8, scopes: 'number.js' }, 118 | { startIndex: 9, scopes: 'delimiter.js' }, 119 | { startIndex: 10, scopes: '' }, 120 | { startIndex: 11, scopes: 'comment.js' } 121 | ]}], 122 | 123 | // Comments - range comment, single line 124 | [{ 125 | line: '/* a simple comment */', 126 | tokens: [ 127 | { startIndex: 0, scopes: 'comment.js' } 128 | ]}], 129 | 130 | [{ 131 | line: 'var x = /* a simple comment */ 1;', 132 | tokens: [ 133 | { startIndex: 0, scopes: 'keyword.js' }, 134 | { startIndex: 3, scopes: '' }, 135 | { startIndex: 4, scopes: 'identifier.js' }, 136 | { startIndex: 5, scopes: '' }, 137 | { startIndex: 6, scopes: 'delimiter.js' }, 138 | { startIndex: 7, scopes: '' }, 139 | { startIndex: 8, scopes: 'comment.js' }, 140 | { startIndex: 30, scopes: '' }, 141 | { startIndex: 31, scopes: 'number.js' }, 142 | { startIndex: 32, scopes: 'delimiter.js' } 143 | ]}], 144 | 145 | [{ 146 | line: 'x = /**/;', 147 | tokens: [ 148 | { startIndex: 0, scopes: 'identifier.js' }, 149 | { startIndex: 1, scopes: '' }, 150 | { startIndex: 2, scopes: 'delimiter.js' }, 151 | { startIndex: 3, scopes: '' }, 152 | { startIndex: 4, scopes: 'comment.js' }, 153 | { startIndex: 8, scopes: 'delimiter.js' } 154 | ]}], 155 | 156 | [{ 157 | line: 'x = /*/;', 158 | tokens: [ 159 | { startIndex: 0, scopes: 'identifier.js' }, 160 | { startIndex: 1, scopes: '' }, 161 | { startIndex: 2, scopes: 'delimiter.js' }, 162 | { startIndex: 3, scopes: '' }, 163 | { startIndex: 4, scopes: 'comment.js' } 164 | ]}], 165 | 166 | // Comments - range comment, multi lines 167 | [{ 168 | line: '/* a multiline comment', 169 | tokens: [ 170 | { startIndex: 0, scopes: 'comment.js' } 171 | ]}, { 172 | line: 'can actually span', 173 | tokens: [ 174 | { startIndex: 0, scopes: 'comment.js' } 175 | ]}, { 176 | line: 'multiple lines */', 177 | tokens: [ 178 | { startIndex: 0, scopes: 'comment.js' } 179 | ]}], 180 | 181 | [{ 182 | line: 'var x = /* start a comment', 183 | tokens: [ 184 | { startIndex: 0, scopes: 'keyword.js' }, 185 | { startIndex: 3, scopes: '' }, 186 | { startIndex: 4, scopes: 'identifier.js' }, 187 | { startIndex: 5, scopes: '' }, 188 | { startIndex: 6, scopes: 'delimiter.js' }, 189 | { startIndex: 7, scopes: '' }, 190 | { startIndex: 8, scopes: 'comment.js' } 191 | ]}, { 192 | line: ' a ', 193 | tokens: [ 194 | { startIndex: 0, scopes: 'comment.js' } 195 | ]}, { 196 | line: 'and end it */ var a = 2;', 197 | tokens: [ 198 | { startIndex: 0, scopes: 'comment.js' }, 199 | { startIndex: 13, scopes: '' }, 200 | { startIndex: 14, scopes: 'keyword.js' }, 201 | { startIndex: 17, scopes: '' }, 202 | { startIndex: 18, scopes: 'identifier.js' }, 203 | { startIndex: 19, scopes: '' }, 204 | { startIndex: 20, scopes: 'delimiter.js' }, 205 | { startIndex: 21, scopes: '' }, 206 | { startIndex: 22, scopes: 'number.js' }, 207 | { startIndex: 23, scopes: 'delimiter.js' } 208 | ]}], 209 | 210 | // Strings 211 | [{ 212 | line: 'var a = \'a\';', 213 | tokens: [ 214 | { startIndex: 0, scopes: 'keyword.js' }, 215 | { startIndex: 3, scopes: '' }, 216 | { startIndex: 4, scopes: 'identifier.js' }, 217 | { startIndex: 5, scopes: '' }, 218 | { startIndex: 6, scopes: 'delimiter.js' }, 219 | { startIndex: 7, scopes: '' }, 220 | { startIndex: 8, scopes: 'string.js' }, 221 | { startIndex: 11, scopes: 'delimiter.js' } 222 | ]}], 223 | 224 | [{ 225 | line: '"use strict";', 226 | tokens: [ 227 | { startIndex: 0, scopes: 'string.js' }, 228 | { startIndex: 12, scopes: 'delimiter.js' } 229 | ]}], 230 | 231 | [{ 232 | line: 'b = a + " \'cool\' "', 233 | tokens: [ 234 | { startIndex: 0, scopes: 'identifier.js' }, 235 | { startIndex: 1, scopes: '' }, 236 | { startIndex: 2, scopes: 'delimiter.js' }, 237 | { startIndex: 3, scopes: '' }, 238 | { startIndex: 4, scopes: 'identifier.js' }, 239 | { startIndex: 5, scopes: '' }, 240 | { startIndex: 6, scopes: 'delimiter.js' }, 241 | { startIndex: 7, scopes: '' }, 242 | { startIndex: 8, scopes: 'string.js' } 243 | ]}], 244 | 245 | [{ 246 | line: '"escaping \\"quotes\\" is cool"', 247 | tokens: [ 248 | { startIndex: 0, scopes: 'string.js' } 249 | ]}], 250 | 251 | [{ 252 | line: '\'\'\'', 253 | tokens: [ 254 | { startIndex: 0, scopes: 'string.js' } 255 | ]}], 256 | 257 | [{ 258 | line: '\'\\\'\'', 259 | tokens: [ 260 | { startIndex: 0, scopes: 'string.js' } 261 | ]}], 262 | 263 | [{ 264 | line: '\'be careful \\not to escape\'', 265 | tokens: [ 266 | { startIndex: 0, scopes: 'string.js' } 267 | ]}], 268 | 269 | // Numbers 270 | [{ 271 | line: '0', 272 | tokens: [ 273 | { startIndex: 0, scopes: 'number.js' } 274 | ]}], 275 | 276 | [{ 277 | line: ' 0', 278 | tokens: [ 279 | { startIndex: 0, scopes: '' }, 280 | { startIndex: 1, scopes: 'number.js' } 281 | ]}], 282 | 283 | [{ 284 | line: ' 0 ', 285 | tokens: [ 286 | { startIndex: 0, scopes: '' }, 287 | { startIndex: 1, scopes: 'number.js' }, 288 | { startIndex: 2, scopes: '' } 289 | ]}], 290 | 291 | [{ 292 | line: '0 ', 293 | tokens: [ 294 | { startIndex: 0, scopes: 'number.js' }, 295 | { startIndex: 1, scopes: '' } 296 | ]}], 297 | 298 | [{ 299 | line: '0+0', 300 | tokens: [ 301 | { startIndex: 0, scopes: 'number.js' }, 302 | { startIndex: 1, scopes: 'delimiter.js' }, 303 | { startIndex: 2, scopes: 'number.js' } 304 | ]}], 305 | 306 | [{ 307 | line: '100+10', 308 | tokens: [ 309 | { startIndex: 0, scopes: 'number.js' }, 310 | { startIndex: 3, scopes: 'delimiter.js' }, 311 | { startIndex: 4, scopes: 'number.js' } 312 | ]}], 313 | 314 | [{ 315 | line: '0 + 0', 316 | tokens: [ 317 | { startIndex: 0, scopes: 'number.js' }, 318 | { startIndex: 1, scopes: '' }, 319 | { startIndex: 2, scopes: 'delimiter.js' }, 320 | { startIndex: 3, scopes: '' }, 321 | { startIndex: 4, scopes: 'number.js' } 322 | ]}], 323 | 324 | [{ 325 | line: '0123', 326 | tokens: [ 327 | { startIndex: 0, scopes: 'number.js' } 328 | ]}], 329 | 330 | [{ 331 | line: '01239', 332 | tokens: [ 333 | { startIndex: 0, scopes: 'number.js' } 334 | ]}], 335 | 336 | [{ 337 | line: '0x', 338 | tokens: [ 339 | { startIndex: 0, scopes: 'number.js' }, 340 | { startIndex: 1, scopes: 'identifier.js' } 341 | ]}], 342 | 343 | [{ 344 | line: '0x123', 345 | tokens: [ 346 | { startIndex: 0, scopes: 'number.js' } 347 | ]}], 348 | 349 | // Regular Expressions 350 | [{ 351 | line: '//', 352 | tokens: [ 353 | { startIndex: 0, scopes: 'comment.js' } 354 | ]}], 355 | 356 | [{ 357 | line: '/**/', 358 | tokens: [ 359 | { startIndex: 0, scopes: 'comment.js' } 360 | ]}], 361 | 362 | [{ 363 | line: '/***/', 364 | tokens: [ 365 | { startIndex: 0, scopes: 'comment.doc.js' } 366 | ]}], 367 | 368 | [{ 369 | line: '5 / 3;', 370 | tokens: [ 371 | { startIndex: 0, scopes: 'number.js' }, 372 | { startIndex: 1, scopes: '' }, 373 | { startIndex: 2, scopes: 'delimiter.js' }, 374 | { startIndex: 3, scopes: '' }, 375 | { startIndex: 4, scopes: 'number.js' }, 376 | { startIndex: 5, scopes: 'delimiter.js' } 377 | ]}], 378 | 379 | // Advanced regular expressions 380 | [{ 381 | line: '1 / 2; /* comment', 382 | tokens: [ 383 | { startIndex: 0, scopes: 'number.js' }, 384 | { startIndex: 1, scopes: '' }, 385 | { startIndex: 2, scopes: 'delimiter.js' }, 386 | { startIndex: 3, scopes: '' }, 387 | { startIndex: 4, scopes: 'number.js' }, 388 | { startIndex: 5, scopes: 'delimiter.js' }, 389 | { startIndex: 6, scopes: '' }, 390 | { startIndex: 7, scopes: 'comment.js' } 391 | ]}], 392 | 393 | [{ 394 | line: '1 / 2 / x / b;', 395 | tokens: [ 396 | { startIndex: 0, scopes: 'number.js' }, 397 | { startIndex: 1, scopes: '' }, 398 | { startIndex: 2, scopes: 'delimiter.js' }, 399 | { startIndex: 3, scopes: '' }, 400 | { startIndex: 4, scopes: 'number.js' }, 401 | { startIndex: 5, scopes: '' }, 402 | { startIndex: 6, scopes: 'delimiter.js' }, 403 | { startIndex: 7, scopes: '' }, 404 | { startIndex: 8, scopes: 'identifier.js' }, 405 | { startIndex: 9, scopes: '' }, 406 | { startIndex: 10, scopes: 'delimiter.js' }, 407 | { startIndex: 11, scopes: '' }, 408 | { startIndex: 12, scopes: 'identifier.js' }, 409 | { startIndex: 13, scopes: 'delimiter.js' } 410 | ]}], 411 | 412 | [{ 413 | line: 'a /ads/ b;', 414 | tokens: [ 415 | { startIndex: 0, scopes: 'identifier.js' }, 416 | { startIndex: 1, scopes: '' }, 417 | { startIndex: 2, scopes: 'delimiter.js' }, 418 | { startIndex: 3, scopes: 'identifier.js' }, 419 | { startIndex: 6, scopes: 'delimiter.js' }, 420 | { startIndex: 7, scopes: '' }, 421 | { startIndex: 8, scopes: 'identifier.js' }, 422 | { startIndex: 9, scopes: 'delimiter.js' } 423 | ]}], 424 | 425 | [{ 426 | line: '1/(2/3)/2/3;', 427 | tokens: [ 428 | { startIndex: 0, scopes: 'number.js' }, 429 | { startIndex: 1, scopes: 'delimiter.js' }, 430 | { startIndex: 2, scopes: 'delimiter.parenthesis.js' }, 431 | { startIndex: 3, scopes: 'number.js' }, 432 | { startIndex: 4, scopes: 'delimiter.js' }, 433 | { startIndex: 5, scopes: 'number.js' }, 434 | { startIndex: 6, scopes: 'delimiter.parenthesis.js' }, 435 | { startIndex: 7, scopes: 'delimiter.js' }, 436 | { startIndex: 8, scopes: 'number.js' }, 437 | { startIndex: 9, scopes: 'delimiter.js' }, 438 | { startIndex: 10, scopes: 'number.js' }, 439 | { startIndex: 11, scopes: 'delimiter.js' } 440 | ]}], 441 | 442 | [{ 443 | line: '{ key: 123 }', 444 | tokens: [ 445 | { startIndex: 0, scopes: 'delimiter.bracket.js' }, 446 | { startIndex: 1, scopes: '' }, 447 | { startIndex: 2, scopes: 'identifier.js' }, 448 | { startIndex: 5, scopes: 'delimiter.js' }, 449 | { startIndex: 6, scopes: '' }, 450 | { startIndex: 7, scopes: 'number.js' }, 451 | { startIndex: 10, scopes: '' }, 452 | { startIndex: 11, scopes: 'delimiter.bracket.js' } 453 | ]}], 454 | 455 | [{ 456 | line: '[1,2,3]', 457 | tokens: [ 458 | { startIndex: 0, scopes: 'delimiter.array.js' }, 459 | { startIndex: 1, scopes: 'number.js' }, 460 | { startIndex: 2, scopes: 'delimiter.js' }, 461 | { startIndex: 3, scopes: 'number.js' }, 462 | { startIndex: 4, scopes: 'delimiter.js' }, 463 | { startIndex: 5, scopes: 'number.js' }, 464 | { startIndex: 6, scopes: 'delimiter.array.js' } 465 | ]}], 466 | 467 | [{ 468 | line: 'foo(123);', 469 | tokens: [ 470 | { startIndex: 0, scopes: 'identifier.js' }, 471 | { startIndex: 3, scopes: 'delimiter.parenthesis.js' }, 472 | { startIndex: 4, scopes: 'number.js' }, 473 | { startIndex: 7, scopes: 'delimiter.parenthesis.js' }, 474 | { startIndex: 8, scopes: 'delimiter.js' } 475 | ]}], 476 | 477 | [{ 478 | line: '{a:{b:[]}}', 479 | tokens: [ 480 | { startIndex: 0, scopes: 'delimiter.bracket.js' }, 481 | { startIndex: 1, scopes: 'identifier.js' }, 482 | { startIndex: 2, scopes: 'delimiter.js' }, 483 | { startIndex: 3, scopes: 'delimiter.bracket.js' }, 484 | { startIndex: 4, scopes: 'identifier.js' }, 485 | { startIndex: 5, scopes: 'delimiter.js' }, 486 | { startIndex: 6, scopes: 'delimiter.array.js' }, 487 | { startIndex: 8, scopes: 'delimiter.bracket.js' } 488 | ]}], 489 | 490 | [{ 491 | line: 'x = "[{()}]"', 492 | tokens: [ 493 | { startIndex: 0, scopes: 'identifier.js' }, 494 | { startIndex: 1, scopes: '' }, 495 | { startIndex: 2, scopes: 'delimiter.js' }, 496 | { startIndex: 3, scopes: '' }, 497 | { startIndex: 4, scopes: 'string.js' } 498 | ]}] 499 | ]); 500 | }); 501 | 502 | }) 503 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "amd", 4 | "outDir": "out", 5 | "target": "es5" 6 | }, 7 | "filesGlob": [ 8 | "src/*.ts", 9 | "test/*.ts", 10 | "lib/*.d.ts", 11 | "node_modules/monaco-editor-core/monaco.d.ts" 12 | ], 13 | "files": [ 14 | "src/languageFeatures.ts", 15 | "src/mode.ts", 16 | "src/monaco.contribution.ts", 17 | "src/tokenization.ts", 18 | "src/typescript.ts", 19 | "src/worker.ts", 20 | "src/workerManager.ts", 21 | "test/assert.d.ts", 22 | "test/mocha.d.ts", 23 | "test/tokenization.test.ts", 24 | "lib/lib-es6-ts.d.ts", 25 | "lib/lib-ts.d.ts", 26 | "lib/typescriptServices.d.ts", 27 | "node_modules/monaco-editor-core/monaco.d.ts" 28 | ] 29 | } --------------------------------------------------------------------------------