Skip to content

Add upper limit for the program size to prevent tsserver from crashing #7486

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Jun 16, 2016
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
4d3cff1
Add upper limit for the program size, fix readDirectory for the symli…
zhengbli Mar 11, 2016
b155fa8
Add comments
zhengbli Mar 12, 2016
a3aa000
CR feedback / Change upper limit / Add disableSizeLimit compiler option
zhengbli Mar 14, 2016
a6a466c
online and offline CR feedback
zhengbli Mar 15, 2016
d4eb3b8
Don't count current opened client file if it's TS file
zhengbli Mar 15, 2016
a839d93
Merge branch 'master' of https://github.com/Microsoft/TypeScript into…
zhengbli Mar 17, 2016
225e3b4
Speed up file searching
zhengbli Mar 17, 2016
c8e0b00
Make language service optional for a project
zhengbli Mar 17, 2016
d7e1d34
Merge branch 'master' of https://github.com/Microsoft/TypeScript into…
zhengbli Mar 18, 2016
cb46f16
Fix failed tests
zhengbli Mar 18, 2016
74e3d7b
Fix project updateing issue after editing config file
zhengbli Mar 18, 2016
1b76294
Merge branch 'master' of https://github.com/Microsoft/TypeScript into…
zhengbli Mar 24, 2016
5c9ce9e
Merge branch 'master' of https://github.com/Microsoft/TypeScript into…
zhengbli Mar 28, 2016
94d44ad
Merge branch 'master' of https://github.com/Microsoft/TypeScript into…
zhengbli Jun 9, 2016
d387050
Fix merging issues and multiple project scenario
zhengbli Jun 9, 2016
4383f1a
Refactoring
zhengbli Jun 9, 2016
e41b10b
add test and spit commandLineParser changes to another PR
zhengbli Jun 10, 2016
3354436
Merge branch 'master' of https://github.com/Microsoft/TypeScript into…
zhengbli Jun 15, 2016
550d912
Refactor code to make if statements cheaper
zhengbli Jun 15, 2016
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 23 additions & 5 deletions src/compiler/commandLineParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,10 @@ namespace ts {
name: "noImplicitUseStrict",
type: "boolean",
description: Diagnostics.Do_not_emit_use_strict_directives_in_module_output
},
{
name: "disableSizeLimit",
type: "boolean"
}
];

