api.js 19.4 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 123
            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));
}
function getMassagedTopLevelDeclarationText(sourceFile, declaration, importName, usage) {
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 163 164
            }
            catch (err) {
                // life..
            }
        });
    }
    result = result.replace(/export default/g, 'export');
    result = result.replace(/export declare/g, 'export');
    return result;
}
A
Alex Dima 已提交
165 166 167 168 169 170
function format(text, endl) {
    const REALLY_FORMAT = false;
    text = preformat(text, endl);
    if (!REALLY_FORMAT) {
        return text;
    }
J
Joao Moreno 已提交
171
    // Parse the source text
172
    let sourceFile = ts.createSourceFile('file.ts', text, ts.ScriptTarget.Latest, /*setParentPointers*/ true);
J
Joao Moreno 已提交
173
    // Get the formatting edits on the input sources
174
    let edits = ts.formatting.formatDocument(sourceFile, getRuleProvider(tsfmt), tsfmt);
J
Joao Moreno 已提交
175 176
    // Apply the edits on the input code
    return applyEdits(text, edits);
A
Alex Dima 已提交
177 178 179 180 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
    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 已提交
268 269 270
    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 已提交
271
        return ts.formatting.getFormatContext(options);
J
Joao Moreno 已提交
272 273 274
    }
    function applyEdits(text, edits) {
        // Apply edits in reverse on the existing text
275 276 277 278 279
        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 已提交
280 281 282 283 284 285 286
            result = head + change.newText + tail;
        }
        return result;
    }
}
function createReplacer(data) {
    data = data || '';
287 288 289
    let rawDirectives = data.split(';');
    let directives = [];
    rawDirectives.forEach((rawDirective) => {
J
Joao Moreno 已提交
290 291 292
        if (rawDirective.length === 0) {
            return;
        }
293 294 295
        let pieces = rawDirective.split('=>');
        let findStr = pieces[0];
        let replaceStr = pieces[1];
J
Joao Moreno 已提交
296 297 298 299
        findStr = findStr.replace(/[\-\\\{\}\*\+\?\|\^\$\.\,\[\]\(\)\#\s]/g, '\\$&');
        findStr = '\\b' + findStr + '\\b';
        directives.push([new RegExp(findStr, 'g'), replaceStr]);
    });
300 301
    return (str) => {
        for (let i = 0; i < directives.length; i++) {
J
Joao Moreno 已提交
302 303 304 305 306
            str = str.replace(directives[i][0], directives[i][1]);
        }
        return str;
    };
}
307
function generateDeclarationFile(recipe, sourceFileGetter) {
308 309 310 311 312 313 314 315 316 317 318
    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$/, '')}';`);
319 320
        return importName;
    };
321 322
    lines.forEach(line => {
        let m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
J
Joao Moreno 已提交
323 324
        if (m1) {
            CURRENT_PROCESSING_RULE = line;
325
            let moduleId = m1[1];
326
            const sourceFile = sourceFileGetter(moduleId);
327
            if (!sourceFile) {
J
Joao Moreno 已提交
328 329
                return;
            }
330 331 332 333
            const importName = generateUsageImport(moduleId);
            let replacer = createReplacer(m1[2]);
            let typeNames = m1[3].split(/,/);
            typeNames.forEach((typeName) => {
J
Joao Moreno 已提交
334 335 336 337
                typeName = typeName.trim();
                if (typeName.length === 0) {
                    return;
                }
338
                let declaration = getTopLevelDeclaration(sourceFile, typeName);
J
Joao Moreno 已提交
339 340 341 342
                if (!declaration) {
                    logErr('Cannot find type ' + typeName);
                    return;
                }
343
                result.push(replacer(getMassagedTopLevelDeclarationText(sourceFile, declaration, importName, usage)));
J
Joao Moreno 已提交
344 345 346
            });
            return;
        }
347
        let m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
J
Joao Moreno 已提交
348 349
        if (m2) {
            CURRENT_PROCESSING_RULE = line;
350
            let moduleId = m2[1];
351
            const sourceFile = sourceFileGetter(moduleId);
352
            if (!sourceFile) {
J
Joao Moreno 已提交
353 354
                return;
            }
355 356 357 358 359 360
            const importName = generateUsageImport(moduleId);
            let replacer = createReplacer(m2[2]);
            let typeNames = m2[3].split(/,/);
            let typesToExcludeMap = {};
            let typesToExcludeArr = [];
            typeNames.forEach((typeName) => {
J
Joao Moreno 已提交
361 362 363 364
                typeName = typeName.trim();
                if (typeName.length === 0) {
                    return;
                }
365 366
                typesToExcludeMap[typeName] = true;
                typesToExcludeArr.push(typeName);
J
Joao Moreno 已提交
367
            });
368
            getAllTopLevelDeclarations(sourceFile).forEach((declaration) => {
M
Matt Bierner 已提交
369
                if (isDeclaration(declaration) && declaration.name) {
370
                    if (typesToExcludeMap[declaration.name.text]) {
J
Joao Moreno 已提交
371 372 373 374 375
                        return;
                    }
                }
                else {
                    // node is ts.VariableStatement
376 377 378
                    let nodeText = getNodeText(sourceFile, declaration);
                    for (let i = 0; i < typesToExcludeArr.length; i++) {
                        if (nodeText.indexOf(typesToExcludeArr[i]) >= 0) {
J
Joao Moreno 已提交
379 380 381 382
                            return;
                        }
                    }
                }
383
                result.push(replacer(getMassagedTopLevelDeclarationText(sourceFile, declaration, importName, usage)));
J
Joao Moreno 已提交
384 385 386 387 388
            });
            return;
        }
        result.push(line);
    });
389
    let resultTxt = result.join(endl);
