Skip to content
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

Don't allow .ts to appear in an import #9646

Merged
10 commits merged into from
Aug 19, 2016
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
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
9 changes: 8 additions & 1 deletion src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1369,7 +1369,14 @@ namespace ts {

if (moduleNotFoundError) {
// report errors only if it was requested
error(moduleReferenceLiteral, moduleNotFoundError, moduleName);
const tsExtension = tryExtractTypeScriptExtension(moduleName);
if (tsExtension) {
const diag = Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
error(moduleReferenceLiteral, diag, tsExtension, removeExtension(moduleName, tsExtension));
}
else {
error(moduleReferenceLiteral, moduleNotFoundError, moduleName);
}
}
return undefined;
}
Expand Down
19 changes: 17 additions & 2 deletions src/compiler/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,17 @@ namespace ts {
return undefined;
}

/** Works like Array.prototype.find, returning `undefined` if no element satisfying the predicate is found. */
export function tryFind<T>(array: T[], predicate: (element: T, index: number) => boolean): T | undefined {
Copy link
Member

Choose a reason for hiding this comment

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

Hmm, I expected find to have the type that tryFind has right now. Why does find take callback and not predicate?
I forgot to mention it when I ran into it last week while trying to use find.

Copy link
Author

Choose a reason for hiding this comment

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

If we rename tryFind to find, what should we call find? mustFind?

Copy link
Member

Choose a reason for hiding this comment

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

findMap? Let me go see if this function is in hoogle...

Copy link
Member

Choose a reason for hiding this comment

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

It's the equivalent of bind (>>=) or something like Data.Foldable.concatMap except that it takes Array<T> to Exception<T>. So, yeah, findMap is not bad, or mapFirst or mapSingle.

for (let i = 0, len = array.length; i < len; i++) {
const value = array[i];
if (predicate(value, i)) {
return value;
}
}
return undefined;
}