Expand Down Expand Up @@ -622,7 +626,7 @@ namespace ts {
}
else {
// by default exclude node_modules, and any specificied output directory
exclude = ["node_modules"];
exclude = ["node_modules", "bower_components"];
const outDir = json["compilerOptions"] && json["compilerOptions"]["outDir"];
if (outDir) {
exclude.push(outDir);
Expand All @@ -633,10 +637,22 @@ namespace ts {
const supportedExtensions = getSupportedExtensions(options);
Debug.assert(indexOf(supportedExtensions, ".ts") < indexOf(supportedExtensions, ".d.ts"), "Changed priority of extensions to pick");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We were re-reading the directory for every file extension in the list? Crazy!! Good find 😄


const potentialFiles: string[] = [];
if (host.readDirectoryWithMultipleExtensions) {
addRange(potentialFiles, host.readDirectoryWithMultipleExtensions(basePath, supportedExtensions, exclude));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe this already handled by @riknoll in #8841. can we make sure we are doing one approach for both PRs.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

possibly split this in a separate PR.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure.

}
else {
for (const extension of supportedExtensions) {
addRange(potentialFiles, host.readDirectory(basePath, extension, exclude));
}
}
// Get files of supported extensions in their order of resolution
for (const extension of supportedExtensions) {
const filesInDirWithExtension = host.readDirectory(basePath, extension, exclude);
for (const fileName of filesInDirWithExtension) {
for (const fileName of potentialFiles) {
if (!fileExtensionIs(fileName, extension)) {
continue;
}

// .ts extension would read the .d.ts extension files too but since .d.ts is lower priority extension,
// lets pick them when its turn comes up
if (extension === ".ts" && fileExtensionIs(fileName, ".d.ts")) {
Expand All @@ -657,8 +673,10 @@ namespace ts {
}
}

filesSeen[fileName] = true;
fileNames.push(fileName);
if (!filesSeen[fileName]) {
filesSeen[fileName] = true;
fileNames.push(fileName);
}
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -2807,5 +2807,9 @@
"Unknown typing option '{0}'.": {
"category": "Error",
"code": 17010
},
"Too many JavaScript files in the project. Consider specifying the 'exclude' setting in project configuration to limit included source folders. The likely folder to exclude is '{0}'. To disable the project size limit, set the 'disableSizeLimit' compiler option to 'true'.": {
"category": "Error",
"code": 17012
}
}
37 changes: 35 additions & 2 deletions src/compiler/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ namespace ts {
/* @internal */ export let emitTime = 0;
/* @internal */ export let ioReadTime = 0;
/* @internal */ export let ioWriteTime = 0;
/* @internal */ export const maxProgramSizeForNonTsFiles = 20 * 1024 * 1024;

/** The version of the TypeScript compiler release */

Expand Down Expand Up @@ -696,6 +697,8 @@ namespace ts {
let diagnosticsProducingTypeChecker: TypeChecker;
let noDiagnosticsTypeChecker: TypeChecker;
let classifiableNames: Map<string>;
let programSizeLimitExceeded = false;
let programSizeForNonTsFiles = 0;

let skipDefaultLib = options.noLib;
const supportedExtensions = getSupportedExtensions(options);
Expand Down Expand Up @@ -742,7 +745,8 @@ namespace ts {
(oldOptions.target !== options.target) ||
(oldOptions.noLib !== options.noLib) ||
(oldOptions.jsx !== options.jsx) ||
(oldOptions.allowJs !== options.allowJs)) {
(oldOptions.allowJs !== options.allowJs) ||
(oldOptions.disableSizeLimit !== options.disableSizeLimit)) {
oldProgram = undefined;
}
}
Expand Down Expand Up @@ -790,6 +794,11 @@ namespace ts {

return program;

function exceedProgramSizeLimit() {
return !options.disableSizeLimit && programSizeLimitExceeded;
}


function getCommonSourceDirectory() {
if (typeof commonSourceDirectory === "undefined") {
if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) {
Expand Down Expand Up @@ -1415,7 +1424,7 @@ namespace ts {
}
}

if (diagnostic) {
if (diagnostic && !exceedProgramSizeLimit()) {
if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) {
fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, diagnostic, ...diagnosticArgument));
}
Expand Down Expand Up @@ -1452,6 +1461,11 @@ namespace ts {
return file;
}

const isNonTsFile = !hasTypeScriptFileExtension(fileName);
if (isNonTsFile && exceedProgramSizeLimit()) {
return undefined;
}

// We haven't looked for this file, do so now and cache result
const file = host.getSourceFile(fileName, options.target, hostErrorMessage => {
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
Expand All @@ -1463,6 +1477,25 @@ namespace ts {
}
});

if (!options.disableSizeLimit && file && file.text && !hasTypeScriptFileExtension(file.fileName)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like we do not need this in the program building, since we are doing it in the server.

programSizeForNonTsFiles += file.text.length;
if (programSizeForNonTsFiles > maxProgramSizeForNonTsFiles) {
// If the program size limit was reached when processing a file, this file is
// likely in the problematic folder than contains too many files.
// Normally the folder is one level down from the commonSourceDirectory, for example,
// if the commonSourceDirectory is "/src/", and the last processed path was "/src/node_modules/a/b.js",
// we should show in the error message "/src/node_modules/".
const commonSourceDirectory = getCommonSourceDirectory();
let rootLevelDirectory = path.substring(0, Math.max(commonSourceDirectory.length, path.indexOf(directorySeparator, commonSourceDirectory.length)));
if (rootLevelDirectory[rootLevelDirectory.length - 1] !== directorySeparator) {
rootLevelDirectory += directorySeparator;
}
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Too_many_JavaScript_files_in_the_project_Consider_specifying_the_exclude_setting_in_project_configuration_to_limit_included_source_folders_The_likely_folder_to_exclude_is_0_To_disable_the_project_size_limit_set_the_disableSizeLimit_compiler_option_to_true, rootLevelDirectory));
programSizeLimitExceeded = true;
return undefined;
}
}

filesByName.set(path, file);
if (file) {
file.wasReferenced = file.wasReferenced || isReference;
Expand Down
76 changes: 57 additions & 19 deletions src/compiler/sys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ namespace ts {
useCaseSensitiveFileNames: boolean;
write(s: string): void;
readFile(path: string, encoding?: string): string;
getFileSize?(path: string): number;
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(path: Path, callback: FileWatcherCallback): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
Expand All @@ -20,6 +21,7 @@ namespace ts {
getExecutingFilePath(): string;
getCurrentDirectory(): string;
readDirectory(path: string, extension?: string, exclude?: string[]): string[];
readDirectoryWithMultipleExtensions?(path: string, extensions: string[], exclude?: string[]): string[];
getMemoryUsage?(): number;
exit(exitCode?: number): void;
}
Expand Down Expand Up @@ -74,7 +76,7 @@ namespace ts {
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
};

export var sys: System = (function () {
export var sys: System = (function() {

function getWScriptSystem(): System {

Expand Down Expand Up @@ -404,8 +406,8 @@ namespace ts {
const watchedFileSet = createWatchedFileSet();

function isNode4OrLater(): boolean {
return parseInt(process.version.charAt(1)) >= 4;
}
return parseInt(process.version.charAt(1)) >= 4;
}

const platform: string = _os.platform();
// win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive
Expand Down Expand Up @@ -489,34 +491,59 @@ namespace ts {
return fileSystemEntryExists(path, FileSystemEntryKind.Directory);
}

function readDirectory(path: string, extension?: string, exclude?: string[]): string[] {
const result: string[] = [];
exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s)));
visitDirectory(path);
return result;
function visitDirectory(path: string) {
const files = _fs.readdirSync(path || ".").sort();
const directories: string[] = [];
for (const current of files) {
const name = combinePaths(path, current);
if (!contains(exclude, getCanonicalPath(name))) {
function visitDirectory(path: string, result: string[], extension: string | string[], exclude: string[]) {
const files = _fs.readdirSync(path || ".").sort();
const directories: string[] = [];
for (const current of files) {
const name = combinePaths(path, current);
if (!contains(exclude, getCanonicalPath(name))) {
// fs.statSync would throw an exception if the file is a symlink
// whose linked file doesn't exist.
try {
const stat = _fs.statSync(name);
if (stat.isFile()) {
if (!extension || fileExtensionIs(name, extension)) {
if (checkExtension(name)) {
result.push(name);
}
}
else if (stat.isDirectory()) {
directories.push(name);
}
}
catch (e) { }
}
}
for (const current of directories) {
visitDirectory(current, result, extension, exclude);
}

function checkExtension(name: string) {
if (!extension) {
return true;
}
for (const current of directories) {
visitDirectory(current);
if (typeof extension === "string") {
return fileExtensionIs(name, extension);
}
else {
return forEach(extension, ext => fileExtensionIs(name, ext));
}
}
}

function readDirectoryWithMultipleExtensions(path: string, extensions: string[], exclude?: string[]): string[] {
const result: string[] = [];
exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s)));
visitDirectory(path, result, extensions, exclude);
return result;
}

function readDirectory(path: string, extension?: string, exclude?: string[]): string[] {
const result: string[] = [];
exclude = map(exclude, s => getCanonicalPath(combinePaths(path, s)));
visitDirectory(path, result, extension, exclude);
return result;
}

return {
args: process.argv.slice(2),
newLine: _os.EOL,
Expand All @@ -532,7 +559,7 @@ namespace ts {
// and https://github.com/Microsoft/TypeScript/issues/4643), therefore
// if the current node.js version is newer than 4, use `fs.watch` instead.
const watchSet = isNode4OrLater() ? watchedFileSet : pollingWatchedFileSet;
const watchedFile = watchSet.addFile(filePath, callback);
const watchedFile = watchSet.addFile(filePath, callback);
return {
close: () => watchSet.removeFile(watchedFile)
};
Expand Down Expand Up @@ -562,7 +589,7 @@ namespace ts {
}
);
},
resolvePath: function (path: string): string {
resolvePath: function(path: string): string {
return _path.resolve(path);
},
fileExists,
Expand All @@ -579,12 +606,23 @@ namespace ts {
return process.cwd();
},
readDirectory,
readDirectoryWithMultipleExtensions,
getMemoryUsage() {
if (global.gc) {
global.gc();
}
return process.memoryUsage().heapUsed;
},
getFileSize(path) {
try {
const stat = _fs.statSync(path);
if (stat.isFile()) {
return stat.size;
}
}
catch (e) { }
return 0;
},
exit(exitCode?: number): void {
process.exit(exitCode);
}
Expand Down
2 changes: 2 additions & 0 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1581,6 +1581,7 @@ namespace ts {

export interface ParseConfigHost {
readDirectory(rootDir: string, extension: string, exclude: string[]): string[];
readDirectoryWithMultipleExtensions?(rootDir: string, extensions: string[], exclude: string[]): string[];
}

export interface WriteFileCallback {
Expand Down Expand Up @@ -2439,6 +2440,7 @@ namespace ts {
allowSyntheticDefaultImports?: boolean;
allowJs?: boolean;
noImplicitUseStrict?: boolean;
disableSizeLimit?: boolean;
lib?: string[];
/* @internal */ stripInternal?: boolean;

Expand Down
4 changes: 4 additions & 0 deletions src/compiler/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2484,6 +2484,10 @@ namespace ts {
return forEach(supportedJavascriptExtensions, extension => fileExtensionIs(fileName, extension));
}

export function hasTypeScriptFileExtension(fileName: string) {
return forEach(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension));
}

/**
* Replace each instance of non-ascii characters by one, two, three, or four escape sequences
* representing the UTF-8 encoding of the character, and return the expanded char code list.
Expand Down
Loading