J
Joao Moreno 已提交
390 391
    resultTxt = resultTxt.replace(/\bURI\b/g, 'Uri');
    resultTxt = resultTxt.replace(/\bEvent</g, 'IEvent<');
A
Alex Dima 已提交
392
    resultTxt = format(resultTxt, endl);
393 394
    return [
        resultTxt,
395
        `${usageImports.join('\n')}\n\n${usage.join('\n')}`
396
    ];
J
Joao Moreno 已提交
397
}
398
function getIncludesInRecipe() {
A
Alex Dima 已提交
399
    let recipe = fs.readFileSync(exports.RECIPE_PATH).toString();
400 401 402 403
    let lines = recipe.split(/\r\n|\n|\r/);
    let result = [];
    lines.forEach(line => {
        let m1 = line.match(/^\s*#include\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
J
Joao Moreno 已提交
404
        if (m1) {
405
            let moduleId = m1[1];
406
            result.push(moduleId);
J
Joao Moreno 已提交
407 408
            return;
        }
409
        let m2 = line.match(/^\s*#includeAll\(([^;)]*)(;[^)]*)?\)\:(.*)$/);
J
Joao Moreno 已提交
410
        if (m2) {
411
            let moduleId = m2[1];
412
            result.push(moduleId);
J
Joao Moreno 已提交
413 414 415 416 417
            return;
        }
    });
    return result;
}
A
Alex Dima 已提交
418
exports.getIncludesInRecipe = getIncludesInRecipe;
419
function getFilesToWatch(out) {
420
    return getIncludesInRecipe().map((moduleId) => moduleIdToPath(out, moduleId));
421
}
J
Joao Moreno 已提交
422
exports.getFilesToWatch = getFilesToWatch;
423
function _run(sourceFileGetter) {
J
Joao Moreno 已提交
424
    log('Starting monaco.d.ts generation');
A
Alex Dima 已提交
425 426 427
    const recipe = fs.readFileSync(exports.RECIPE_PATH).toString();
    const [result, usageContent] = generateDeclarationFile(recipe, sourceFileGetter);
    const currentContent = fs.readFileSync(DECLARATION_PATH).toString();
428 429
    const one = currentContent.replace(/\r\n/gm, '\n');
    const other = result.replace(/\r\n/gm, '\n');
430
    const isTheSame = (one === other);
A
Alex Dima 已提交
431
    log('Finished monaco.d.ts generation');
J
Joao Moreno 已提交
432 433
    return {
        content: result,
434
        usageContent: usageContent,
J
Joao Moreno 已提交
435
        filePath: DECLARATION_PATH,
436
        isTheSame
J
Joao Moreno 已提交
437 438
    };
}
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
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 已提交
456
exports.run = run;
457 458 459 460 461 462 463 464
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 已提交
465 466 467 468
function complainErrors() {
    logErr('Not running monaco.d.ts generation due to compile errors');
}
exports.complainErrors = complainErrors;
469 470
class TypeScriptLanguageServiceHost {
    constructor(libs, files, compilerOptions) {
471 472 473 474 475
        this._libs = libs;
        this._files = files;
        this._compilerOptions = compilerOptions;
    }
    // --- language service host ---------------
476
    getCompilationSettings() {
477
        return this._compilerOptions;
478 479
    }
    getScriptFileNames() {
480 481 482
        return ([]
            .concat(Object.keys(this._libs))
            .concat(Object.keys(this._files)));
483 484
    }
    getScriptVersion(_fileName) {
485
        return '1';
486 487
    }
    getProjectVersion() {
488
        return '1';
489 490
    }
    getScriptSnapshot(fileName) {
491 492 493 494 495 496 497 498 499
        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('');
        }
500 501
    }
    getScriptKind(_fileName) {
502
        return ts.ScriptKind.TS;
503 504
    }
    getCurrentDirectory() {
505
        return '';
506 507
    }
    getDefaultLibFileName(_options) {
508
        return 'defaultLib:es5';
509 510
    }
    isDefaultLibFileName(fileName) {
511
        return fileName === this.getDefaultLibFileName(this._compilerOptions);
512 513
    }
}
A
Alex Dima 已提交
514
exports.TypeScriptLanguageServiceHost = TypeScriptLanguageServiceHost;
515
function execute() {
516 517 518 519
    const OUTPUT_FILES = {};
    const SRC_FILES = {};
    const SRC_FILE_TO_EXPECTED_NAME = {};
    getIncludesInRecipe().forEach((moduleId) => {
520
        if (/\.d\.ts$/.test(moduleId)) {
521 522
            let fileName = path.join(SRC, moduleId);
            OUTPUT_FILES[moduleIdToPath('src', moduleId)] = fs.readFileSync(fileName).toString();
523 524
            return;
        }
525
        let fileName = path.join(SRC, moduleId) + '.ts';
526 527 528
        SRC_FILES[fileName] = fs.readFileSync(fileName).toString();
        SRC_FILE_TO_EXPECTED_NAME[fileName] = moduleIdToPath('src', moduleId);
    });
529
    const languageService = ts.createLanguageService(new TypeScriptLanguageServiceHost({}, SRC_FILES, {}));
530
    var t1 = Date.now();
531 532
    Object.keys(SRC_FILES).forEach((fileName) => {
        const emitOutput = languageService.getEmitOutput(fileName, true);
533 534
        OUTPUT_FILES[SRC_FILE_TO_EXPECTED_NAME[fileName]] = emitOutput.outputFiles[0].text;
    });
535
    console.log(`Generating .d.ts took ${Date.now() - t1} ms`);
A
Alex Dima 已提交
536
    return run('src', OUTPUT_FILES);
537
}
A
Alex Dima 已提交
538
exports.execute = execute;