/** Like `forEach`, but assumes existence of array and fails if no truthy value is found. */
export function find<T, U>(array: T[], callback: (element: T, index: number) => U | undefined): U {
for (let i = 0, len = array.length; i < len; i++) {
Expand Down Expand Up @@ -1311,8 +1322,12 @@ namespace ts {
return path;
}

export function tryRemoveExtension(path: string, extension: string): string {
return fileExtensionIs(path, extension) ? path.substring(0, path.length - extension.length) : undefined;
export function tryRemoveExtension(path: string, extension: string): string | undefined {
return fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
}

export function removeExtension(path: string, extension: string): string {
return path.substring(0, path.length - extension.length);
}

export function isJsxOrTsxExtension(ext: string): boolean {
Expand Down
4 changes: 4 additions & 0 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -1951,6 +1951,10 @@
"category": "Error",
"code": 2690
},
"An import path cannot end with a '{0}' extension. Consider importing '{1}' instead.": {
"category": "Error",
"code": 2691
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
Expand Down
55 changes: 29 additions & 26 deletions src/compiler/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -661,51 +661,52 @@ namespace ts {
* @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary
* in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations.
*/
function loadModuleFromFile(candidate: string, extensions: string[], failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string {
// First try to keep/add an extension: importing "./foo.ts" can be matched by a file "./foo.ts", and "./foo" by "./foo.d.ts"
const resolvedByAddingOrKeepingExtension = loadModuleFromFileWorker(candidate, extensions, failedLookupLocation, onlyRecordFailures, state);
if (resolvedByAddingOrKeepingExtension) {
return resolvedByAddingOrKeepingExtension;
function loadModuleFromFile(candidate: string, extensions: string[], failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined {
// First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
Copy link
Member

Choose a reason for hiding this comment

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

do we know that candidate is extensionless already? tryAddingExtensions looks like it blindly adds ext to the end of candidate

Copy link
Author

Choose a reason for hiding this comment

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

That's right, so if someone imports "foo.bar" they can get "foo.bar.ts".

const resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state);
if (resolvedByAddingExtension) {
return resolvedByAddingExtension;
}
// Then try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one, e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"

// If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
// e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
if (hasJavaScriptFileExtension(candidate)) {
const extensionless = removeFileExtension(candidate);
if (state.traceEnabled) {
const extension = candidate.substring(extensionless.length);
trace(state.host, Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
}
return loadModuleFromFileWorker(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state);
return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state);
}
}

function loadModuleFromFileWorker(candidate: string, extensions: string[], failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string {
/** Try to return an existing file that adds one of the `extensions` to `candidate`. */
function tryAddingExtensions(candidate: string, extensions: string[], failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined {
if (!onlyRecordFailures) {
// check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
const directory = getDirectoryPath(candidate);
if (directory) {
onlyRecordFailures = !directoryProbablyExists(directory, state.host);
}
}
return forEach(extensions, tryLoad);
return forEach(extensions, ext =>
!(state.skipTsx && isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state));
}

function tryLoad(ext: string): string {
if (state.skipTsx && isJsxOrTsxExtension(ext)) {
return undefined;
}
const fileName = fileExtensionIs(candidate, ext) ? candidate : candidate + ext;
if (!onlyRecordFailures && state.host.fileExists(fileName)) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
}
return fileName;
/** Return the file if it exists. */
function tryFile(fileName: string, failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string | undefined {
if (!onlyRecordFailures && state.host.fileExists(fileName)) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_does_not_exist, fileName);
}
failedLookupLocation.push(fileName);
return undefined;
return fileName;
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_does_not_exist, fileName);
}
failedLookupLocation.push(fileName);
return undefined;
}
}

Expand All @@ -718,7 +719,9 @@ namespace ts {
}
const typesFile = tryReadTypesSection(packageJsonPath, candidate, state);
if (typesFile) {
const result = loadModuleFromFile(typesFile, extensions, failedLookupLocation, !directoryProbablyExists(getDirectoryPath(typesFile), state.host), state);
const onlyRecordFailures = !directoryProbablyExists(getDirectoryPath(typesFile), state.host);
// The package.json "typings" property must specify the file with extension, so just try that exact filename.
const result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures, state);
if (result) {
return result;
}
Expand Down
7 changes: 7 additions & 0 deletions src/compiler/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2713,6 +2713,13 @@ namespace ts {
return forEach(supportedTypeScriptExtensions, extension => fileExtensionIs(fileName, extension));
}

/** Return ".ts" or ".tsx" if that is the extension. */
Copy link
Member

Choose a reason for hiding this comment

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

".d.ts"?

export function tryExtractTypeScriptExtension(fileName: string): string | undefined {
return tryFind(supportedTypescriptExtensionsWithDtsFirst, extension => fileExtensionIs(fileName, extension));
}
// Must have '.d.ts' first because if '.ts' goes first, that will be detected as the extension instead of '.d.ts'.
const supportedTypescriptExtensionsWithDtsFirst = supportedTypeScriptExtensions.slice().reverse();
Copy link
Member

Choose a reason for hiding this comment

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

why not just change supportedTypeScriptExtensions ?

Copy link
Author

Choose a reason for hiding this comment

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

supportedTypeScriptExtensions is in order of file resolution precedence, meaning we want .d.ts to be tried last.

Copy link
Member

Choose a reason for hiding this comment

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

Seems like something you probably want to make explicit in case anyone relies on that behavior.

Copy link
Author

Choose a reason for hiding this comment

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

supportedTypescriptExtensions currently has a comment on it saying that it's in file resolution precedence. What else could we add?
I might want to change this code to just duplicate the list, though, because if anyone ever changes the order of supportedTypescriptExtensions, this one will no longer have .d.ts first.

Copy link
Member

Choose a reason for hiding this comment

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

The fact that the list is in resolution order is independent of the fact that you're trying to give the longer extension a higher priority. Does that make sense?


/**
* 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
8 changes: 4 additions & 4 deletions src/harness/unittests/moduleResolution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -450,8 +450,8 @@ export = C;
"/a/B/c/moduleB.ts": `import a = require("./moduleC")`,
"/a/B/c/moduleC.ts": "export var x",
"/a/B/c/moduleD.ts": `
import a = require("./moduleA.ts");
import b = require("./moduleB.ts");
import a = require("./moduleA");
import b = require("./moduleB");
`
};
test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", /*useCaseSensitiveFileNames*/ false, ["moduleD.ts"], [1149]);
Expand All @@ -462,8 +462,8 @@ import b = require("./moduleB.ts");
"/a/B/c/moduleB.ts": `import a = require("./moduleC")`,
"/a/B/c/moduleC.ts": "export var x",
"/a/B/c/moduleD.ts": `
import a = require("./moduleA.ts");
import b = require("./moduleB.ts");
import a = require("./moduleA");
import b = require("./moduleB");
`
};
test(files, { module: ts.ModuleKind.CommonJS, forceConsistentCasingInFileNames: true }, "/a/B/c", /*useCaseSensitiveFileNames*/ false, ["moduleD.ts"], []);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ tests/cases/compiler/missingFunctionImplementation2_b.ts(1,17): error TS2391: Fu

==== tests/cases/compiler/missingFunctionImplementation2_a.ts (1 errors) ====
export {};
declare module "./missingFunctionImplementation2_b.ts" {
declare module "./missingFunctionImplementation2_b" {
export function f(a, b): void;
~
!!! error TS2384: Overload signatures must all be ambient or non-ambient.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

//// [missingFunctionImplementation2_a.ts]
export {};
declare module "./missingFunctionImplementation2_b.ts" {
declare module "./missingFunctionImplementation2_b" {
export function f(a, b): void;
}

Expand Down
31 changes: 31 additions & 0 deletions tests/baselines/reference/moduleResolutionNoTs.errors.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
tests/cases/compiler/user.ts(1,15): error TS2691: An import path cannot end with a '.ts' extension. Consider importing './x' instead.
tests/cases/compiler/user.ts(2,15): error TS2691: An import path cannot end with a '.tsx' extension. Consider importing './y' instead.
tests/cases/compiler/user.ts(3,15): error TS2691: An import path cannot end with a '.d.ts' extension. Consider importing './z' instead.


==== tests/cases/compiler/x.ts (0 errors) ====
export default 0;

==== tests/cases/compiler/y.tsx (0 errors) ====
export default 0;

==== tests/cases/compiler/z.d.ts (0 errors) ====
declare const x: number;
export default x;

==== tests/cases/compiler/user.ts (3 errors) ====
import x from "./x.ts";
~~~~~~~~
!!! error TS2691: An import path cannot end with a '.ts' extension. Consider importing './x' instead.
import y from "./y.tsx";
~~~~~~~~~
!!! error TS2691: An import path cannot end with a '.tsx' extension. Consider importing './y' instead.
import z from "./z.d.ts";
~~~~~~~~~~
!!! error TS2691: An import path cannot end with a '.d.ts' extension. Consider importing './z' instead.

// Making sure the suggested fixes are valid:
import x2 from "./x";
import y2 from "./y";
import z2 from "./z";

33 changes: 33 additions & 0 deletions tests/baselines/reference/moduleResolutionNoTs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
//// [tests/cases/compiler/moduleResolutionNoTs.ts] ////

//// [x.ts]
export default 0;

//// [y.tsx]
export default 0;

//// [z.d.ts]
declare const x: number;
export default x;

//// [user.ts]
import x from "./x.ts";
import y from "./y.tsx";
import z from "./z.d.ts";

// Making sure the suggested fixes are valid:
import x2 from "./x";
import y2 from "./y";
import z2 from "./z";


//// [x.js]
"use strict";
exports.__esModule = true;
exports["default"] = 0;
//// [y.js]
"use strict";
exports.__esModule = true;
exports["default"] = 0;
//// [user.js]
"use strict";
7 changes: 0 additions & 7 deletions tests/baselines/reference/moduleResolutionWithExtensions.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@ export default 0;
//// [b.ts]
import a from './a';

// Matching extension
//// [c.ts]
import a from './a.ts';

// '.js' extension: stripped and replaced with '.ts'
//// [d.ts]
import a from './a.js';
Expand All @@ -36,9 +32,6 @@ exports["default"] = 0;
// No extension: '.ts' added
//// [b.js]
"use strict";
// Matching extension
//// [c.js]
"use strict";
// '.js' extension: stripped and replaced with '.ts'
//// [d.js]
"use strict";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,6 @@ No type information for this code.=== /src/b.ts ===
import a from './a';
>a : Symbol(a, Decl(b.ts, 0, 6))

// Matching extension
=== /src/c.ts ===
import a from './a.ts';
>a : Symbol(a, Decl(c.ts, 0, 6))

// '.js' extension: stripped and replaced with '.ts'
=== /src/d.ts ===
import a from './a.js';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,6 @@
"File '/src/a.ts' exist - use it as a name resolution result.",
"Resolving real path for '/src/a.ts', result '/src/a.ts'",
"======== Module name './a' was successfully resolved to '/src/a.ts'. ========",
"======== Resolving module './a.ts' from '/src/c.ts'. ========",
"Module resolution kind is not specified, using 'NodeJs'.",
"Loading module as file / folder, candidate module location '/src/a.ts'.",
"File '/src/a.ts' exist - use it as a name resolution result.",
"Resolving real path for '/src/a.ts', result '/src/a.ts'",
"======== Module name './a.ts' was successfully resolved to '/src/a.ts'. ========",
"======== Resolving module './a.js' from '/src/d.ts'. ========",
"Module resolution kind is not specified, using 'NodeJs'.",
"Loading module as file / folder, candidate module location '/src/a.js'.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,6 @@ No type information for this code.=== /src/b.ts ===
import a from './a';
>a : number

// Matching extension
=== /src/c.ts ===
import a from './a.ts';
>a : number

// '.js' extension: stripped and replaced with '.ts'
=== /src/d.ts ===
import a from './a.js';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ tests/cases/compiler/staticInstanceResolution5_1.ts(6,16): error TS2304: Cannot


==== tests/cases/compiler/staticInstanceResolution5_1.ts (3 errors) ====
import WinJS = require('staticInstanceResolution5_0.ts');
import WinJS = require('staticInstanceResolution5_0');

// these 3 should be errors
var x = (w1: WinJS) => { };
Expand Down
2 changes: 1 addition & 1 deletion tests/baselines/reference/staticInstanceResolution5.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export class Promise {
}

//// [staticInstanceResolution5_1.ts]
import WinJS = require('staticInstanceResolution5_0.ts');
import WinJS = require('staticInstanceResolution5_0');

// these 3 should be errors
var x = (w1: WinJS) => { };
Expand Down
2 changes: 1 addition & 1 deletion tests/cases/compiler/missingFunctionImplementation2.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @Filename: missingFunctionImplementation2_a.ts
export {};
declare module "./missingFunctionImplementation2_b.ts" {
declare module "./missingFunctionImplementation2_b" {
export function f(a, b): void;
}

Expand Down
19 changes: 19 additions & 0 deletions tests/cases/compiler/moduleResolutionNoTs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// @filename: x.ts
export default 0;

// @filename: y.tsx
export default 0;

// @filename: z.d.ts
declare const x: number;
export default x;

// @filename: user.ts
import x from "./x.ts";
import y from "./y.tsx";
import z from "./z.d.ts";

// Making sure the suggested fixes are valid:
import x2 from "./x";
import y2 from "./y";
import z2 from "./z";
2 changes: 1 addition & 1 deletion tests/cases/compiler/staticInstanceResolution5.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export class Promise {
}

// @Filename: staticInstanceResolution5_1.ts
import WinJS = require('staticInstanceResolution5_0.ts');
import WinJS = require('staticInstanceResolution5_0');

// these 3 should be errors
var x = (w1: WinJS) => { };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,6 @@ export default 0;
// @Filename: /src/b.ts
import a from './a';

// Matching extension
// @Filename: /src/c.ts
import a from './a.ts';

// '.js' extension: stripped and replaced with '.ts'
// @Filename: /src/d.ts
import a from './a.js';
Expand Down