Merge branch 'master' into tscJsFiles

This commit is contained in:
Sheetal Nandi
2015-09-14 12:40:47 -07:00
187 changed files with 4163 additions and 1640 deletions
+114 -42
View File
@@ -976,8 +976,8 @@ namespace ts {
}
}
let fileName = getResolvedModuleFileName(getSourceFile(location), moduleReferenceLiteral.text);
let sourceFile = fileName && host.getSourceFile(fileName);
let resolvedModule = getResolvedModule(getSourceFile(location), moduleReferenceLiteral.text);
let sourceFile = resolvedModule && host.getSourceFile(resolvedModule.resolvedFileName);
if (sourceFile) {
if (sourceFile.symbol) {
return sourceFile.symbol;
@@ -2318,8 +2318,8 @@ namespace ts {
// Use type of the specified property, or otherwise, for a numeric name, the type of the numeric index signature,
// or otherwise the type of the string index signature.
type = getTypeOfPropertyOfType(parentType, name.text) ||
isNumericLiteralName(name.text) && getIndexTypeOfType(parentType, IndexKind.Number) ||
getIndexTypeOfType(parentType, IndexKind.String);
isNumericLiteralName(name.text) && getIndexTypeOfType(parentType, IndexKind.Number) ||
getIndexTypeOfType(parentType, IndexKind.String);
if (!type) {
error(name, Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), declarationNameToString(name));
return unknownType;
@@ -2406,7 +2406,7 @@ namespace ts {
// If the declaration specifies a binding pattern, use the type implied by the binding pattern
if (isBindingPattern(declaration.name)) {
return getTypeFromBindingPattern(<BindingPattern>declaration.name);
return getTypeFromBindingPattern(<BindingPattern>declaration.name, /*includePatternInType*/ false);
}
// No type specified and nothing can be inferred
@@ -2416,48 +2416,47 @@ namespace ts {
// Return the type implied by a binding pattern element. This is the type of the initializer of the element if
// one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding
// pattern. Otherwise, it is the type any.
function getTypeFromBindingElement(element: BindingElement): Type {
function getTypeFromBindingElement(element: BindingElement, includePatternInType?: boolean): Type {
if (element.initializer) {
return getWidenedType(checkExpressionCached(element.initializer));
}
if (isBindingPattern(element.name)) {
return getTypeFromBindingPattern(<BindingPattern>element.name);
return getTypeFromBindingPattern(<BindingPattern>element.name, includePatternInType);
}
return anyType;
}
// Return the type implied by an object binding pattern
function getTypeFromObjectBindingPattern(pattern: BindingPattern): Type {
function getTypeFromObjectBindingPattern(pattern: BindingPattern, includePatternInType: boolean): Type {
let members: SymbolTable = {};
forEach(pattern.elements, e => {
let flags = SymbolFlags.Property | SymbolFlags.Transient | (e.initializer ? SymbolFlags.Optional : 0);
let name = e.propertyName || <Identifier>e.name;
let symbol = <TransientSymbol>createSymbol(flags, name.text);
symbol.type = getTypeFromBindingElement(e);
symbol.type = getTypeFromBindingElement(e, includePatternInType);
symbol.bindingElement = e;
members[symbol.name] = symbol;
});
return createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined);
let result = createAnonymousType(undefined, members, emptyArray, emptyArray, undefined, undefined);
if (includePatternInType) {
result.pattern = pattern;
}
return result;
}
// Return the type implied by an array binding pattern
function getTypeFromArrayBindingPattern(pattern: BindingPattern): Type {
let hasSpreadElement: boolean = false;
let elementTypes: Type[] = [];
forEach(pattern.elements, e => {
elementTypes.push(e.kind === SyntaxKind.OmittedExpression || e.dotDotDotToken ? anyType : getTypeFromBindingElement(e));
if (e.dotDotDotToken) {
hasSpreadElement = true;
}
});
if (!elementTypes.length) {
function getTypeFromArrayBindingPattern(pattern: BindingPattern, includePatternInType: boolean): Type {
let elements = pattern.elements;
if (elements.length === 0 || elements[elements.length - 1].dotDotDotToken) {
return languageVersion >= ScriptTarget.ES6 ? createIterableType(anyType) : anyArrayType;
}
else if (hasSpreadElement) {
let unionOfElements = getUnionType(elementTypes);
return languageVersion >= ScriptTarget.ES6 ? createIterableType(unionOfElements) : createArrayType(unionOfElements);
}
// If the pattern has at least one element, and no rest element, then it should imply a tuple type.
let elementTypes = map(elements, e => e.kind === SyntaxKind.OmittedExpression ? anyType : getTypeFromBindingElement(e, includePatternInType));
if (includePatternInType) {
let result = createNewTupleType(elementTypes);
result.pattern = pattern;
return result;
}
return createTupleType(elementTypes);
}
@@ -2468,10 +2467,10 @@ namespace ts {
// used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring
// parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of
// the parameter.
function getTypeFromBindingPattern(pattern: BindingPattern): Type {
function getTypeFromBindingPattern(pattern: BindingPattern, includePatternInType?: boolean): Type {
return pattern.kind === SyntaxKind.ObjectBindingPattern
? getTypeFromObjectBindingPattern(pattern)
: getTypeFromArrayBindingPattern(pattern);
? getTypeFromObjectBindingPattern(pattern, includePatternInType)
: getTypeFromArrayBindingPattern(pattern, includePatternInType);
}
// Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type
@@ -3126,7 +3125,7 @@ namespace ts {
}
function findMatchingSignature(signatureList: Signature[], signature: Signature, partialMatch: boolean, ignoreReturnTypes: boolean): Signature {
for (let s of signatureList) {
for (let s of signatureList) {
if (compareSignatures(s, signature, partialMatch, ignoreReturnTypes, compareTypes)) {
return s;
}
@@ -4047,11 +4046,12 @@ namespace ts {
function createTupleType(elementTypes: Type[]) {
let id = getTypeListId(elementTypes);
let type = tupleTypes[id];
if (!type) {
type = tupleTypes[id] = <TupleType>createObjectType(TypeFlags.Tuple | getPropagatingFlagsOfTypes(elementTypes));
type.elementTypes = elementTypes;
}
return tupleTypes[id] || (tupleTypes[id] = createNewTupleType(elementTypes));
}
function createNewTupleType(elementTypes: Type[]) {
let type = <TupleType>createObjectType(TypeFlags.Tuple | getPropagatingFlagsOfTypes(elementTypes));
type.elementTypes = elementTypes;
return type;
}
@@ -4640,7 +4640,9 @@ namespace ts {
// and intersection types are further deconstructed on the target side, we don't want to
// make the check again (as it might fail for a partial target type). Therefore we obtain
// the regular source type and proceed with that.
source = getRegularTypeOfObjectLiteral(source);
if (target.flags & TypeFlags.UnionOrIntersection) {
source = getRegularTypeOfObjectLiteral(source);
}
}
let saveErrorInfo = errorInfo;
@@ -5511,6 +5513,7 @@ namespace ts {
regularType.constructSignatures = (<ResolvedType>type).constructSignatures;
regularType.stringIndexType = (<ResolvedType>type).stringIndexType;
regularType.numberIndexType = (<ResolvedType>type).numberIndexType;
(<FreshObjectLiteralType>type).regularType = regularType;
}
return regularType;
}
@@ -6613,7 +6616,7 @@ namespace ts {
}
}
if (isBindingPattern(declaration.name)) {
return getTypeFromBindingPattern(<BindingPattern>declaration.name);
return getTypeFromBindingPattern(<BindingPattern>declaration.name, /*includePatternInType*/ true);
}
}
return undefined;
@@ -7009,11 +7012,13 @@ namespace ts {
return checkIteratedTypeOrElementType(arrayOrIterableType, node.expression, /*allowStringInput*/ false);
}
function hasDefaultValue(node: BindingElement | Expression): boolean {
return (node.kind === SyntaxKind.BindingElement && !!(<BindingElement>node).initializer) ||
(node.kind === SyntaxKind.BinaryExpression && (<BinaryExpression>node).operatorToken.kind === SyntaxKind.EqualsToken);
}
function checkArrayLiteral(node: ArrayLiteralExpression, contextualMapper?: TypeMapper): Type {
let elements = node.elements;
if (!elements.length) {
return createArrayType(undefinedType);
}
let hasSpreadElement = false;
let elementTypes: Type[] = [];
let inDestructuringPattern = isAssignmentTarget(node);
@@ -7045,12 +7050,39 @@ namespace ts {
hasSpreadElement = hasSpreadElement || e.kind === SyntaxKind.SpreadElementExpression;
}
if (!hasSpreadElement) {
// If array literal is actually a destructuring pattern, mark it as an implied type. We do this such
// that we get the same behavior for "var [x, y] = []" and "[x, y] = []".
if (inDestructuringPattern && elementTypes.length) {
let type = createNewTupleType(elementTypes);
type.pattern = node;
return type;
}
let contextualType = getContextualType(node);
if (contextualType && contextualTypeIsTupleLikeType(contextualType) || inDestructuringPattern) {
return createTupleType(elementTypes);
if (contextualType && contextualTypeIsTupleLikeType(contextualType)) {
let pattern = contextualType.pattern;
// If array literal is contextually typed by a binding pattern or an assignment pattern, pad the resulting
// tuple type with the corresponding binding or assignment element types to make the lengths equal.
if (pattern && (pattern.kind === SyntaxKind.ArrayBindingPattern || pattern.kind === SyntaxKind.ArrayLiteralExpression)) {
let patternElements = (<BindingPattern | ArrayLiteralExpression>pattern).elements;
for (let i = elementTypes.length; i < patternElements.length; i++) {
let patternElement = patternElements[i];
if (hasDefaultValue(patternElement)) {
elementTypes.push((<TupleType>contextualType).elementTypes[i]);
}
else {
if (patternElement.kind !== SyntaxKind.OmittedExpression) {
error(patternElement, Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
}
elementTypes.push(unknownType);
}
}
}
if (elementTypes.length) {
return createTupleType(elementTypes);
}
}
}
return createArrayType(getUnionType(elementTypes));
return createArrayType(elementTypes.length ? getUnionType(elementTypes) : undefinedType)
}
function isNumericName(name: DeclarationName): boolean {
@@ -7117,6 +7149,9 @@ namespace ts {
let propertiesTable: SymbolTable = {};
let propertiesArray: Symbol[] = [];
let contextualType = getContextualType(node);
let contextualTypeHasPattern = contextualType && contextualType.pattern &&
(contextualType.pattern.kind === SyntaxKind.ObjectBindingPattern || contextualType.pattern.kind === SyntaxKind.ObjectLiteralExpression);
let inDestructuringPattern = isAssignmentTarget(node);
let typeFlags: TypeFlags = 0;
for (let memberDecl of node.properties) {
@@ -7137,6 +7172,25 @@ namespace ts {
}
typeFlags |= type.flags;
let prop = <TransientSymbol>createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.name);
if (inDestructuringPattern) {
// If object literal is an assignment pattern and if the assignment pattern specifies a default value
// for the property, make the property optional.
if (memberDecl.kind === SyntaxKind.PropertyAssignment && hasDefaultValue((<PropertyAssignment>memberDecl).initializer)) {
prop.flags |= SymbolFlags.Optional;
}
}
else if (contextualTypeHasPattern) {
// If object literal is contextually typed by the implied type of a binding pattern, and if the
// binding pattern specifies a default value for the property, make the property optional.
let impliedProp = getPropertyOfType(contextualType, member.name);
if (impliedProp) {
prop.flags |= impliedProp.flags & SymbolFlags.Optional;
}
else if (!compilerOptions.suppressExcessPropertyErrors) {
error(memberDecl.name, Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1,
symbolToString(member), typeToString(contextualType));
}
}
prop.declarations = member.declarations;
prop.parent = member.parent;
if (member.valueDeclaration) {
@@ -7163,11 +7217,29 @@ namespace ts {
propertiesArray.push(member);
}
// If object literal is contextually typed by the implied type of a binding pattern, augment the result
// type with those properties for which the binding pattern specifies a default value.
if (contextualTypeHasPattern) {
for (let prop of getPropertiesOfType(contextualType)) {
if (!hasProperty(propertiesTable, prop.name)) {
if (!(prop.flags & SymbolFlags.Optional)) {
error(prop.valueDeclaration || (<TransientSymbol>prop).bindingElement,
Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
}
propertiesTable[prop.name] = prop;
propertiesArray.push(prop);
}
}
}
let stringIndexType = getIndexType(IndexKind.String);
let numberIndexType = getIndexType(IndexKind.Number);
let result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType);
let freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : TypeFlags.FreshObjectLiteral;
result.flags |= TypeFlags.ObjectLiteral | TypeFlags.ContainsObjectLiteral | freshObjectLiteralFlag | (typeFlags & TypeFlags.PropagatingFlags);
if (inDestructuringPattern) {
result.pattern = node;
}
return result;
function getIndexType(kind: IndexKind) {
@@ -415,6 +415,7 @@ namespace ts {
The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: DiagnosticCategory.Error, key: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." },
yield_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2523, category: DiagnosticCategory.Error, key: "'yield' expressions cannot be used in a parameter initializer." },
await_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2524, category: DiagnosticCategory.Error, key: "'await' expressions cannot be used in a parameter initializer." },
Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value: { code: 2525, category: DiagnosticCategory.Error, key: "Initializer provides no value for this binding element and the binding element has no default value." },
JSX_element_attributes_type_0_must_be_an_object_type: { code: 2600, category: DiagnosticCategory.Error, key: "JSX element attributes type '{0}' must be an object type." },
The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: DiagnosticCategory.Error, key: "The return type of a JSX element constructor must return an object type." },
JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: DiagnosticCategory.Error, key: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." },
@@ -428,6 +429,8 @@ namespace ts {
A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: { code: 2651, category: DiagnosticCategory.Error, key: "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums." },
Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: { code: 2652, category: DiagnosticCategory.Error, key: "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead." },
Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1: { code: 2653, category: DiagnosticCategory.Error, key: "Non-abstract class expression does not implement inherited abstract member '{0}' from class '{1}'." },
Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition: { code: 2654, category: DiagnosticCategory.Error, key: "Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition." },
Exported_external_package_typings_can_only_be_in_d_ts_files_Please_contact_the_package_author_to_update_the_package_definition: { code: 2655, category: DiagnosticCategory.Error, key: "Exported external package typings can only be in '.d.ts' files. Please contact the package author to update the package definition." },
Import_declaration_0_is_using_private_name_1: { code: 4000, category: DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." },
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." },
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." },
+12 -1
View File
@@ -1649,6 +1649,10 @@
"category": "Error",
"code": 2524
},
"Initializer provides no value for this binding element and the binding element has no default value.": {
"category": "Error",
"code": 2525
},
"JSX element attributes type '{0}' must be an object type.": {
"category": "Error",
"code": 2600
@@ -1701,7 +1705,14 @@
"category": "Error",
"code": 2653
},
"Exported external package typings file cannot contain tripleslash references. Please contact the package author to update the package definition.": {
"category": "Error",
"code": 2654
},
"Exported external package typings can only be in '.d.ts' files. Please contact the package author to update the package definition.": {
"category": "Error",
"code": 2655
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
+102 -53
View File
@@ -186,6 +186,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
/** Sourcemap data that will get encoded */
let sourceMapData: SourceMapData;
/** If removeComments is true, no leading-comments needed to be emitted **/
let emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos: number) { } : emitLeadingCommentsOfPositionWorker;
if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {
initializeEmitterWithSourceMaps();
}
@@ -1292,8 +1295,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function jsxEmitPreserve(node: JsxElement|JsxSelfClosingElement) {
function emitJsxAttribute(node: JsxAttribute) {
emit(node.name);
write("=");
emit(node.initializer);
if (node.initializer) {
write("=");
emit(node.initializer);
}
}
function emitJsxSpreadAttribute(node: JsxSpreadAttribute) {
@@ -2352,7 +2357,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
operand.kind !== SyntaxKind.PostfixUnaryExpression &&
operand.kind !== SyntaxKind.NewExpression &&
!(operand.kind === SyntaxKind.CallExpression && node.parent.kind === SyntaxKind.NewExpression) &&
!(operand.kind === SyntaxKind.FunctionExpression && node.parent.kind === SyntaxKind.CallExpression)) {
!(operand.kind === SyntaxKind.FunctionExpression && node.parent.kind === SyntaxKind.CallExpression) &&
!(operand.kind === SyntaxKind.NumericLiteral && node.parent.kind === SyntaxKind.PropertyAccessExpression)) {
emit(operand);
return;
}
@@ -3142,6 +3148,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitExportSpecifierInSystemModule(specifier: ExportSpecifier): void {
Debug.assert(compilerOptions.module === ModuleKind.System);
if (!resolver.getReferencedValueDeclaration(specifier.propertyName || specifier.name) && !resolver.isValueAliasDeclaration(specifier) ) {
return;
}
writeLine();
emitStart(specifier.name);
@@ -3666,7 +3676,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitFunctionDeclaration(node: FunctionLikeDeclaration) {
if (nodeIsMissing(node.body)) {
return emitOnlyPinnedOrTripleSlashComments(node);
return emitCommentsOnNotEmittedNode(node);
}
// TODO (yuisu) : we should not have special cases to condition emitting comments
@@ -4143,7 +4153,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
else if (member.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature) {
if (!(<MethodDeclaration>member).body) {
return emitOnlyPinnedOrTripleSlashComments(member);
return emitCommentsOnNotEmittedNode(member);
}
writeLine();
@@ -4210,7 +4220,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitMemberFunctionsForES6AndHigher(node: ClassLikeDeclaration) {
for (let member of node.members) {
if ((member.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.MethodSignature) && !(<MethodDeclaration>member).body) {
emitOnlyPinnedOrTripleSlashComments(member);
emitCommentsOnNotEmittedNode(member);
}
else if (member.kind === SyntaxKind.MethodDeclaration ||
member.kind === SyntaxKind.GetAccessor ||
@@ -4267,7 +4277,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// Emit the constructor overload pinned comments
forEach(node.members, member => {
if (member.kind === SyntaxKind.Constructor && !(<ConstructorDeclaration>member).body) {
emitOnlyPinnedOrTripleSlashComments(member);
emitCommentsOnNotEmittedNode(member);
}
// Check if there is any non-static property assignment
if (member.kind === SyntaxKind.PropertyDeclaration && (<PropertyDeclaration>member).initializer && (member.flags & NodeFlags.Static) === 0) {
@@ -5166,7 +5176,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function emitInterfaceDeclaration(node: InterfaceDeclaration) {
emitOnlyPinnedOrTripleSlashComments(node);
emitCommentsOnNotEmittedNode(node);
}
function shouldEmitEnumDeclaration(node: EnumDeclaration) {
@@ -5288,7 +5298,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let shouldEmit = shouldEmitModuleDeclaration(node);
if (!shouldEmit) {
return emitOnlyPinnedOrTripleSlashComments(node);
return emitCommentsOnNotEmittedNode(node);
}
let hoistedInDeclarationScope = shouldHoistDeclarationInSystemJsModule(node);
let emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node);
@@ -6089,7 +6099,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return;
}
if (isInternalModuleImportEqualsDeclaration(node)) {
if (isInternalModuleImportEqualsDeclaration(node) && resolver.isValueAliasDeclaration(node)) {
if (!hoistedVars) {
hoistedVars = [];
}
@@ -6718,7 +6728,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitNodeConsideringCommentsOption(node: Node, emitNodeConsideringSourcemap: (node: Node) => void): void {
if (node) {
if (node.flags & NodeFlags.Ambient) {
return emitOnlyPinnedOrTripleSlashComments(node);
return emitCommentsOnNotEmittedNode(node);
}
if (isSpecializedCommentHandling(node)) {
@@ -6985,22 +6995,28 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return leadingComments;
}
/**
* Removes all but the pinned or triple slash comments.
* @param ranges The array to be filtered
* @param onlyPinnedOrTripleSlashComments whether the filtering should be performed.
*/
function filterComments(ranges: CommentRange[], onlyPinnedOrTripleSlashComments: boolean): CommentRange[] {
// If we're removing comments, then we want to strip out all but the pinned or
// triple slash comments.
if (ranges && onlyPinnedOrTripleSlashComments) {
ranges = filter(ranges, isPinnedOrTripleSlashComment);
if (ranges.length === 0) {
return undefined;
}
}
function isPinnedComments(comment: CommentRange) {
return currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk &&
currentSourceFile.text.charCodeAt(comment.pos + 2) === CharacterCodes.exclamation;
}
return ranges;
/**
* Determine if the given comment is a triple-slash
*
* @return true if the comment is a triple-slash comment else false
**/
function isTripleSlashComment(comment: CommentRange) {
// Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
// so that we don't end up computing comment string and doing match for all // comments
if (currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.slash &&
comment.pos + 2 < comment.end &&
currentSourceFile.text.charCodeAt(comment.pos + 2) === CharacterCodes.slash) {
let textSubStr = currentSourceFile.text.substring(comment.pos, comment.end);
return textSubStr.match(fullTripleSlashReferencePathRegEx) ||
textSubStr.match(fullTripleSlashAMDReferencePathRegEx) ?
true : false;
}
return false;
}
function getLeadingCommentsToEmit(node: Node) {
@@ -7028,28 +7044,53 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
function emitOnlyPinnedOrTripleSlashComments(node: Node) {
emitLeadingCommentsWorker(node, /*onlyPinnedOrTripleSlashComments:*/ true);
/**
* Emit comments associated with node that will not be emitted into JS file
*/
function emitCommentsOnNotEmittedNode(node: Node) {
emitLeadingCommentsWorker(node, /*isEmittedNode:*/ false);
}
function emitLeadingComments(node: Node) {
return emitLeadingCommentsWorker(node, /*onlyPinnedOrTripleSlashComments:*/ compilerOptions.removeComments);
return emitLeadingCommentsWorker(node, /*isEmittedNode:*/ true);
}
function emitLeadingCommentsWorker(node: Node, onlyPinnedOrTripleSlashComments: boolean) {
// If the caller only wants pinned or triple slash comments, then always filter
// down to that set. Otherwise, filter based on the current compiler options.
let leadingComments = filterComments(getLeadingCommentsToEmit(node), onlyPinnedOrTripleSlashComments);
function emitLeadingCommentsWorker(node: Node, isEmittedNode: boolean) {
if (compilerOptions.removeComments) {
return;
}
let leadingComments: CommentRange[];
if (isEmittedNode) {
leadingComments = getLeadingCommentsToEmit(node);
}
else {
// If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
// unless it is a triple slash comment at the top of the file.
// For Example:
// /// <reference-path ...>
// declare var x;
// /// <reference-path ...>
// interface F {}
// The first /// will NOT be removed while the second one will be removed eventhough both node will not be emitted
if (node.pos === 0) {
leadingComments = filter(getLeadingCommentsToEmit(node), isTripleSlashComment);
}
}
emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments);
// Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment);
emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator:*/ true, newLine, writeComment);
}
function emitTrailingComments(node: Node) {
if (compilerOptions.removeComments) {
return;
}
// Emit the trailing comments only if the parent's end doesn't match
let trailingComments = filterComments(getTrailingCommentsToEmit(node), /*onlyPinnedOrTripleSlashComments:*/ compilerOptions.removeComments);
let trailingComments = getTrailingCommentsToEmit(node);
// trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/
emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment);
@@ -7061,13 +7102,21 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
* ^ => pos; the function will emit "comment1" in the emitJS
*/
function emitTrailingCommentsOfPosition(pos: number) {
let trailingComments = filterComments(getTrailingCommentRanges(currentSourceFile.text, pos), /*onlyPinnedOrTripleSlashComments:*/ compilerOptions.removeComments);
if (compilerOptions.removeComments) {
return;
}
let trailingComments = getTrailingCommentRanges(currentSourceFile.text, pos);
// trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/
emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment);
}
function emitLeadingCommentsOfPosition(pos: number) {
function emitLeadingCommentsOfPositionWorker(pos: number) {
if (compilerOptions.removeComments) {
return;
}
let leadingComments: CommentRange[];
if (hasDetachedComments(pos)) {
// get comments without detached comments
@@ -7078,7 +7127,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
leadingComments = getLeadingCommentRanges(currentSourceFile.text, pos);
}
leadingComments = filterComments(leadingComments, compilerOptions.removeComments);
emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments);
// Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
@@ -7086,7 +7134,22 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function emitDetachedComments(node: TextRange) {
let leadingComments = getLeadingCommentRanges(currentSourceFile.text, node.pos);
let leadingComments: CommentRange[];
if (compilerOptions.removeComments) {
// removeComments is true, only reserve pinned comment at the top of file
// For example:
// /*! Pinned Comment */
//
// var x = 10;
if (node.pos === 0) {
leadingComments = filter(getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComments);
}
}
else {
// removeComments is false, just get detached as normal and bypass the process to filter comment
leadingComments = getLeadingCommentRanges(currentSourceFile.text, node.pos);
}
if (leadingComments) {
let detachedComments: CommentRange[] = [];
let lastComment: CommentRange;
@@ -7136,20 +7199,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(shebang);
}
}
function isPinnedOrTripleSlashComment(comment: CommentRange) {
if (currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk) {
return currentSourceFile.text.charCodeAt(comment.pos + 2) === CharacterCodes.exclamation;
}
// Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
// so that we don't end up computing comment string and doing match for all // comments
else if (currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.slash &&
comment.pos + 2 < comment.end &&
currentSourceFile.text.charCodeAt(comment.pos + 2) === CharacterCodes.slash &&
currentSourceFile.text.substring(comment.pos, comment.end).match(fullTripleSlashReferencePathRegEx)) {
return true;
}
}
}
function emitFile(jsFilePath: string, sourceFile?: SourceFile) {
+13 -17
View File
@@ -1058,11 +1058,11 @@ namespace ts {
}
function parseIdentifierName(): Identifier {
return createIdentifier(isIdentifierOrKeyword());
return createIdentifier(tokenIsIdentifierOrKeyword(token));
}
function isLiteralPropertyName(): boolean {
return isIdentifierOrKeyword() ||
return tokenIsIdentifierOrKeyword(token) ||
token === SyntaxKind.StringLiteral ||
token === SyntaxKind.NumericLiteral;
}
@@ -1086,7 +1086,7 @@ namespace ts {
}
function isSimplePropertyName() {
return token === SyntaxKind.StringLiteral || token === SyntaxKind.NumericLiteral || isIdentifierOrKeyword();
return token === SyntaxKind.StringLiteral || token === SyntaxKind.NumericLiteral || tokenIsIdentifierOrKeyword(token);
}
function parseComputedPropertyName(): ComputedPropertyName {
@@ -1213,9 +1213,9 @@ namespace ts {
case ParsingContext.HeritageClauses:
return isHeritageClause();
case ParsingContext.ImportOrExportSpecifiers:
return isIdentifierOrKeyword();
return tokenIsIdentifierOrKeyword(token);
case ParsingContext.JsxAttributes:
return isIdentifierOrKeyword() || token === SyntaxKind.OpenBraceToken;
return tokenIsIdentifierOrKeyword(token) || token === SyntaxKind.OpenBraceToken;
case ParsingContext.JsxChildren:
return true;
case ParsingContext.JSDocFunctionParameters:
@@ -1254,7 +1254,7 @@ namespace ts {
function nextTokenIsIdentifierOrKeyword() {
nextToken();
return isIdentifierOrKeyword();
return tokenIsIdentifierOrKeyword(token);
}
function isHeritageClauseExtendsOrImplementsKeyword(): boolean {
@@ -1824,7 +1824,7 @@ namespace ts {
// the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword".
// In the first case though, ASI will not take effect because there is not a
// line terminator after the identifier or keyword.
if (scanner.hasPrecedingLineBreak() && isIdentifierOrKeyword()) {
if (scanner.hasPrecedingLineBreak() && tokenIsIdentifierOrKeyword(token)) {
let matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
if (matchesPattern) {
@@ -2282,7 +2282,7 @@ namespace ts {
}
}
if (isIdentifierOrKeyword()) {
if (tokenIsIdentifierOrKeyword(token)) {
return parsePropertyOrMethodSignature();
}
}
@@ -4101,13 +4101,9 @@ namespace ts {
}
}
function isIdentifierOrKeyword() {
return token >= SyntaxKind.Identifier;
}
function nextTokenIsIdentifierOrKeywordOnSameLine() {
nextToken();
return isIdentifierOrKeyword() && !scanner.hasPrecedingLineBreak();
return tokenIsIdentifierOrKeyword(token) && !scanner.hasPrecedingLineBreak();
}
function nextTokenIsFunctionKeywordOnSameLine() {
@@ -4117,7 +4113,7 @@ namespace ts {
function nextTokenIsIdentifierOrKeywordOrNumberOnSameLine() {
nextToken();
return (isIdentifierOrKeyword() || token === SyntaxKind.NumericLiteral) && !scanner.hasPrecedingLineBreak();
return (tokenIsIdentifierOrKeyword(token) || token === SyntaxKind.NumericLiteral) && !scanner.hasPrecedingLineBreak();
}
function isDeclaration(): boolean {
@@ -4170,7 +4166,7 @@ namespace ts {
case SyntaxKind.ImportKeyword:
nextToken();
return token === SyntaxKind.StringLiteral || token === SyntaxKind.AsteriskToken ||
token === SyntaxKind.OpenBraceToken || isIdentifierOrKeyword();
token === SyntaxKind.OpenBraceToken || tokenIsIdentifierOrKeyword(token);
case SyntaxKind.ExportKeyword:
nextToken();
if (token === SyntaxKind.EqualsToken || token === SyntaxKind.AsteriskToken ||
@@ -4777,7 +4773,7 @@ namespace ts {
// It is very important that we check this *after* checking indexers because
// the [ token can start an index signature or a computed property name
if (isIdentifierOrKeyword() ||
if (tokenIsIdentifierOrKeyword(token) ||
token === SyntaxKind.StringLiteral ||
token === SyntaxKind.NumericLiteral ||
token === SyntaxKind.AsteriskToken ||
@@ -5320,7 +5316,7 @@ namespace ts {
return true;
}
return isIdentifierOrKeyword();
return tokenIsIdentifierOrKeyword(token);
}
export function parseJSDocTypeExpressionForTests(content: string, start: number, length: number) {
+88 -81
View File
@@ -36,7 +36,7 @@ namespace ts {
return normalizePath(referencedFileName);
}
export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModule {
export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
let moduleResolution = compilerOptions.moduleResolution !== undefined
? compilerOptions.moduleResolution
: compilerOptions.module === ModuleKind.CommonJS ? ModuleResolutionKind.NodeJs : ModuleResolutionKind.Classic;
@@ -47,7 +47,7 @@ namespace ts {
}
}
export function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModule {
export function nodeModuleNameResolver(moduleName: string, containingFile: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
let containingDirectory = getDirectoryPath(containingFile);
if (getRootLength(moduleName) !== 0 || nameStartsWithDotSlashOrDotDotSlash(moduleName)) {
@@ -56,11 +56,13 @@ namespace ts {
let resolvedFileName = loadNodeModuleFromFile(candidate, /* loadOnlyDts */ false, failedLookupLocations, host);
if (resolvedFileName) {
return { resolvedFileName, failedLookupLocations };
return { resolvedModule: { resolvedFileName }, failedLookupLocations };
}
resolvedFileName = loadNodeModuleFromDirectory(candidate, /* loadOnlyDts */ false, failedLookupLocations, host);
return { resolvedFileName, failedLookupLocations };
return resolvedFileName
? { resolvedModule: { resolvedFileName }, failedLookupLocations }
: { resolvedModule: undefined, failedLookupLocations };
}
else {
return loadModuleFromNodeModules(moduleName, containingDirectory, host);
@@ -117,7 +119,7 @@ namespace ts {
return loadNodeModuleFromFile(combinePaths(candidate, "index"), loadOnlyDts, failedLookupLocation, host);
}
function loadModuleFromNodeModules(moduleName: string, directory: string, host: ModuleResolutionHost): ResolvedModule {
function loadModuleFromNodeModules(moduleName: string, directory: string, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
let failedLookupLocations: string[] = [];
directory = normalizeSlashes(directory);
while (true) {
@@ -127,12 +129,12 @@ namespace ts {
let candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName));
let result = loadNodeModuleFromFile(candidate, /* loadOnlyDts */ true, failedLookupLocations, host);
if (result) {
return { resolvedFileName: result, failedLookupLocations };
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations };
}
result = loadNodeModuleFromDirectory(candidate, /* loadOnlyDts */ true, failedLookupLocations, host);
if (result) {
return { resolvedFileName: result, failedLookupLocations };
return { resolvedModule: { resolvedFileName: result, isExternalLibraryImport: true }, failedLookupLocations };
}
}
@@ -144,47 +146,19 @@ namespace ts {
directory = parentPath;
}
return { resolvedFileName: undefined, failedLookupLocations };
}
export function baseUrlModuleNameResolver(moduleName: string, containingFile: string, baseUrl: string, host: ModuleResolutionHost): ResolvedModule {
Debug.assert(baseUrl !== undefined);
let normalizedModuleName = normalizeSlashes(moduleName);
let basePart = useBaseUrl(moduleName) ? baseUrl : getDirectoryPath(containingFile);
let candidate = normalizePath(combinePaths(basePart, moduleName));
let failedLookupLocations: string[] = [];
return forEach(supportedExtensions, ext => tryLoadFile(candidate + ext)) || { resolvedFileName: undefined, failedLookupLocations };
function tryLoadFile(location: string): ResolvedModule {
if (host.fileExists(location)) {
return { resolvedFileName: location, failedLookupLocations };
}
else {
failedLookupLocations.push(location);
return undefined;
}
}
return { resolvedModule: undefined, failedLookupLocations };
}
function nameStartsWithDotSlashOrDotDotSlash(name: string) {
let i = name.lastIndexOf("./", 1);
return i === 0 || (i === 1 && name.charCodeAt(0) === CharacterCodes.dot);
}
function useBaseUrl(moduleName: string): boolean {
// path is not rooted
// module name does not start with './' or '../'
return getRootLength(moduleName) === 0 && !nameStartsWithDotSlashOrDotDotSlash(moduleName);
}
export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModule {
export function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
// module names that contain '!' are used to reference resources and are not resolved to actual files on disk
if (moduleName.indexOf('!') != -1) {
return { resolvedFileName: undefined, failedLookupLocations: [] };
return { resolvedModule: undefined, failedLookupLocations: [] };
}
let searchPath = getDirectoryPath(containingFile);
@@ -222,7 +196,9 @@ namespace ts {
searchPath = parentPath;
}
return { resolvedFileName: referencedSourceFile, failedLookupLocations };
return referencedSourceFile
? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations }
: { resolvedModule: undefined, failedLookupLocations };
}
/* @internal */
@@ -358,7 +334,8 @@ namespace ts {
export function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program {
let program: Program;
let files: SourceFile[] = [];
let diagnostics = createDiagnosticCollection();
let fileProcessingDiagnostics = createDiagnosticCollection();
let programDiagnostics = createDiagnosticCollection();
let commonSourceDirectory: string;
let diagnosticsProducingTypeChecker: TypeChecker;
@@ -371,9 +348,9 @@ namespace ts {
host = host || createCompilerHost(options);
const resolveModuleNamesWorker =
host.resolveModuleNames ||
((moduleNames, containingFile) => map(moduleNames, moduleName => resolveModuleName(moduleName, containingFile, options, host).resolvedFileName));
const resolveModuleNamesWorker = host.resolveModuleNames
? ((moduleNames: string[], containingFile: string) => host.resolveModuleNames(moduleNames, containingFile))
: ((moduleNames: string[], containingFile: string) => map(moduleNames, moduleName => resolveModuleName(moduleName, containingFile, options, host).resolvedModule));
let filesByName = createFileMap<SourceFile>(fileName => host.getCanonicalFileName(fileName));
@@ -428,6 +405,7 @@ namespace ts {
getIdentifierCount: () => getDiagnosticsProducingTypeChecker().getIdentifierCount(),
getSymbolCount: () => getDiagnosticsProducingTypeChecker().getSymbolCount(),
getTypeCount: () => getDiagnosticsProducingTypeChecker().getTypeCount(),
getFileProcessingDiagnostics: () => fileProcessingDiagnostics
};
return program;
@@ -460,6 +438,7 @@ namespace ts {
// check if program source files has changed in the way that can affect structure of the program
let newSourceFiles: SourceFile[] = [];
let modifiedSourceFiles: SourceFile[] = [];
for (let oldSourceFile of oldProgram.getSourceFiles()) {
let newSourceFile = host.getSourceFile(oldSourceFile.fileName, options.target);
if (!newSourceFile) {
@@ -491,14 +470,22 @@ namespace ts {
let resolutions = resolveModuleNamesWorker(moduleNames, newSourceFile.fileName);
// ensure that module resolution results are still correct
for (let i = 0; i < moduleNames.length; ++i) {
let oldResolution = getResolvedModuleFileName(oldSourceFile, moduleNames[i]);
if (oldResolution !== resolutions[i]) {
let newResolution = resolutions[i];
let oldResolution = getResolvedModule(oldSourceFile, moduleNames[i]);
let resolutionChanged = oldResolution
? !newResolution ||
oldResolution.resolvedFileName !== newResolution.resolvedFileName ||
!!oldResolution.isExternalLibraryImport !== !!newResolution.isExternalLibraryImport
: newResolution;
if (resolutionChanged) {
return false;
}
}
}
}
// pass the cache of module resolutions from the old source file
newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
modifiedSourceFiles.push(newSourceFile);
}
else {
// file has no changes - use it as is
@@ -515,7 +502,11 @@ namespace ts {
}
files = newSourceFiles;
fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
for (let modifiedFile of modifiedSourceFiles) {
fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile);
}
oldProgram.structureIsReused = true;
return true;
@@ -652,9 +643,10 @@ namespace ts {
Debug.assert(!!sourceFile.bindDiagnostics);
let bindDiagnostics = sourceFile.bindDiagnostics;
let checkDiagnostics = typeChecker.getDiagnostics(sourceFile, cancellationToken);
let programDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
let fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
let programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
return bindDiagnostics.concat(checkDiagnostics).concat(programDiagnostics);
return bindDiagnostics.concat(checkDiagnostics).concat(fileProcessingDiagnosticsInFile).concat(programDiagnosticsInFile);
});
}
@@ -830,7 +822,8 @@ namespace ts {
function getOptionsDiagnostics(): Diagnostic[] {
let allDiagnostics: Diagnostic[] = [];
addRange(allDiagnostics, diagnostics.getGlobalDiagnostics());
addRange(allDiagnostics, fileProcessingDiagnostics.getGlobalDiagnostics())
addRange(allDiagnostics, programDiagnostics.getGlobalDiagnostics());
return sortAndDeduplicateDiagnostics(allDiagnostics);
}
@@ -938,10 +931,10 @@ namespace ts {
if (diagnostic) {
if (refFile !== undefined && refEnd !== undefined && refPos !== undefined) {
diagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, diagnostic, ...diagnosticArgument));
fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos, diagnostic, ...diagnosticArgument));
}
else {
diagnostics.add(createCompilerDiagnostic(diagnostic, ...diagnosticArgument));
fileProcessingDiagnostics.add(createCompilerDiagnostic(diagnostic, ...diagnosticArgument));
}
}
}
@@ -963,11 +956,11 @@ namespace ts {
// We haven't looked for this file, do so now and cache result
let file = host.getSourceFile(fileName, options.target, hostErrorMessage => {
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
diagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos,
fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos,
Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
}
else {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
fileProcessingDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, hostErrorMessage));
}
});
filesByName.set(canonicalName, file);
@@ -1003,11 +996,11 @@ namespace ts {
let sourceFileName = useAbsolutePath ? getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory()) : file.fileName;
if (canonicalName !== sourceFileName) {
if (refFile !== undefined && refPos !== undefined && refEnd !== undefined) {
diagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos,
fileProcessingDiagnostics.add(createFileDiagnostic(refFile, refPos, refEnd - refPos,
Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, sourceFileName));
}
else {
diagnostics.add(createCompilerDiagnostic(Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, sourceFileName));
fileProcessingDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, sourceFileName));
}
}
}
@@ -1030,9 +1023,23 @@ namespace ts {
let resolutions = resolveModuleNamesWorker(moduleNames, file.fileName);
for (let i = 0; i < file.imports.length; ++i) {
let resolution = resolutions[i];
setResolvedModuleName(file, moduleNames[i], resolution);
setResolvedModule(file, moduleNames[i], resolution);
if (resolution && !options.noResolve) {
findModuleSourceFile(resolution, file.imports[i]);
const importedFile = findModuleSourceFile(resolution.resolvedFileName, file.imports[i]);
if (importedFile && resolution.isExternalLibraryImport) {
if (!isExternalModule(importedFile)) {
let start = getTokenPosOfNode(file.imports[i], file)
fileProcessingDiagnostics.add(createFileDiagnostic(file, start, file.imports[i].end - start, Diagnostics.File_0_is_not_a_module, importedFile.fileName));
}
else if (!fileExtensionIs(importedFile.fileName, ".d.ts")) {
let start = getTokenPosOfNode(file.imports[i], file)
fileProcessingDiagnostics.add(createFileDiagnostic(file, start, file.imports[i].end - start, Diagnostics.Exported_external_package_typings_can_only_be_in_d_ts_files_Please_contact_the_package_author_to_update_the_package_definition));
}
else if (importedFile.referencedFiles.length) {
let firstRef = importedFile.referencedFiles[0];
fileProcessingDiagnostics.add(createFileDiagnostic(importedFile, firstRef.pos, firstRef.end - firstRef.pos, Diagnostics.Exported_external_package_typings_file_cannot_contain_tripleslash_references_Please_contact_the_package_author_to_update_the_package_definition));
}
}
}
}
}
@@ -1043,7 +1050,7 @@ namespace ts {
return;
function findModuleSourceFile(fileName: string, nameLiteral: Expression) {
return findSourceFile(fileName, /* isDefaultLib */ false, file, nameLiteral.pos, nameLiteral.end);
return findSourceFile(fileName, /* isDefaultLib */ false, file, skipTrivia(file.text, nameLiteral.pos), nameLiteral.end);
}
}
@@ -1068,7 +1075,7 @@ namespace ts {
for (let i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); i < n; i++) {
if (commonPathComponents[i] !== sourcePathComponents[i]) {
if (i === 0) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files));
return;
}
@@ -1097,7 +1104,7 @@ namespace ts {
if (!isDeclarationFile(sourceFile)) {
let absoluteSourceFilePath = host.getCanonicalFileName(getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, options.rootDir));
allFilesBelongToPath = false;
}
}
@@ -1110,52 +1117,52 @@ namespace ts {
function verifyCompilerOptions() {
if (options.isolatedModules) {
if (options.declaration) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "declaration", "isolatedModules"));
}
if (options.noEmitOnError) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmitOnError", "isolatedModules"));
}
if (options.out) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules"));
}
if (options.outFile) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules"));
}
}
if (options.inlineSourceMap) {
if (options.sourceMap) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap"));
}
if (options.mapRoot) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap"));
}
if (options.sourceRoot) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSourceMap"));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceRoot", "inlineSourceMap"));
}
}
if (options.inlineSources) {
if (!options.sourceMap && !options.inlineSourceMap) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_inlineSources_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided));
}
}
if (options.out && options.outFile) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile"));
}
if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) {
// Error to specify --mapRoot or --sourceRoot without mapSourceFiles
if (options.mapRoot) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "mapRoot", "sourceMap"));
}
if (options.sourceRoot) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap"));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "sourceRoot", "sourceMap"));
}
return;
}
@@ -1166,24 +1173,24 @@ namespace ts {
let firstExternalModuleSourceFile = forEach(files, f => isExternalModule(f) ? f : undefined);
if (options.isolatedModules) {
if (!options.module && languageVersion < ScriptTarget.ES6) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES6_or_higher));
}
let firstNonExternalModuleSourceFile = forEach(files, f => !isExternalModule(f) && !isDeclarationFile(f) ? f : undefined);
if (firstNonExternalModuleSourceFile) {
let span = getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
diagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided));
programDiagnostics.add(createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_namespaces_when_the_isolatedModules_flag_is_provided));
}
}
else if (firstExternalModuleSourceFile && languageVersion < ScriptTarget.ES6 && !options.module) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
let span = getErrorSpanForNode(firstExternalModuleSourceFile, firstExternalModuleSourceFile.externalModuleIndicator);
diagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided));
programDiagnostics.add(createFileDiagnostic(firstExternalModuleSourceFile, span.start, span.length, Diagnostics.Cannot_compile_modules_unless_the_module_flag_is_provided));
}
// Cannot specify module gen target when in es6 or above
if (options.module && languageVersion >= ScriptTarget.ES6) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_compile_modules_into_commonjs_amd_system_or_umd_when_targeting_ES6_or_higher));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_compile_modules_into_commonjs_amd_system_or_umd_when_targeting_ES6_or_higher));
}
// there has to be common source directory if user specified --outdir || --sourceRoot
@@ -1212,30 +1219,30 @@ namespace ts {
if (options.noEmit) {
if (options.out) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "out"));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "out"));
}
if (options.outFile) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outFile"));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outFile"));
}
if (options.outDir) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outDir"));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "outDir"));
}
if (options.declaration) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration"));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", "declaration"));
}
}
if (options.emitDecoratorMetadata &&
!options.experimentalDecorators) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators"));
}
if (options.experimentalAsyncFunctions &&
options.target !== ScriptTarget.ES6) {
diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_experimentalAsyncFunctions_cannot_be_specified_when_targeting_ES5_or_lower));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_experimentalAsyncFunctions_cannot_be_specified_when_targeting_ES5_or_lower));
}
}
}
+6 -1
View File
@@ -6,6 +6,11 @@ namespace ts {
(message: DiagnosticMessage, length: number): void;
}
/* @internal */
export function tokenIsIdentifierOrKeyword(token: SyntaxKind): boolean {
return token >= SyntaxKind.Identifier;
}
export interface Scanner {
getStartPos(): number;
getToken(): SyntaxKind;
@@ -1590,7 +1595,7 @@ namespace ts {
// Scans a JSX identifier; these differ from normal identifiers in that
// they allow dashes
function scanJsxIdentifier(): SyntaxKind {
if (token === SyntaxKind.Identifier) {
if (tokenIsIdentifierOrKeyword(token)) {
let firstCharPosition = pos;
while (pos < end) {
let ch = text.charCodeAt(pos);
+24 -9
View File
@@ -1284,7 +1284,7 @@ namespace ts {
// Stores a mapping 'external module reference text' -> 'resolved file name' | undefined
// It is used to resolve module names in the checker.
// Content of this fiels should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead
/* @internal */ resolvedModules: Map<string>;
/* @internal */ resolvedModules: Map<ResolvedModule>;
/* @internal */ imports: LiteralExpression[];
}
@@ -1359,6 +1359,7 @@ namespace ts {
/* @internal */ getSymbolCount(): number;
/* @internal */ getTypeCount(): number;
/* @internal */ getFileProcessingDiagnostics(): DiagnosticCollection;
// For testing purposes only.
/* @internal */ structureIsReused?: boolean;
}
@@ -1714,6 +1715,7 @@ namespace ts {
resolvedExports?: SymbolTable; // Resolved exports of module
exportsChecked?: boolean; // True if exports of external module have been checked
isNestedRedeclaration?: boolean; // True if symbol is block scoped redeclaration
bindingElement?: BindingElement; // Binding element associated with property symbol
}
/* @internal */
@@ -1811,11 +1813,14 @@ namespace ts {
PropagatingFlags = ContainsUndefinedOrNull | ContainsObjectLiteral | ContainsAnyFunctionType
}
export type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression;
// Properties common to all types
export interface Type {
flags: TypeFlags; // Flags
/* @internal */ id: number; // Unique ID
symbol?: Symbol; // Symbol associated with type (if any)
flags: TypeFlags; // Flags
/* @internal */ id: number; // Unique ID
symbol?: Symbol; // Symbol associated with type (if any)
pattern?: DestructuringPattern; // Destructuring pattern represented by type (if any)
}
/* @internal */
@@ -1864,8 +1869,7 @@ namespace ts {
}
export interface TupleType extends ObjectType {
elementTypes: Type[]; // Element types
baseArrayType: TypeReference; // Array<T> where T is best common type of element types
elementTypes: Type[]; // Element types
}
export interface UnionOrIntersectionType extends Type {
@@ -2269,11 +2273,20 @@ namespace ts {
export interface ResolvedModule {
resolvedFileName: string;
/*
* Denotes if 'resolvedFileName' is isExternalLibraryImport and thus should be proper external module:
* - be a .d.ts file
* - use top level imports\exports
* - don't use tripleslash references
*/
isExternalLibraryImport?: boolean;
}
export interface ResolvedModuleWithFailedLookupLocations {
resolvedModule: ResolvedModule;
failedLookupLocations: string[];
}
export type ModuleNameResolver = (moduleName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost) => ResolvedModule;
export interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
@@ -2291,7 +2304,7 @@ namespace ts {
* If resolveModuleNames is implemented then implementation for members from ModuleResolutionHost can be just
* 'throw new Error("NotImplemented")'
*/
resolveModuleNames?(moduleNames: string[], containingFile: string): string[];
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
}
export interface TextSpan {
@@ -2322,5 +2335,7 @@ namespace ts {
// operation caused diagnostics to be returned by storing and comparing the return value
// of this method before/after the operation is performed.
getModificationCount(): number;
/* @internal */ reattachFileDiagnostics(newFile: SourceFile): void;
}
}
+18 -6
View File
@@ -99,20 +99,20 @@ namespace ts {
return true;
}
export function hasResolvedModuleName(sourceFile: SourceFile, moduleNameText: string): boolean {
export function hasResolvedModule(sourceFile: SourceFile, moduleNameText: string): boolean {
return sourceFile.resolvedModules && hasProperty(sourceFile.resolvedModules, moduleNameText);
}
export function getResolvedModuleFileName(sourceFile: SourceFile, moduleNameText: string): string {
return hasResolvedModuleName(sourceFile, moduleNameText) ? sourceFile.resolvedModules[moduleNameText] : undefined;
export function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModule {
return hasResolvedModule(sourceFile, moduleNameText) ? sourceFile.resolvedModules[moduleNameText] : undefined;
}
export function setResolvedModuleName(sourceFile: SourceFile, moduleNameText: string, resolvedFileName: string): void {
export function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModule): void {
if (!sourceFile.resolvedModules) {
sourceFile.resolvedModules = {};
}
sourceFile.resolvedModules[moduleNameText] = resolvedFileName;
sourceFile.resolvedModules[moduleNameText] = resolvedModule;
}
// Returns true if this node contains a parse error anywhere underneath it.
@@ -435,6 +435,7 @@ namespace ts {
}
export let fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
export let fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
export function isTypeNode(node: Node): boolean {
if (SyntaxKind.FirstTypeNode <= node.kind && node.kind <= SyntaxKind.LastTypeNode) {
@@ -1507,12 +1508,23 @@ namespace ts {
add,
getGlobalDiagnostics,
getDiagnostics,
getModificationCount
getModificationCount,
reattachFileDiagnostics
};
function getModificationCount() {
return modificationCount;
}
function reattachFileDiagnostics(newFile: SourceFile): void {
if (!hasProperty(fileDiagnostics, newFile.fileName)) {
return;
}
for (let diagnostic of fileDiagnostics[newFile.fileName]) {
diagnostic.file = newFile;
}
}
function add(diagnostic: Diagnostic): void {
let diagnostics: Diagnostic[];
+2 -2
View File
@@ -225,8 +225,8 @@ module Harness.LanguageService {
let imports: ts.Map<string> = {};
for (let module of preprocessInfo.importedFiles) {
let resolutionInfo = ts.resolveModuleName(module.fileName, fileName, compilerOptions, moduleResolutionHost);
if (resolutionInfo.resolvedFileName) {
imports[module.fileName] = resolutionInfo.resolvedFileName;
if (resolutionInfo.resolvedModule) {
imports[module.fileName] = resolutionInfo.resolvedModule.resolvedFileName;
}
}
return JSON.stringify(imports);
+7 -7
View File
@@ -79,7 +79,7 @@ namespace ts.server {
}
}
interface TimestampedResolvedModule extends ResolvedModule {
interface TimestampedResolvedModule extends ResolvedModuleWithFailedLookupLocations {
lastCheckTime: number;
}
@@ -99,11 +99,11 @@ namespace ts.server {
}
}
resolveModuleNames(moduleNames: string[], containingFile: string): string[] {
resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[] {
let currentResolutionsInFile = this.resolvedModuleNames.get(containingFile);
let newResolutions: Map<TimestampedResolvedModule> = {};
let resolvedFileNames: string[] = [];
let resolvedModules: ResolvedModule[] = [];
let compilerOptions = this.getCompilationSettings();
@@ -119,25 +119,25 @@ namespace ts.server {
else {
resolution = <TimestampedResolvedModule>resolveModuleName(moduleName, containingFile, compilerOptions, this.moduleResolutionHost);
resolution.lastCheckTime = Date.now();
newResolutions[moduleName] = resolution;
newResolutions[moduleName] = resolution;
}
}
ts.Debug.assert(resolution !== undefined);
resolvedFileNames.push(resolution.resolvedFileName);
resolvedModules.push(resolution.resolvedModule);
}
// replace old results with a new one
this.resolvedModuleNames.set(containingFile, newResolutions);
return resolvedFileNames;
return resolvedModules;
function moduleResolutionIsValid(resolution: TimestampedResolvedModule): boolean {
if (!resolution) {
return false;
}
if (resolution.resolvedFileName) {
if (resolution.resolvedModule) {
// TODO: consider checking failedLookupLocations
// TODO: use lastCheckTime to track expiration for module name resolution
return true;
+7 -41
View File
@@ -213,27 +213,11 @@ namespace ts.formatting {
public NoSpaceBetweenYieldKeywordAndStar: Rule;
public SpaceBetweenYieldOrYieldStarAndOperand: Rule;
// Async-await
// Async functions
public SpaceBetweenAsyncAndFunctionKeyword: Rule;
public NoSpaceBetweenAsyncAndFunctionKeyword: Rule;
public SpaceAfterAwaitKeyword: Rule;
public NoSpaceAfterAwaitKeyword: Rule;
// Type alias declaration
public SpaceAfterTypeKeyword: Rule;
public NoSpaceAfterTypeKeyword: Rule;
// Tagged template string
public SpaceBetweenTagAndTemplateString: Rule;
public NoSpaceBetweenTagAndTemplateString: Rule;
// Type operation
public SpaceBeforeBar: Rule;
public NoSpaceBeforeBar: Rule;
public SpaceAfterBar: Rule;
public NoSpaceAfterBar: Rule;
public SpaceBeforeAmpersand: Rule;
public SpaceAfterAmpersand: Rule;
constructor() {
///
@@ -315,7 +299,7 @@ namespace ts.formatting {
this.NoSpaceBeforeComma = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.CommaToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.SpaceAfterCertainKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.VarKeyword, SyntaxKind.ThrowKeyword, SyntaxKind.NewKeyword, SyntaxKind.DeleteKeyword, SyntaxKind.ReturnKeyword, SyntaxKind.TypeOfKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceAfterCertainKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.VarKeyword, SyntaxKind.ThrowKeyword, SyntaxKind.NewKeyword, SyntaxKind.DeleteKeyword, SyntaxKind.ReturnKeyword, SyntaxKind.TypeOfKeyword, SyntaxKind.AwaitKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceAfterLetConstInVariableDeclaration = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.LetKeyword, SyntaxKind.ConstKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsStartOfVariableDeclarationList), RuleAction.Space));
this.NoSpaceBeforeOpenParenInFuncCall = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext, Rules.IsFunctionCallOrNewContext, Rules.IsPreviousTokenNotComma), RuleAction.Delete));
this.SpaceAfterFunctionInFuncDecl = new Rule(RuleDescriptor.create3(SyntaxKind.FunctionKeyword, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsFunctionDeclContext), RuleAction.Space));
@@ -348,7 +332,7 @@ namespace ts.formatting {
this.NoSpaceAfterModuleImport = new Rule(RuleDescriptor.create2(Shared.TokenRange.FromTokens([SyntaxKind.ModuleKeyword, SyntaxKind.RequireKeyword]), SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
// Add a space around certain TypeScript keywords
this.SpaceAfterCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.AbstractKeyword, SyntaxKind.ClassKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.EnumKeyword, SyntaxKind.ExportKeyword, SyntaxKind.ExtendsKeyword, SyntaxKind.GetKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PublicKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SetKeyword, SyntaxKind.StaticKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceAfterCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.AbstractKeyword, SyntaxKind.ClassKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.EnumKeyword, SyntaxKind.ExportKeyword, SyntaxKind.ExtendsKeyword, SyntaxKind.GetKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PublicKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SetKeyword, SyntaxKind.StaticKeyword, SyntaxKind.TypeKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceBeforeCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.FromTokens([SyntaxKind.ExtendsKeyword, SyntaxKind.ImplementsKeyword])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
// Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" {
@@ -384,25 +368,9 @@ namespace ts.formatting {
// Async-await
this.SpaceBetweenAsyncAndFunctionKeyword = new Rule(RuleDescriptor.create1(SyntaxKind.AsyncKeyword, SyntaxKind.FunctionKeyword), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceBetweenAsyncAndFunctionKeyword = new Rule(RuleDescriptor.create1(SyntaxKind.AsyncKeyword, SyntaxKind.FunctionKeyword), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.SpaceAfterAwaitKeyword = new Rule(RuleDescriptor.create3(SyntaxKind.AwaitKeyword, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceAfterAwaitKeyword = new Rule(RuleDescriptor.create3(SyntaxKind.AwaitKeyword, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
// Type alias declaration
this.SpaceAfterTypeKeyword = new Rule(RuleDescriptor.create3(SyntaxKind.TypeKeyword, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceAfterTypeKeyword = new Rule(RuleDescriptor.create3(SyntaxKind.TypeKeyword, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
// template string
this.SpaceBetweenTagAndTemplateString = new Rule(RuleDescriptor.create3(SyntaxKind.Identifier, Shared.TokenRange.FromTokens([SyntaxKind.NoSubstitutionTemplateLiteral, SyntaxKind.TemplateHead])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceBetweenTagAndTemplateString = new Rule(RuleDescriptor.create3(SyntaxKind.Identifier, Shared.TokenRange.FromTokens([SyntaxKind.NoSubstitutionTemplateLiteral, SyntaxKind.TemplateHead])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
// type operation
this.SpaceBeforeBar = new Rule(RuleDescriptor.create3(SyntaxKind.BarToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceBeforeBar = new Rule(RuleDescriptor.create3(SyntaxKind.BarToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.SpaceAfterBar = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.BarToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.NoSpaceAfterBar = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.BarToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
this.SpaceBeforeAmpersand = new Rule(RuleDescriptor.create3(SyntaxKind.AmpersandToken, Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceAfterAmpersand = new Rule(RuleDescriptor.create2(Shared.TokenRange.Any, SyntaxKind.AmpersandToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
// These rules are higher in priority than user-configurable rules.
this.HighPriorityCommonRules =
@@ -430,12 +398,8 @@ namespace ts.formatting {
this.NoSpaceBeforeOpenParenInFuncCall,
this.SpaceBeforeBinaryKeywordOperator, this.SpaceAfterBinaryKeywordOperator,
this.SpaceAfterVoidOperator,
this.SpaceBetweenAsyncAndFunctionKeyword, this.NoSpaceBetweenAsyncAndFunctionKeyword,
this.SpaceAfterAwaitKeyword, this.NoSpaceAfterAwaitKeyword,
this.SpaceAfterTypeKeyword, this.NoSpaceAfterTypeKeyword,
this.SpaceBetweenTagAndTemplateString, this.NoSpaceBetweenTagAndTemplateString,
this.SpaceBeforeBar, this.NoSpaceBeforeBar, this.SpaceAfterBar, this.NoSpaceAfterBar,
this.SpaceBeforeAmpersand, this.SpaceAfterAmpersand,
this.SpaceBetweenAsyncAndFunctionKeyword,
this.SpaceBetweenTagAndTemplateString,
// TypeScript-specific rules
this.NoSpaceAfterConstructor, this.NoSpaceAfterModuleImport,
@@ -539,6 +503,8 @@ namespace ts.formatting {
case SyntaxKind.ConditionalExpression:
case SyntaxKind.AsExpression:
case SyntaxKind.TypePredicate:
case SyntaxKind.UnionType:
case SyntaxKind.IntersectionType:
return true;
// equals in binding elements: function foo([[x, y] = [1, 2]])
+2 -2
View File
@@ -802,7 +802,7 @@ namespace ts {
public languageVariant: LanguageVariant;
public identifiers: Map<string>;
public nameTable: Map<string>;
public resolvedModules: Map<string>;
public resolvedModules: Map<ResolvedModule>;
public imports: LiteralExpression[];
private namedDeclarations: Map<Declaration[]>;
@@ -1022,7 +1022,7 @@ namespace ts {
* if implementation is omitted then language service will use built-in module resolution logic and get answers to
* host specific questions using 'getScriptSnapshot'.
*/
resolveModuleNames?(moduleNames: string[], containingFile: string): string[];
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
}
//
+10 -3
View File
@@ -273,7 +273,7 @@ namespace ts {
private loggingEnabled = false;
private tracingEnabled = false;
public resolveModuleNames: (moduleName: string[], containingFile: string) => string[];
public resolveModuleNames: (moduleName: string[], containingFile: string) => ResolvedModule[];
constructor(private shimHost: LanguageServiceShimHost) {
// if shimHost is a COM object then property check will become method call with no arguments.
@@ -281,7 +281,10 @@ namespace ts {
if ("getModuleResolutionsForFile" in this.shimHost) {
this.resolveModuleNames = (moduleNames: string[], containingFile: string) => {
let resolutionsInFile = <Map<string>>JSON.parse(this.shimHost.getModuleResolutionsForFile(containingFile));
return map(moduleNames, name => lookUp(resolutionsInFile, name));
return map(moduleNames, name => {
const result = lookUp(resolutionsInFile, name);
return result ? { resolvedFileName: result } : undefined;
});
};
}
}
@@ -942,7 +945,11 @@ namespace ts {
public resolveModuleName(fileName: string, moduleName: string, compilerOptionsJson: string): string {
return this.forwardJSONCall(`resolveModuleName('${fileName}')`, () => {
let compilerOptions = <CompilerOptions>JSON.parse(compilerOptionsJson);
return resolveModuleName(moduleName, normalizeSlashes(fileName), compilerOptions, this.host);
const result = resolveModuleName(moduleName, normalizeSlashes(fileName), compilerOptions, this.host);
return {
resolvedFileName: result.resolvedModule ? result.resolvedModule.resolvedFileName: undefined,
failedLookupLocations: result.failedLookupLocations
};
});
}