api.js 20.2 KB
Newer Older
J
Joao Moreno 已提交
1 2 3 4 5 6
"use strict";
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
7 8 9 10 11 12 13
const fs = require("fs");
const ts = require("typescript");
const path = require("path");
const util = require("gulp-util");
const tsfmt = require('../../tsfmt.json');
function log(message, ...rest) {
    util.log(util.colors.cyan('[monaco.d.ts]'), message, ...rest);
J
Joao Moreno 已提交
14
}
15 16
const SRC = path.join(__dirname, '../../src');
const OUT_ROOT = path.join(__dirname, '../../');
A
Alex Dima 已提交
17
exports.RECIPE_PATH = path.join(__dirname, './monaco.d.ts.recipe');
18
const DECLARATION_PATH = path.join(__dirname, '../../src/vs/monaco.d.ts');
J
Joao Moreno 已提交
19
var CURRENT_PROCESSING_RULE = '';
20
function logErr(message, ...rest) {
J
Joao Moreno 已提交
21
    util.log(util.colors.red('[monaco.d.ts]'), 'WHILE HANDLING RULE: ', CURRENT_PROCESSING_RULE);
22
    util.log(util.colors.red('[monaco.d.ts]'), message, ...rest);
J
Joao Moreno 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
}
function moduleIdToPath(out, moduleId) {
    if (/\.d\.ts/.test(moduleId)) {
        return path.join(SRC, moduleId);
    }
    return path.join(OUT_ROOT, out, moduleId) + '.d.ts';
}
function isDeclaration(a) {
    return (a.kind === ts.SyntaxKind.InterfaceDeclaration
        || a.kind === ts.SyntaxKind.EnumDeclaration
        || a.kind === ts.SyntaxKind.ClassDeclaration
        || a.kind === ts.SyntaxKind.TypeAliasDeclaration
        || a.kind === ts.SyntaxKind.FunctionDeclaration
        || a.kind === ts.SyntaxKind.ModuleDeclaration);
}
function visitTopLevelDeclarations(sourceFile, visitor) {
39 40
    let stop = false;
    let visit = (node) => {
J
Joao Moreno 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
        if (stop) {
            return;
        }
        switch (node.kind) {
            case ts.SyntaxKind.InterfaceDeclaration:
            case ts.SyntaxKind.EnumDeclaration:
            case ts.SyntaxKind.ClassDeclaration:
            case ts.SyntaxKind.VariableStatement:
            case ts.SyntaxKind.TypeAliasDeclaration:
            case ts.SyntaxKind.FunctionDeclaration:
            case ts.SyntaxKind.ModuleDeclaration:
                stop = visitor(node);
        }
        if (stop) {
            return;
        }
        ts.forEachChild(node, visit);
    };
    visit(sourceFile);
}
function getAllTopLevelDeclarations(sourceFile) {
62 63
    let all = [];
    visitTopLevelDeclarations(sourceFile, (node) => {
J
Joao Moreno 已提交
64
        if (node.kind === ts.SyntaxKind.InterfaceDeclaration || node.kind === ts.SyntaxKind.ClassDeclaration || node.kind === ts.SyntaxKind.ModuleDeclaration) {
65 66 67 68
            let interfaceDeclaration = node;
            let triviaStart = interfaceDeclaration.pos;
            let triviaEnd = interfaceDeclaration.name.pos;
            let triviaText = getNodeText(sourceFile, { pos: triviaStart, end: triviaEnd });
J
Joao Moreno 已提交
69 70 71 72 73
            if (triviaText.indexOf('@internal') === -1) {
                all.push(node);
            }
        }
        else {
74
            let nodeText = getNodeText(sourceFile, node);
J
Joao Moreno 已提交
75 76 77 78 79 80 81 82 83
            if (nodeText.indexOf('@internal') === -1) {
                all.push(node);
            }
        }
        return false /*continue*/;
    });
    return all;
}
function getTopLevelDeclaration(sourceFile, typeName) {
84 85
    let result = null;
    visitTopLevelDeclarations(sourceFile, (node) => {
M
Matt Bierner 已提交
86
        if (isDeclaration(node) && node.name) {
J
Joao Moreno 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
            if (node.name.text === typeName) {
                result = node;
                return true /*stop*/;
            }
            return false /*continue*/;
        }
        // node is ts.VariableStatement
        if (getNodeText(sourceFile, node).indexOf(typeName) >= 0) {
            result = node;
            return true /*stop*/;
        }
        return false /*continue*/;
    });
    return result;
}
function getNodeText(sourceFile, node) {
    return sourceFile.getFullText().substring(node.pos, node.end);
}
105 106
function hasModifier(modifiers, kind) {
    if (modifiers) {
107 108
        for (let i = 0; i < modifiers.length; i++) {
            let mod = modifiers[i];
109 110 111 112 113 114 115 116 117 118 119 120 121 122
            if (mod.kind === kind) {
                return true;
            }
        }
    }
    return false;
}
function isStatic(member) {
    return hasModifier(member.modifiers, ts.SyntaxKind.StaticKeyword);
}
function isDefaultExport(declaration) {
    return (hasModifier(declaration.modifiers, ts.SyntaxKind.DefaultKeyword)
        && hasModifier(declaration.modifiers, ts.SyntaxKind.ExportKeyword));
}
123
function getMassagedTopLevelDeclarationText(sourceFile, declaration, importName, usage, enums) {
124
    let result = getNodeText(sourceFile, declaration);
J
Joao Moreno 已提交
125
    if (declaration.kind === ts.SyntaxKind.InterfaceDeclaration || declaration.kind === ts.SyntaxKind.ClassDeclaration) {
126 127 128 129 130 131
        let interfaceDeclaration = declaration;
        const staticTypeName = (isDefaultExport(interfaceDeclaration)
            ? `${importName}.default`
            : `${importName}.${declaration.name.text}`);
        let instanceTypeName = staticTypeName;
        const typeParametersCnt = (interfaceDeclaration.typeParameters ? interfaceDeclaration.typeParameters.length : 0);
132
        if (typeParametersCnt > 0) {
133 134
            let arr = [];
            for (let i = 0; i < typeParametersCnt; i++) {
135 136
                arr.push('any');
            }
137
            instanceTypeName = `${instanceTypeName}<${arr.join(',')}>`;
138
        }
139 140
        const members = interfaceDeclaration.members;
        members.forEach((member) => {
J
Joao Moreno 已提交
141
            try {
142
                let memberText = getNodeText(sourceFile, member);
J
Joao Moreno 已提交
143 144 145
                if (memberText.indexOf('@internal') >= 0 || memberText.indexOf('private') >= 0) {
                    result = result.replace(memberText, '');
                }
146
                else {
147
                    const memberName = member.name.text;
148
                    if (isStatic(member)) {
149
                        usage.push(`a = ${staticTypeName}.${memberName};`);
150 151
                    }
                    else {
152
                        usage.push(`a = (<${instanceTypeName}>b).${memberName};`);
153 154
                    }
                }
J
Joao Moreno 已提交
155 156 157 158 159 160 161 162
            }
            catch (err) {
                // life..
            }
        });
    }
    result = result.replace(/export default/g, 'export');
    result = result.replace(/export declare/g, 'export');
163 164 165 166
    if (declaration.kind === ts.SyntaxKind.EnumDeclaration) {
        result = result.replace(/const enum/, 'enum');
        enums.push(result);
    }
J
Joao Moreno 已提交
167 168
    return result;
}
A
Alex Dima 已提交
169 170 171 172 173 174
function format(text, endl) {
    const REALLY_FORMAT = false;
    text = preformat(text, endl);
    if (!REALLY_FORMAT) {
        return text;
    }
J
Joao Moreno 已提交
175
    // Parse the source text
176
    let sourceFile = ts.createSourceFile('file.ts', text, ts.ScriptTarget.Latest, /*setParentPointers*/ true);
J
Joao Moreno 已提交
177
    // Get the formatting edits on the input sources
178
    let edits = ts.formatting.formatDocument(sourceFile, getRuleProvider(tsfmt), tsfmt);
J
Joao Moreno 已提交
179 180
    // Apply the edits on the input code
    return applyEdits(text, edits);
A
Alex Dima 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    function countParensCurly(text) {
        let cnt = 0;
        for (let i = 0; i < text.length; i++) {
            if (text.charAt(i) === '(' || text.charAt(i) === '{') {
                cnt++;
            }
            if (text.charAt(i) === ')' || text.charAt(i) === '}') {
                cnt--;
            }
        }
        return cnt;
    }
    function repeatStr(s, cnt) {
        let r = '';
        for (let i = 0; i < cnt; i++) {
            r += s;
        }
        return r;
    }
    function preformat(text, endl) {
        let lines = text.split(endl);
        let inComment = false;
        let inCommentDeltaIndent = 0;
        let indent = 0;
        for (let i = 0; i < lines.length; i++) {
            let line = lines[i].replace(/\s$/, '');
            let repeat = false;
            let lineIndent = 0;
            do {
                repeat = false;
                if (line.substring(0, 4) === '    ') {
                    line = line.substring(4);
                    lineIndent++;
                    repeat = true;
                }
                if (line.charAt(0) === '\t') {
                    line = line.substring(1);
                    lineIndent++;
                    repeat = true;
                }
            } while (repeat);
            if (line.length === 0) {
                continue;
            }
            if (inComment) {
                if (/\*\//.test(line)) {
                    inComment = false;
                }
                lines[i] = repeatStr('\t', lineIndent + inCommentDeltaIndent) + line;
                continue;
            }
            if (/\/\*/.test(line)) {
                inComment = true;
                inCommentDeltaIndent = indent - lineIndent;
                lines[i] = repeatStr('\t', indent) + line;
                continue;
            }
            const cnt = countParensCurly(line);
            let shouldUnindentAfter = false;
            let shouldUnindentBefore = false;
            if (cnt < 0) {
                if (/[({]/.test(line)) {
                    shouldUnindentAfter = true;
                }
                else {
                    shouldUnindentBefore = true;
                }
            }
            else if (cnt === 0) {
                shouldUnindentBefore = /^\}/.test(line);
            }
            let shouldIndentAfter = false;
            if (cnt > 0) {
                shouldIndentAfter = true;
            }
            else if (cnt === 0) {
                shouldIndentAfter = /{$/.test(line);
            }
            if (shouldUnindentBefore) {
                indent--;
            }
            lines[i] = repeatStr('\t', indent) + line;
            if (shouldUnindentAfter) {
                indent--;
            }
            if (shouldIndentAfter) {
                indent++;
            }
        }
        return lines.join(endl);
    }
J
Joao Moreno 已提交
272 273 274
    function getRuleProvider(options) {
        // Share this between multiple formatters using the same options.
        // This represents the bulk of the space the formatter uses.
M
Matt Bierner 已提交
275
        return ts.formatting.getFormatContext(options);
J
Joao Moreno 已提交
276 277 278
    }
    function applyEdits(text, edits) {
        // Apply edits in reverse on the existing text
279 280 281 282 283
        let result = text;
        for (let i = edits.length - 1; i >= 0; i--) {
            let change = edits[i];
            let head = result.slice(0, change.span.start);
            let tail = result.slice(change.span.start + change.span.length);
J
Joao Moreno 已提交
284 285 286 287 288 289 290
            result = head + change.newText + tail;
        }
        return result;
    }
}
function createReplacer(data) {
    data = data || '';
291 292 293
    let rawDirectives = data.split(';');
    let directives = [];
    rawDirectives.forEach((rawDirective) => {
J
Joao Moreno 已提交
294 295 296
        if (rawDirective.length === 0) {
            return;
        }
297 298 299
        let pieces = rawDirective.split('=>');
        let findStr = pieces[0];
        let replaceStr = pieces[1];
J
Joao Moreno 已提交
300 301 302 303
        findStr = findStr.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&');
        findStr = '\\b' + findStr + '\\b';
        directives.push([new RegExp(findStr, 'g'), replaceStr]);
    });
304 305
    return (str) => {
        for (let i = 0; i < directives.length; i++) {
J
Joao Moreno 已提交
306 307 308 309 310
            str = str.replace(directives[i][0], directives[i][1]);
        }
        return str;
    };
}
311
function generateDeclarationFile(recipe, sourceFileGetter) {
312 313 314 315 316 317 318 319 320 321 322
    const endl = /\r\n/.test(recipe) ? '\r\n' : '\n';
    let lines = recipe.split(endl);
    let result = [];
    let usageCounter = 0;
    let usageImports = [];
    let usage = [];
    usage.push(`var a;`);
    usage.push(`var b;`);
    const generateUsageImport = (moduleId) => {
        let importName = 'm' + (++usageCounter);
        usageImports.push(`import * as ${importName} from './${moduleId.replace(/\.d\.ts$/, '')}';`);
323 324
        return importName;
    };
325
    let enums = [];
326 327
    lines.forEach(line => {
        let m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
J
Joao Moreno 已提交
328 329
        if (m1) {
            CURRENT_PROCESSING_RULE = line;
330
            let moduleId = m1[1];
331
            const sourceFile = sourceFileGetter(moduleId);
332
            if (!sourceFile) {
J
Joao Moreno 已提交
333 334
                return;
            }
335 336 337 338
            const importName = generateUsageImport(moduleId);
            let replacer = createReplacer(m1[2]);
            let typeNames = m1[3].split(/,/);
            typeNames.forEach((typeName) => {
J
Joao Moreno 已提交
339 340 341 342
                typeName = typeName.trim();
                if (typeName.length === 0) {
                    return;
                }
343
                let declaration = getTopLevelDeclaration(sourceFile, typeName);
J
Joao Moreno 已提交
344 345 346 347
                if (!declaration) {
                    logErr('Cannot find type ' + typeName);
                    return;
                }
348
                result.push(replacer(getMassagedTopLevelDeclarationText(sourceFile, declaration, importName, usage, enums)));
J
Joao Moreno 已提交
349 350 351
            });
            return;
        }
352
        let m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
J
Joao Moreno 已提交
353 354
        if (m2) {
            CURRENT_PROCESSING_RULE = line;
355
            let moduleId = m2[1];
356
            const sourceFile = sourceFileGetter(moduleId);
357
            if (!sourceFile) {
J
Joao Moreno 已提交
358 359
                return;
            }
360 361 362 363 364 365
            const importName = generateUsageImport(moduleId);
            let replacer = createReplacer(m2[2]);
            let typeNames = m2[3].split(/,/);
            let typesToExcludeMap = {};
            let typesToExcludeArr = [];
            typeNames.forEach((typeName) => {
J
Joao Moreno 已提交
366 367 368 369
                typeName = typeName.trim();
                if (typeName.length === 0) {
                    return;
                }
370 371
                typesToExcludeMap[typeName] = true;
                typesToExcludeArr.push(typeName);
J
Joao Moreno 已提交
372
            });
373
            getAllTopLevelDeclarations(sourceFile).forEach((declaration) => {
M
Matt Bierner 已提交
374
                if (isDeclaration(declaration) && declaration.name) {
375
                    if (typesToExcludeMap[declaration.name.text]) {
J
Joao Moreno 已提交
376 377 378 379 380
                        return;
                    }
                }
                else {
                    // node is ts.VariableStatement
381 382 383
                    let nodeText = getNodeText(sourceFile, declaration);
                    for (let i = 0; i < typesToExcludeArr.length; i++) {
                        if (nodeText.indexOf(typesToExcludeArr[i]) >= 0) {
J
Joao Moreno 已提交
384 385 386 387
                            return;
                        }
                    }
                }
388
                result.push(replacer(getMassagedTopLevelDeclarationText(sourceFile, declaration, importName, usage, enums)));
J
Joao Moreno 已提交
389 390 391 392 393
            });
            return;
        }
        result.push(line);
    });
394
    let resultTxt = result.join(endl);
J
Joao Moreno 已提交
395 396
    resultTxt = resultTxt.replace(/\bURI\b/g, 'Uri');
    resultTxt = resultTxt.replace(/\bEvent</g, 'IEvent<');
A
Alex Dima 已提交
397
    resultTxt = format(resultTxt, endl);
398 399 400 401 402 403 404 405 406 407
    let resultEnums = [
        '/*---------------------------------------------------------------------------------------------',
        ' *  Copyright (c) Microsoft Corporation. All rights reserved.',
        ' *  Licensed under the MIT License. See License.txt in the project root for license information.',
        ' *--------------------------------------------------------------------------------------------*/',
        '',
        '// THIS IS A GENERATED FILE. DO NOT EDIT DIRECTLY.',
        ''
    ].concat(enums).join(endl);
    resultEnums = format(resultEnums, endl);
408 409
    return [
        resultTxt,
410 411
        `${usageImports.join('\n')}\n\n${usage.join('\n')}`,
        resultEnums
412
    ];
J
Joao Moreno 已提交
413
}
414
function getIncludesInRecipe() {
A
Alex Dima 已提交
415
    let recipe = fs.readFileSync(exports.RECIPE_PATH).toString();
416 417 418 419
    let lines = recipe.split(/\r\n|\n|\r/);
    let result = [];
    lines.forEach(line => {
        let m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
J
Joao Moreno 已提交
420
        if (m1) {
421
            let moduleId = m1[1];
422
            result.push(moduleId);
J
Joao Moreno 已提交
423 424
            return;
        }
425
        let m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
J
Joao Moreno 已提交
426
        if (m2) {
427
            let moduleId = m2[1];
428
            result.push(moduleId);
J
Joao Moreno 已提交
429 430 431 432 433
            return;
        }
    });
    return result;
}
A
Alex Dima 已提交
434
exports.getIncludesInRecipe = getIncludesInRecipe;
435
function getFilesToWatch(out) {
436
    return getIncludesInRecipe().map((moduleId) => moduleIdToPath(out, moduleId));
437
}
J
Joao Moreno 已提交
438
exports.getFilesToWatch = getFilesToWatch;
439
function _run(sourceFileGetter) {
J
Joao Moreno 已提交
440
    log('Starting monaco.d.ts generation');
A
Alex Dima 已提交
441
    const recipe = fs.readFileSync(exports.RECIPE_PATH).toString();
442
    const [result, usageContent, enums] = generateDeclarationFile(recipe, sourceFileGetter);
A
Alex Dima 已提交
443
    const currentContent = fs.readFileSync(DECLARATION_PATH).toString();
444 445
    const one = currentContent.replace(/\r\n/gm, '\n');
    const other = result.replace(/\r\n/gm, '\n');
446
    const isTheSame = (one === other);
A
Alex Dima 已提交
447
    log('Finished monaco.d.ts generation');
J
Joao Moreno 已提交
448 449
    return {
        content: result,
450
        usageContent: usageContent,
451
        enums: enums,
J
Joao Moreno 已提交
452
        filePath: DECLARATION_PATH,
453
        isTheSame
J
Joao Moreno 已提交
454 455
    };
}
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
function run(out, inputFiles) {
    let SOURCE_FILE_MAP = {};
    const sourceFileGetter = (moduleId) => {
        if (!SOURCE_FILE_MAP[moduleId]) {
            let filePath = path.normalize(moduleIdToPath(out, moduleId));
            if (!inputFiles.hasOwnProperty(filePath)) {
                logErr('CANNOT FIND FILE ' + filePath + '. YOU MIGHT NEED TO RESTART gulp');
                return null;
            }
            let fileContents = inputFiles[filePath];
            let sourceFile = ts.createSourceFile(filePath, fileContents, ts.ScriptTarget.ES5);
            SOURCE_FILE_MAP[moduleId] = sourceFile;
        }
        return SOURCE_FILE_MAP[moduleId];
    };
    return _run(sourceFileGetter);
}
J
Joao Moreno 已提交
473
exports.run = run;
474 475 476 477 478 479 480 481
function run2(out, sourceFileMap) {
    const sourceFileGetter = (moduleId) => {
        let filePath = path.normalize(moduleIdToPath(out, moduleId));
        return sourceFileMap[filePath];
    };
    return _run(sourceFileGetter);
}
exports.run2 = run2;
J
Joao Moreno 已提交
482 483 484 485
function complainErrors() {
    logErr('Not running monaco.d.ts generation due to compile errors');
}
exports.complainErrors = complainErrors;
486 487
class TypeScriptLanguageServiceHost {
    constructor(libs, files, compilerOptions) {
488 489 490 491 492
        this._libs = libs;
        this._files = files;
        this._compilerOptions = compilerOptions;
    }
    // --- language service host ---------------
493
    getCompilationSettings() {
494
        return this._compilerOptions;
495 496
    }
    getScriptFileNames() {
497 498 499
        return ([]
            .concat(Object.keys(this._libs))
            .concat(Object.keys(this._files)));
500 501
    }
    getScriptVersion(_fileName) {
502
        return '1';
503 504
    }
    getProjectVersion() {
505
        return '1';
506 507
    }
    getScriptSnapshot(fileName) {
508 509 510 511 512 513 514 515 516
        if (this._files.hasOwnProperty(fileName)) {
            return ts.ScriptSnapshot.fromString(this._files[fileName]);
        }
        else if (this._libs.hasOwnProperty(fileName)) {
            return ts.ScriptSnapshot.fromString(this._libs[fileName]);
        }
        else {
            return ts.ScriptSnapshot.fromString('');
        }
517 518
    }
    getScriptKind(_fileName) {
519
        return ts.ScriptKind.TS;
520 521
    }
    getCurrentDirectory() {
522
        return '';
523 524
    }
    getDefaultLibFileName(_options) {
525
        return 'defaultLib:es5';
526 527
    }
    isDefaultLibFileName(fileName) {
528
        return fileName === this.getDefaultLibFileName(this._compilerOptions);
529 530
    }
}
A
Alex Dima 已提交
531
exports.TypeScriptLanguageServiceHost = TypeScriptLanguageServiceHost;
532
function execute() {
533 534 535 536
    const OUTPUT_FILES = {};
    const SRC_FILES = {};
    const SRC_FILE_TO_EXPECTED_NAME = {};
    getIncludesInRecipe().forEach((moduleId) => {
537
        if (/\.d\.ts$/.test(moduleId)) {
538 539
            let fileName = path.join(SRC, moduleId);
            OUTPUT_FILES[moduleIdToPath('src', moduleId)] = fs.readFileSync(fileName).toString();
540 541
            return;
        }
542
        let fileName = path.join(SRC, moduleId) + '.ts';
543 544 545
        SRC_FILES[fileName] = fs.readFileSync(fileName).toString();
        SRC_FILE_TO_EXPECTED_NAME[fileName] = moduleIdToPath('src', moduleId);
    });
546
    const languageService = ts.createLanguageService(new TypeScriptLanguageServiceHost({}, SRC_FILES, {}));
547
    var t1 = Date.now();
548 549
    Object.keys(SRC_FILES).forEach((fileName) => {
        const emitOutput = languageService.getEmitOutput(fileName, true);
550 551
        OUTPUT_FILES[SRC_FILE_TO_EXPECTED_NAME[fileName]] = emitOutput.outputFiles[0].text;
    });
552
    console.log(`Generating .d.ts took ${Date.now() - t1} ms`);
A
Alex Dima 已提交
553
    return run('src', OUTPUT_FILES);
554
}
A
Alex Dima 已提交
555
exports.execute = execute;