Merge branch 'master' into destructuring

This commit is contained in:
Anders Hejlsberg
2014-11-06 15:07:08 -08:00
379 changed files with 19239 additions and 17596 deletions
+61 -18
View File
@@ -5,25 +5,51 @@
module ts {
export function isInstantiated(node: Node): boolean {
export const enum ModuleInstanceState {
NonInstantiated = 0,
Instantiated = 1,
ConstEnumOnly = 2
}
export function getModuleInstanceState(node: Node): ModuleInstanceState {
// A module is uninstantiated if it contains only
// 1. interface declarations
if (node.kind === SyntaxKind.InterfaceDeclaration) {
return false;
return ModuleInstanceState.NonInstantiated;
}
// 2. non - exported import declarations
// 2. const enum declarations don't make module instantiated
else if (node.kind === SyntaxKind.EnumDeclaration && isConstEnumDeclaration(<EnumDeclaration>node)) {
return ModuleInstanceState.ConstEnumOnly;
}
// 3. non - exported import declarations
else if (node.kind === SyntaxKind.ImportDeclaration && !(node.flags & NodeFlags.Export)) {
return false;
return ModuleInstanceState.NonInstantiated;
}
// 3. other uninstantiated module declarations.
else if (node.kind === SyntaxKind.ModuleBlock && !forEachChild(node, isInstantiated)) {
return false;
// 4. other uninstantiated module declarations.
else if (node.kind === SyntaxKind.ModuleBlock) {
var state = ModuleInstanceState.NonInstantiated;
forEachChild(node, n => {
switch (getModuleInstanceState(n)) {
case ModuleInstanceState.NonInstantiated:
// child is non-instantiated - continue searching
return false;
case ModuleInstanceState.ConstEnumOnly:
// child is const enum only - record state and continue searching
state = ModuleInstanceState.ConstEnumOnly;
return false;
case ModuleInstanceState.Instantiated:
// child is instantiated - record state and stop
state = ModuleInstanceState.Instantiated;
return true;
}
});
return state;
}
else if (node.kind === SyntaxKind.ModuleDeclaration && !isInstantiated((<ModuleDeclaration>node).body)) {
return false;
else if (node.kind === SyntaxKind.ModuleDeclaration) {
return getModuleInstanceState((<ModuleDeclaration>node).body);
}
else {
return true;
return ModuleInstanceState.Instantiated;
}
}
@@ -58,12 +84,13 @@ module ts {
if (symbolKind & SymbolFlags.Value && !symbol.valueDeclaration) symbol.valueDeclaration = node;
}
// TODO(jfreeman): Implement getDeclarationName for property name
function getDeclarationName(node: Declaration): string {
if (node.name) {
if (node.kind === SyntaxKind.ModuleDeclaration && node.name.kind === SyntaxKind.StringLiteral) {
return '"' + node.name.text + '"';
return '"' + (<LiteralExpression>node.name).text + '"';
}
return node.name.text;
return (<Identifier>node.name).text;
}
switch (node.kind) {
case SyntaxKind.Constructor: return "__constructor";
@@ -74,7 +101,7 @@ module ts {
}
function getDisplayName(node: Declaration): string {
return node.name ? identifierToString(node.name) : getDeclarationName(node);
return node.name ? declarationNameToString(node.name) : getDeclarationName(node);
}
function declareSymbol(symbols: SymbolTable, parent: Symbol, node: Declaration, includes: SymbolFlags, excludes: SymbolFlags): Symbol {
@@ -248,11 +275,22 @@ module ts {
if (node.name.kind === SyntaxKind.StringLiteral) {
bindDeclaration(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes, /*isBlockScopeContainer*/ true);
}
else if (isInstantiated(node)) {
bindDeclaration(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes, /*isBlockScopeContainer*/ true);
}
else {
bindDeclaration(node, SymbolFlags.NamespaceModule, SymbolFlags.NamespaceModuleExcludes, /*isBlockScopeContainer*/ true);
var state = getModuleInstanceState(node);
if (state === ModuleInstanceState.NonInstantiated) {
bindDeclaration(node, SymbolFlags.NamespaceModule, SymbolFlags.NamespaceModuleExcludes, /*isBlockScopeContainer*/ true);
}
else {
bindDeclaration(node, SymbolFlags.ValueModule, SymbolFlags.ValueModuleExcludes, /*isBlockScopeContainer*/ true);
if (state === ModuleInstanceState.ConstEnumOnly) {
// mark value module as module that contains only enums
node.symbol.constEnumOnlyModule = true;
}
else if (node.symbol.constEnumOnlyModule) {
// const only value module was merged with instantiated module - reset flag
node.symbol.constEnumOnlyModule = false;
}
}
}
}
@@ -369,7 +407,12 @@ module ts {
bindDeclaration(<Declaration>node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes, /*isBlockScopeContainer*/ false);
break;
case SyntaxKind.EnumDeclaration:
bindDeclaration(<Declaration>node, SymbolFlags.Enum, SymbolFlags.EnumExcludes, /*isBlockScopeContainer*/ false);
if (isConstEnumDeclaration(<EnumDeclaration>node)) {
bindDeclaration(<Declaration>node, SymbolFlags.ConstEnum, SymbolFlags.ConstEnumExcludes, /*isBlockScopeContainer*/ false);
}
else {
bindDeclaration(<Declaration>node, SymbolFlags.RegularEnum, SymbolFlags.RegularEnumExcludes, /*isBlockScopeContainer*/ false);
}
break;
case SyntaxKind.ModuleDeclaration:
bindModuleDeclaration(<ModuleDeclaration>node);
+307 -130
View File
@@ -186,7 +186,8 @@ module ts {
if (flags & SymbolFlags.Function) result |= SymbolFlags.FunctionExcludes;
if (flags & SymbolFlags.Class) result |= SymbolFlags.ClassExcludes;
if (flags & SymbolFlags.Interface) result |= SymbolFlags.InterfaceExcludes;
if (flags & SymbolFlags.Enum) result |= SymbolFlags.EnumExcludes;
if (flags & SymbolFlags.RegularEnum) result |= SymbolFlags.RegularEnumExcludes;
if (flags & SymbolFlags.ConstEnum) result |= SymbolFlags.ConstEnumExcludes;
if (flags & SymbolFlags.ValueModule) result |= SymbolFlags.ValueModuleExcludes;
if (flags & SymbolFlags.Method) result |= SymbolFlags.MethodExcludes;
if (flags & SymbolFlags.GetAccessor) result |= SymbolFlags.GetAccessorExcludes;
@@ -207,6 +208,7 @@ module ts {
result.declarations = symbol.declarations.slice(0);
result.parent = symbol.parent;
if (symbol.valueDeclaration) result.valueDeclaration = symbol.valueDeclaration;
if (symbol.constEnumOnlyModule) result.constEnumOnlyModule = true;
if (symbol.members) result.members = cloneSymbolTable(symbol.members);
if (symbol.exports) result.exports = cloneSymbolTable(symbol.exports);
recordMergedSymbol(result, symbol);
@@ -215,6 +217,10 @@ module ts {
function extendSymbol(target: Symbol, source: Symbol) {
if (!(target.flags & getExcludedSymbolFlags(source.flags))) {
if (source.flags & SymbolFlags.ValueModule && target.flags & SymbolFlags.ValueModule && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
// reset flag when merging instantiated module into value module that has only const enums
target.constEnumOnlyModule = false;
}
target.flags |= source.flags;
if (!target.valueDeclaration && source.valueDeclaration) target.valueDeclaration = source.valueDeclaration;
forEach(source.declarations, node => {
@@ -309,6 +315,22 @@ module ts {
// return undefined if we can't find a symbol.
}
/** Returns true if node1 is defined before node 2**/
function isDefinedBefore(node1: Node, node2: Node): boolean {
var file1 = getSourceFileOfNode(node1);
var file2 = getSourceFileOfNode(node2);
if (file1 === file2) {
return node1.pos <= node2.pos;
}
if (!compilerOptions.out) {
return true;
}
var sourceFiles = program.getSourceFiles();
return sourceFiles.indexOf(file1) <= sourceFiles.indexOf(file2);
}
// Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
// the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with
// the given name can be found.
@@ -409,7 +431,7 @@ module ts {
if (!result) {
if (nameNotFoundMessage) {
error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : identifierToString(nameArg));
error(errorLocation, nameNotFoundMessage, typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg));
}
return undefined;
}
@@ -421,25 +443,15 @@ module ts {
// to a local variable in the constructor where the code will be emitted.
var propertyName = (<PropertyDeclaration>propertyWithInvalidInitializer).name;
error(errorLocation, Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor,
identifierToString(propertyName), typeof nameArg === "string" ? nameArg : identifierToString(nameArg));
declarationNameToString(propertyName), typeof nameArg === "string" ? nameArg : declarationNameToString(nameArg));
return undefined;
}
if (result.flags & SymbolFlags.BlockScopedVariable) {
// Block-scoped variables cannot be used before their definition
var declaration = forEach(result.declarations, d => d.flags & NodeFlags.BlockScoped ? d : undefined);
Debug.assert(declaration !== undefined, "Block-scoped variable declaration is undefined");
var declarationSourceFile = getSourceFileOfNode(declaration);
var referenceSourceFile = getSourceFileOfNode(errorLocation);
if (declarationSourceFile === referenceSourceFile) {
if (declaration.pos > errorLocation.pos) {
error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, identifierToString(declaration.name));
}
}
else if (compilerOptions.out) {
var sourceFiles = program.getSourceFiles();
if (sourceFiles.indexOf(referenceSourceFile) < sourceFiles.indexOf(declarationSourceFile)) {
error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, identifierToString(declaration.name));
}
if (!isDefinedBefore(declaration, errorLocation)) {
error(errorLocation, Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationNameToString(declaration.name));
}
}
}
@@ -471,7 +483,7 @@ module ts {
// This function is only for imports with entity names
function getSymbolOfPartOfRightHandSideOfImport(entityName: EntityName, importDeclaration?: ImportDeclaration): Symbol {
if (!importDeclaration) {
importDeclaration = getAncestor(entityName, SyntaxKind.ImportDeclaration);
importDeclaration = <ImportDeclaration>getAncestor(entityName, SyntaxKind.ImportDeclaration);
Debug.assert(importDeclaration !== undefined);
}
// There are three things we might try to look for. In the following examples,
@@ -513,7 +525,7 @@ module ts {
var symbol = getSymbol(namespace.exports, (<QualifiedName>name).right.text, meaning);
if (!symbol) {
error(location, Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(namespace),
identifierToString((<QualifiedName>name).right));
declarationNameToString((<QualifiedName>name).right));
return;
}
}
@@ -951,11 +963,11 @@ module ts {
getNodeLinks(declaration).isVisible = true;
if (aliasesToMakeVisible) {
if (!contains(aliasesToMakeVisible, declaration)) {
aliasesToMakeVisible.push(declaration);
aliasesToMakeVisible.push(<ImportDeclaration>declaration);
}
}
else {
aliasesToMakeVisible = [declaration];
aliasesToMakeVisible = [<ImportDeclaration>declaration];
}
return true;
}
@@ -975,7 +987,7 @@ module ts {
var hasNamespaceDeclarationsVisibile = hasVisibleDeclarations(symbolOfNameSpace);
return hasNamespaceDeclarationsVisibile ?
{ accessibility: SymbolAccessibility.Accessible, aliasesToMakeVisible: hasNamespaceDeclarationsVisibile.aliasesToMakeVisible } :
{ accessibility: SymbolAccessibility.NotAccessible, errorSymbolName: identifierToString(<Identifier>firstIdentifier) };
{ accessibility: SymbolAccessibility.NotAccessible, errorSymbolName: declarationNameToString(<Identifier>firstIdentifier) };
}
function releaseStringWriter(writer: StringSymbolWriter) {
@@ -1048,7 +1060,7 @@ module ts {
if (symbol.declarations && symbol.declarations.length > 0) {
var declaration = symbol.declarations[0];
if (declaration.name) {
writer.writeSymbol(identifierToString(declaration.name), symbol);
writer.writeSymbol(declarationNameToString(declaration.name), symbol);
return;
}
}
@@ -1594,7 +1606,7 @@ module ts {
return true;
default:
Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + SyntaxKind[node.kind]);
Debug.fail("isDeclarationVisible unknown: SyntaxKind: " + node.kind);
}
}
@@ -1616,7 +1628,7 @@ module ts {
return classType.typeParameters ? createTypeReference(<GenericType>classType, map(classType.typeParameters, _ => anyType)) : classType;
}
function getTypeOfVariableDeclaration(declaration: VariableDeclaration): Type {
function getTypeOfVariableOrPropertyDeclaration(declaration: VariableDeclaration | PropertyDeclaration): Type {
// A variable declared in a for..in statement is always of type any
if (declaration.parent.kind === SyntaxKind.ForInStatement) {
return anyType;
@@ -1626,7 +1638,7 @@ module ts {
return getTypeFromTypeNode(declaration.type);
}
if (declaration.kind === SyntaxKind.Parameter) {
var func = <FunctionDeclaration>declaration.parent;
var func = <FunctionLikeDeclaration>declaration.parent;
// For a parameter of a set accessor, use the type of the get accessor if one is present
if (func.kind === SyntaxKind.SetAccessor) {
var getter = <AccessorDeclaration>getDeclarationOfKind(declaration.parent.symbol, SyntaxKind.GetAccessor);
@@ -1635,7 +1647,7 @@ module ts {
}
}
// Use contextual parameter type if one is available
var type = getContextuallyTypedParameterType(declaration);
var type = getContextuallyTypedParameterType(<ParameterDeclaration>declaration);
if (type) {
return type;
}
@@ -1672,7 +1684,7 @@ module ts {
}
// Handle variable, parameter or property
links.type = resolvingType;
var type = getTypeOfVariableDeclaration(<VariableDeclaration>declaration);
var type = getTypeOfVariableOrPropertyDeclaration(<VariableDeclaration>declaration);
if (links.type === resolvingType) {
links.type = type;
}
@@ -2465,7 +2477,7 @@ module ts {
returnType = getAnnotatedAccessorType(setter);
}
if (!returnType && !(<FunctionDeclaration>declaration).body) {
if (!returnType && !(<FunctionLikeDeclaration>declaration).body) {
returnType = anyType;
}
}
@@ -2495,7 +2507,7 @@ module ts {
// Don't include signature if node is the implementation of an overloaded function. A node is considered
// an implementation node if it has a body and the previous node is of the same kind and immediately
// precedes the implementation node (i.e. has the same parent and ends where the implementation starts).
if (i > 0 && (<FunctionDeclaration>node).body) {
if (i > 0 && (<FunctionLikeDeclaration>node).body) {
var previous = symbol.declarations[i - 1];
if (node.parent === previous.parent && node.kind === previous.kind && node.pos === previous.end) {
break;
@@ -2517,7 +2529,7 @@ module ts {
var type = getUnionType(map(signature.unionSignatures, getReturnTypeOfSignature));
}
else {
var type = getReturnTypeFromBody(<FunctionDeclaration>signature.declaration);
var type = getReturnTypeFromBody(<FunctionLikeDeclaration>signature.declaration);
}
if (signature.resolvedReturnType === resolvingType) {
signature.resolvedReturnType = type;
@@ -2528,7 +2540,7 @@ module ts {
if (compilerOptions.noImplicitAny) {
var declaration = <Declaration>signature.declaration;
if (declaration.name) {
error(declaration.name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, identifierToString(declaration.name));
error(declaration.name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(declaration.name));
}
else {
error(declaration, Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions);
@@ -4002,8 +4014,10 @@ module ts {
}
function createInferenceContext(typeParameters: TypeParameter[], inferUnionTypes: boolean): InferenceContext {
var inferences: Type[][] = [];
for (var i = 0; i < typeParameters.length; i++) inferences.push([]);
var inferences: TypeInferences[] = [];
for (var i = 0; i < typeParameters.length; i++) {
inferences.push({ primary: undefined, secondary: undefined });
}
return {
typeParameters: typeParameters,
inferUnionTypes: inferUnionTypes,
@@ -4017,6 +4031,7 @@ module ts {
var sourceStack: Type[];
var targetStack: Type[];
var depth = 0;
var inferiority = 0;
inferFromTypes(source, target);
function isInProcess(source: Type, target: Type) {
@@ -4045,9 +4060,11 @@ module ts {
var typeParameters = context.typeParameters;
for (var i = 0; i < typeParameters.length; i++) {
if (target === typeParameters[i]) {
context.inferenceCount++;
var inferences = context.inferences[i];
if (!contains(inferences, source)) inferences.push(source);
var candidates = inferiority ?
inferences.secondary || (inferences.secondary = []) :
inferences.primary || (inferences.primary = []);
if (!contains(candidates, source)) candidates.push(source);
break;
}
}
@@ -4062,7 +4079,6 @@ module ts {
}
else if (target.flags & TypeFlags.Union) {
var targetTypes = (<UnionType>target).types;
var startCount = context.inferenceCount;
var typeParameterCount = 0;
var typeParameter: TypeParameter;
// First infer to each type in union that isn't a type parameter
@@ -4076,9 +4092,11 @@ module ts {
inferFromTypes(source, t);
}
}
// If no inferences were produced above and union contains a single naked type parameter, infer to that type parameter
if (context.inferenceCount === startCount && typeParameterCount === 1) {
// If union contains a single naked type parameter, make a secondary inference to that type parameter
if (typeParameterCount === 1) {
inferiority++;
inferFromTypes(source, typeParameter);
inferiority--;
}
}
else if (source.flags & TypeFlags.Union) {
@@ -4148,10 +4166,15 @@ module ts {
}
}
function getInferenceCandidates(context: InferenceContext, index: number): Type[]{
var inferences = context.inferences[index];
return inferences.primary || inferences.secondary || emptyArray;
}
function getInferredType(context: InferenceContext, index: number): Type {
var inferredType = context.inferredTypes[index];
if (!inferredType) {
var inferences = context.inferences[index];
var inferences = getInferenceCandidates(context, index);
if (inferences.length) {
// Infer widened union or supertype, or the undefined type for no common supertype
var unionOrSuperType = context.inferUnionTypes ? getUnionType(inferences) : getCommonSupertype(inferences);
@@ -4161,7 +4184,6 @@ module ts {
// Infer the empty object type when no inferences were made
inferredType = emptyObjectType;
}
if (inferredType !== inferenceFailureType) {
var constraint = getConstraintOfTypeParameter(context.typeParameters[index]);
inferredType = constraint && !isTypeAssignableTo(inferredType, constraint) ? constraint : inferredType;
@@ -4461,8 +4483,8 @@ module ts {
if (symbol.flags & SymbolFlags.Import) {
// Mark the import as referenced so that we emit it in the final .js file.
// exception: identifiers that appear in type queries
getSymbolLinks(symbol).referenced = !isInTypeQuery(node);
// exception: identifiers that appear in type queries, const enums, modules that contain only const enums
getSymbolLinks(symbol).referenced = !isInTypeQuery(node) && !isConstEnumOrConstEnumOnlyModule(resolveImport(symbol));
}
checkCollisionWithCapturedSuperVariable(node, node);
@@ -4653,7 +4675,7 @@ module ts {
// Return contextual type of parameter or undefined if no contextual type is available
function getContextuallyTypedParameterType(parameter: ParameterDeclaration): Type {
var func = <FunctionDeclaration>parameter.parent;
var func = <FunctionLikeDeclaration>parameter.parent;
if (func.kind === SyntaxKind.FunctionExpression || func.kind === SyntaxKind.ArrowFunction) {
if (isContextSensitiveExpression(func)) {
var contextualSignature = getContextualSignature(func);
@@ -4799,7 +4821,8 @@ module ts {
var declaration = <PropertyDeclaration>node.parent;
var objectLiteral = <ObjectLiteral>declaration.parent;
var type = getContextualType(objectLiteral);
var name = declaration.name.text;
// TODO(jfreeman): Handle this case for computed names and symbols
var name = (<Identifier>declaration.name).text;
if (type && name) {
return getTypeOfPropertyOfContextualType(type, name) ||
isNumericName(name) && getIndexTypeOfContextualType(type, IndexKind.Number) ||
@@ -5070,7 +5093,7 @@ module ts {
var prop = getPropertyOfType(apparentType, node.right.text);
if (!prop) {
if (node.right.text) {
error(node.right, Diagnostics.Property_0_does_not_exist_on_type_1, identifierToString(node.right), typeToString(type));
error(node.right, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(node.right), typeToString(type));
}
return unknownType;
}
@@ -5120,6 +5143,10 @@ module ts {
if (objectType === unknownType) return unknownType;
if (isConstEnumObjectType(objectType) && node.index.kind !== SyntaxKind.StringLiteral) {
error(node.index, Diagnostics.Index_expression_arguments_in_const_enums_must_be_of_type_string);
}
// TypeScript 1.0 spec (April 2014): 4.10 Property Access
// - If IndexExpr is a string literal or a numeric literal and ObjExpr's apparent type has a property with the name
// given by that literal(converted to its string representation in the case of a numeric literal), the property access is of the type of that property.
@@ -5134,6 +5161,7 @@ module ts {
var name = (<LiteralExpression>node.index).text;
var prop = getPropertyOfType(objectType, name);
if (prop) {
getNodeLinks(node).resolvedSymbol = prop;
return getTypeOfSymbol(prop);
}
}
@@ -5401,7 +5429,7 @@ module ts {
else {
Debug.assert(resultOfFailedInference.failedTypeParameterIndex >= 0);
var failedTypeParameter = candidateForTypeArgumentError.typeParameters[resultOfFailedInference.failedTypeParameterIndex];
var inferenceCandidates = resultOfFailedInference.inferences[resultOfFailedInference.failedTypeParameterIndex];
var inferenceCandidates = getInferenceCandidates(resultOfFailedInference, resultOfFailedInference.failedTypeParameterIndex);
var diagnosticChainHead = chainDiagnosticMessages(/*details*/ undefined, // details will be provided by call to reportNoCommonSupertypeError
Diagnostics.The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly,
@@ -5712,7 +5740,7 @@ module ts {
}
}
function getReturnTypeFromBody(func: FunctionDeclaration, contextualMapper?: TypeMapper): Type {
function getReturnTypeFromBody(func: FunctionLikeDeclaration, contextualMapper?: TypeMapper): Type {
var contextualSignature = getContextualSignature(func);
if (func.body.kind !== SyntaxKind.FunctionBlock) {
var type = checkAndMarkExpression(func.body, contextualMapper);
@@ -5768,7 +5796,7 @@ module ts {
// An explicitly typed function whose return type isn't the Void or the Any type
// must have at least one return statement somewhere in its body.
// An exception to this rule is if the function implementation consists of a single 'throw' statement.
function checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(func: FunctionDeclaration, returnType: Type): void {
function checkIfNonVoidFunctionHasReturnExpressionsOrSingleThrowStatment(func: FunctionLikeDeclaration, returnType: Type): void {
if (!fullTypeCheck) {
return;
}
@@ -5979,6 +6007,14 @@ module ts {
return (type.flags & TypeFlags.Structured) !== 0;
}
function isConstEnumObjectType(type: Type) : boolean {
return type.flags & (TypeFlags.ObjectType | TypeFlags.Anonymous) && type.symbol && isConstEnumSymbol(type.symbol);
}
function isConstEnumSymbol(symbol: Symbol): boolean {
return (symbol.flags & SymbolFlags.ConstEnum) !== 0;
}
function checkInstanceOfExpression(node: BinaryExpression, leftType: Type, rightType: Type): Type {
// TypeScript 1.0 spec (April 2014): 4.15.4
// The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type,
@@ -6216,6 +6252,21 @@ module ts {
}
}
}
if (isConstEnumObjectType(type)) {
// enum object type for const enums are only permitted in:
// - 'left' in property access
// - 'object' in indexed access
// - target in rhs of import statement
var ok =
(node.parent.kind === SyntaxKind.PropertyAccess && (<PropertyAccess>node.parent).left === node) ||
(node.parent.kind === SyntaxKind.IndexedAccess && (<IndexedAccess>node.parent).object === node) ||
((node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.QualifiedName) && isInRightSideOfImportOrExportAssignment(<EntityName>node));
if (!ok) {
error(node, Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment);
}
}
return type;
}
@@ -6304,7 +6355,7 @@ module ts {
}
}
else {
if (parameterDeclaration.initializer && !(<FunctionDeclaration>parameterDeclaration.parent).body) {
if (parameterDeclaration.initializer && !(<FunctionLikeDeclaration>parameterDeclaration.parent).body) {
error(parameterDeclaration, Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
}
}
@@ -6313,16 +6364,16 @@ module ts {
function checkReferencesInInitializer(n: Node): void {
if (n.kind === SyntaxKind.Identifier) {
var referencedSymbol = getNodeLinks(n).resolvedSymbol;
// check FunctionDeclaration.locals (stores parameters\function local variable)
// check FunctionLikeDeclaration.locals (stores parameters\function local variable)
// if it contains entry with a specified name and if this entry matches the resolved symbol
if (referencedSymbol && referencedSymbol !== unknownSymbol && getSymbol(parameterDeclaration.parent.locals, referencedSymbol.name, SymbolFlags.Value) === referencedSymbol) {
if (referencedSymbol.valueDeclaration.kind === SyntaxKind.Parameter) {
if (referencedSymbol.valueDeclaration === parameterDeclaration) {
error(n, Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, identifierToString(parameterDeclaration.name));
error(n, Diagnostics.Parameter_0_cannot_be_referenced_in_its_initializer, declarationNameToString(parameterDeclaration.name));
return;
}
var enclosingOrReferencedParameter =
forEach((<FunctionDeclaration>parameterDeclaration.parent).parameters, p => p === parameterDeclaration || p === referencedSymbol.valueDeclaration ? p : undefined);
forEach((<FunctionLikeDeclaration>parameterDeclaration.parent).parameters, p => p === parameterDeclaration || p === referencedSymbol.valueDeclaration ? p : undefined);
if (enclosingOrReferencedParameter === referencedSymbol.valueDeclaration) {
// legal case - parameter initializer references some parameter strictly on left of current parameter declaration
@@ -6331,7 +6382,7 @@ module ts {
// fall through to error reporting
}
error(n, Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, identifierToString(parameterDeclaration.name), identifierToString(<Identifier>n));
error(n, Diagnostics.Initializer_of_parameter_0_cannot_reference_identifier_1_declared_after_it, declarationNameToString(parameterDeclaration.name), declarationNameToString(<Identifier>n));
}
}
else {
@@ -6596,7 +6647,7 @@ module ts {
// TypeScript 1.0 spec (April 2014): 3.7.2.2
// Specialized signatures are not permitted in conjunction with a function body
if ((<FunctionDeclaration>signatureDeclarationNode).body) {
if ((<FunctionLikeDeclaration>signatureDeclarationNode).body) {
error(signatureDeclarationNode, Diagnostics.A_signature_with_an_implementation_cannot_use_a_string_literal_type);
return;
}
@@ -6647,7 +6698,7 @@ module ts {
return;
}
function checkFlagAgreementBetweenOverloads(overloads: Declaration[], implementation: FunctionDeclaration, flagsToCheck: NodeFlags, someOverloadFlags: NodeFlags, allOverloadFlags: NodeFlags): void {
function checkFlagAgreementBetweenOverloads(overloads: Declaration[], implementation: FunctionLikeDeclaration, flagsToCheck: NodeFlags, someOverloadFlags: NodeFlags, allOverloadFlags: NodeFlags): void {
// Error if some overloads have a flag that is not shared by all overloads. To find the
// deviations, we XOR someOverloadFlags with allOverloadFlags
var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
@@ -6683,14 +6734,14 @@ module ts {
var someNodeFlags: NodeFlags = 0;
var allNodeFlags = flagsToCheck;
var hasOverloads = false;
var bodyDeclaration: FunctionDeclaration;
var lastSeenNonAmbientDeclaration: FunctionDeclaration;
var previousDeclaration: FunctionDeclaration;
var bodyDeclaration: FunctionLikeDeclaration;
var lastSeenNonAmbientDeclaration: FunctionLikeDeclaration;
var previousDeclaration: FunctionLikeDeclaration;
var declarations = symbol.declarations;
var isConstructor = (symbol.flags & SymbolFlags.Constructor) !== 0;
function reportImplementationExpectedError(node: FunctionDeclaration): void {
function reportImplementationExpectedError(node: FunctionLikeDeclaration): void {
if (node.name && node.name.kind === SyntaxKind.Missing) {
return;
}
@@ -6706,8 +6757,9 @@ module ts {
});
if (subsequentNode) {
if (subsequentNode.kind === node.kind) {
var errorNode: Node = (<FunctionDeclaration>subsequentNode).name || subsequentNode;
if (node.name && (<FunctionDeclaration>subsequentNode).name && node.name.text === (<FunctionDeclaration>subsequentNode).name.text) {
var errorNode: Node = (<FunctionLikeDeclaration>subsequentNode).name || subsequentNode;
// TODO(jfreeman): These are methods, so handle computed name case
if (node.name && (<FunctionLikeDeclaration>subsequentNode).name && (<Identifier>node.name).text === (<Identifier>(<FunctionLikeDeclaration>subsequentNode).name).text) {
// the only situation when this is possible (same kind\same name but different symbol) - mixed static and instance class members
Debug.assert(node.kind === SyntaxKind.Method);
Debug.assert((node.flags & NodeFlags.Static) !== (subsequentNode.flags & NodeFlags.Static));
@@ -6715,8 +6767,8 @@ module ts {
error(errorNode, diagnostic);
return;
}
else if ((<FunctionDeclaration>subsequentNode).body) {
error(errorNode, Diagnostics.Function_implementation_name_must_be_0, identifierToString(node.name));
else if ((<FunctionLikeDeclaration>subsequentNode).body) {
error(errorNode, Diagnostics.Function_implementation_name_must_be_0, declarationNameToString(node.name));
return;
}
}
@@ -6736,7 +6788,7 @@ module ts {
var duplicateFunctionDeclaration = false;
var multipleConstructorImplementation = false;
for (var i = 0; i < declarations.length; i++) {
var node = <FunctionDeclaration>declarations[i];
var node = <FunctionLikeDeclaration>declarations[i];
var inAmbientContext = isInAmbientContext(node);
var inAmbientContextOrInterface = node.parent.kind === SyntaxKind.InterfaceDeclaration || node.parent.kind === SyntaxKind.TypeLiteral || inAmbientContext;
if (inAmbientContextOrInterface) {
@@ -6880,7 +6932,7 @@ module ts {
// declaration spaces for exported and non-exported declarations intersect
forEach(symbol.declarations, d => {
if (getDeclarationSpaces(d) & commonDeclarationSpace) {
error(d.name, Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, identifierToString(d.name));
error(d.name, Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, declarationNameToString(d.name));
}
});
}
@@ -6890,7 +6942,7 @@ module ts {
case SyntaxKind.InterfaceDeclaration:
return SymbolFlags.ExportType;
case SyntaxKind.ModuleDeclaration:
return (<ModuleDeclaration>d).name.kind === SyntaxKind.StringLiteral || isInstantiated(d)
return (<ModuleDeclaration>d).name.kind === SyntaxKind.StringLiteral || getModuleInstanceState(d) !== ModuleInstanceState.NonInstantiated
? SymbolFlags.ExportNamespace | SymbolFlags.ExportValue
: SymbolFlags.ExportNamespace;
case SyntaxKind.ClassDeclaration:
@@ -6907,7 +6959,7 @@ module ts {
}
}
function checkFunctionDeclaration(node: FunctionDeclaration): void {
function checkFunctionDeclaration(node: FunctionLikeDeclaration): void {
checkSignatureDeclaration(node);
var symbol = getSymbolOfNode(node);
@@ -6948,7 +7000,7 @@ module ts {
function checkCollisionWithArgumentsInGeneratedCode(node: SignatureDeclaration) {
// no rest parameters \ declaration context \ overload - no codegen impact
if (!hasRestParameters(node) || isInAmbientContext(node) || !(<FunctionDeclaration>node).body) {
if (!hasRestParameters(node) || isInAmbientContext(node) || !(<FunctionLikeDeclaration>node).body) {
return;
}
@@ -6969,7 +7021,7 @@ module ts {
// - function has implementation (not a signature)
// - function has rest parameters
// - context is not ambient (otherwise no codegen impact)
if ((<FunctionDeclaration>node.parent).body && hasRestParameters(<FunctionDeclaration>node.parent) && !isInAmbientContext(node)) {
if ((<FunctionLikeDeclaration>node.parent).body && hasRestParameters(<FunctionLikeDeclaration>node.parent) && !isInAmbientContext(node)) {
error(node, Diagnostics.Duplicate_identifier_i_Compiler_uses_i_to_initialize_rest_parameter);
}
return;
@@ -7027,7 +7079,7 @@ module ts {
case SyntaxKind.Method:
case SyntaxKind.ArrowFunction:
case SyntaxKind.Constructor:
if (hasRestParameters(<FunctionDeclaration>current)) {
if (hasRestParameters(<FunctionLikeDeclaration>current)) {
error(node, Diagnostics.Expression_resolves_to_variable_declaration_i_that_compiler_uses_to_initialize_rest_parameter);
return;
}
@@ -7037,8 +7089,9 @@ module ts {
}
}
function needCollisionCheckForIdentifier(node: Node, identifier: Identifier, name: string): boolean {
if (!(identifier && identifier.text === name)) {
// TODO(jfreeman): Decide what to do for computed properties
function needCollisionCheckForIdentifier(node: Node, identifier: DeclarationName, name: string): boolean {
if (!(identifier && (<Identifier>identifier).text === name)) {
return false;
}
@@ -7055,15 +7108,16 @@ module ts {
return false;
}
if (node.kind === SyntaxKind.Parameter && !(<FunctionDeclaration>node.parent).body) {
if (node.kind === SyntaxKind.Parameter && !(<FunctionLikeDeclaration>node.parent).body) {
// just an overload - no codegen impact
return false;
}
return true;
}
function checkCollisionWithCapturedThisVariable(node: Node, name: Identifier): void {
// TODO(jfreeman): Decide what to do for computed properties
function checkCollisionWithCapturedThisVariable(node: Node, name: DeclarationName): void {
if (!needCollisionCheckForIdentifier(node, name, "_this")) {
return;
}
@@ -7088,7 +7142,7 @@ module ts {
}
}
function checkCollisionWithCapturedSuperVariable(node: Node, name: Identifier) {
function checkCollisionWithCapturedSuperVariable(node: Node, name: DeclarationName) {
if (!needCollisionCheckForIdentifier(node, name, "_super")) {
return;
}
@@ -7111,13 +7165,14 @@ module ts {
}
}
function checkCollisionWithRequireExportsInGeneratedCode(node: Node, name: Identifier) {
// TODO(jfreeman): Decide what to do for computed properties
function checkCollisionWithRequireExportsInGeneratedCode(node: Node, name: DeclarationName) {
if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
return;
}
// Uninstantiated modules shouldnt do this check
if (node.kind === SyntaxKind.ModuleDeclaration && !isInstantiated(node)) {
if (node.kind === SyntaxKind.ModuleDeclaration && getModuleInstanceState(node) !== ModuleInstanceState.Instantiated) {
return;
}
@@ -7125,7 +7180,8 @@ module ts {
var parent = node.kind === SyntaxKind.VariableDeclaration ? node.parent.parent : node.parent;
if (parent.kind === SyntaxKind.SourceFile && isExternalModule(<SourceFile>parent)) {
// If the declaration happens to be in external module, report error that require and exports are reserved keywords
error(name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_an_external_module, name.text, name.text);
error(name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_an_external_module,
declarationNameToString(name), declarationNameToString(name));
}
}
@@ -7161,7 +7217,7 @@ module ts {
}
}
function checkVariableDeclaration(node: VariableDeclaration) {
function checkVariableDeclaration(node: VariableDeclaration | PropertyDeclaration) {
checkSourceElement(node.type);
checkExportsOnMergedDeclarations(node);
@@ -7175,7 +7231,7 @@ module ts {
type = typeOfValueDeclaration;
}
else {
type = getTypeOfVariableDeclaration(node);
type = getTypeOfVariableOrPropertyDeclaration(node);
}
@@ -7184,7 +7240,8 @@ module ts {
// Use default messages
checkTypeAssignableTo(checkAndMarkExpression(node.initializer), type, node, /*headMessage*/ undefined);
}
checkCollisionWithConstDeclarations(node);
//TODO(jfreeman): Check that it is not a computed property
checkCollisionWithConstDeclarations(<VariableDeclaration>node);
}
checkCollisionWithCapturedSuperVariable(node, node.name);
@@ -7195,7 +7252,7 @@ module ts {
// Multiple declarations for the same variable name in the same declaration space are permitted,
// provided that each declaration associates the same type with the variable.
if (typeOfValueDeclaration !== unknownType && type !== unknownType && !isTypeIdenticalTo(typeOfValueDeclaration, type)) {
error(node.name, Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, identifierToString(node.name), typeToString(typeOfValueDeclaration), typeToString(type));
error(node.name, Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, declarationNameToString(node.name), typeToString(typeOfValueDeclaration), typeToString(type));
}
}
}
@@ -7413,16 +7470,17 @@ module ts {
}
}
function checkTypeNameIsReserved(name: Identifier, message: DiagnosticMessage): void {
// TODO(jfreeman): Decide what to do for computed properties
function checkTypeNameIsReserved(name: DeclarationName, message: DiagnosticMessage): void {
// TS 1.0 spec (April 2014): 3.6.1
// The predefined type keywords are reserved and cannot be used as names of user defined types.
switch (name.text) {
switch ((<Identifier>name).text) {
case "any":
case "number":
case "boolean":
case "string":
case "void":
error(name, message, name.text);
error(name, message, (<Identifier>name).text);
}
}
@@ -7436,7 +7494,7 @@ module ts {
if (fullTypeCheck) {
for (var j = 0; j < i; j++) {
if (typeParameterDeclarations[j].symbol === node.symbol) {
error(node.name, Diagnostics.Duplicate_identifier_0, identifierToString(node.name));
error(node.name, Diagnostics.Duplicate_identifier_0, declarationNameToString(node.name));
}
}
}
@@ -7683,23 +7741,6 @@ module ts {
checkSourceElement(node.type);
}
function getConstantValueForExpression(node: Expression): number {
var isNegative = false;
if (node.kind === SyntaxKind.PrefixOperator) {
var unaryExpression = <UnaryExpression>node;
if (unaryExpression.operator === SyntaxKind.MinusToken || unaryExpression.operator === SyntaxKind.PlusToken) {
node = unaryExpression.operand;
isNegative = unaryExpression.operator === SyntaxKind.MinusToken;
}
}
if (node.kind === SyntaxKind.NumericLiteral) {
var literalText = (<LiteralExpression>node).text;
return isNegative ? -literalText : +literalText;
}
return undefined;
}
function computeEnumMemberValues(node: EnumDeclaration) {
var nodeLinks = getNodeLinks(node);
@@ -7708,23 +7749,39 @@ module ts {
var enumType = getDeclaredTypeOfSymbol(enumSymbol);
var autoValue = 0;
var ambient = isInAmbientContext(node);
var enumIsConst = isConstEnumDeclaration(node);
forEach(node.members, member => {
if(isNumericName(member.name.text)) {
// TODO(jfreeman): Check that it is not a computed name
if(isNumericName((<Identifier>member.name).text)) {
error(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name);
}
var initializer = member.initializer;
if (initializer) {
autoValue = getConstantValueForExpression(initializer);
if (autoValue === undefined && !ambient) {
// Only here do we need to check that the initializer is assignable to the enum type.
// If it is a constant value (not undefined), it is syntactically constrained to be a number.
// Also, we do not need to check this for ambients because there is already
// a syntax error if it is not a constant.
autoValue = getConstantValueForEnumMemberInitializer(initializer, enumIsConst);
if (autoValue === undefined) {
if (enumIsConst) {
error(initializer, Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression);
}
else if (!ambient) {
// Only here do we need to check that the initializer is assignable to the enum type.
// If it is a constant value (not undefined), it is syntactically constrained to be a number.
// Also, we do not need to check this for ambients because there is already
// a syntax error if it is not a constant.
checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*headMessage*/ undefined);
}
}
else if (enumIsConst) {
if (isNaN(autoValue)) {
error(initializer, Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN);
}
else if (!isFinite(autoValue)) {
error(initializer, Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value);
}
}
}
else if (ambient) {
else if (ambient && !enumIsConst) {
autoValue = undefined;
}
@@ -7735,6 +7792,110 @@ module ts {
nodeLinks.flags |= NodeCheckFlags.EnumValuesComputed;
}
function getConstantValueForEnumMemberInitializer(initializer: Expression, enumIsConst: boolean): number {
return evalConstant(initializer);
function evalConstant(e: Node): number {
switch (e.kind) {
case SyntaxKind.PrefixOperator:
var value = evalConstant((<UnaryExpression>e).operand);
if (value === undefined) {
return undefined;
}
switch ((<UnaryExpression>e).operator) {
case SyntaxKind.PlusToken: return value;
case SyntaxKind.MinusToken: return -value;
case SyntaxKind.TildeToken: return enumIsConst ? ~value : undefined;
}
return undefined;
case SyntaxKind.BinaryExpression:
if (!enumIsConst) {
return undefined;
}
var left = evalConstant((<BinaryExpression>e).left);
if (left === undefined) {
return undefined;
}
var right = evalConstant((<BinaryExpression>e).right);
if (right === undefined) {
return undefined;
}
switch ((<BinaryExpression>e).operator) {
case SyntaxKind.BarToken: return left | right;
case SyntaxKind.AmpersandToken: return left & right;
case SyntaxKind.GreaterThanGreaterThanToken: return left >> right;
case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: return left >>> right;
case SyntaxKind.LessThanLessThanToken: return left << right;
case SyntaxKind.CaretToken: return left ^ right;
case SyntaxKind.AsteriskToken: return left * right;
case SyntaxKind.SlashToken: return left / right;
case SyntaxKind.PlusToken: return left + right;
case SyntaxKind.MinusToken: return left - right;
case SyntaxKind.PercentToken: return left % right;
}
return undefined;
case SyntaxKind.NumericLiteral:
return +(<LiteralExpression>e).text;
case SyntaxKind.ParenExpression:
return enumIsConst ? evalConstant((<ParenExpression>e).expression) : undefined;
case SyntaxKind.Identifier:
case SyntaxKind.IndexedAccess:
case SyntaxKind.PropertyAccess:
if (!enumIsConst) {
return undefined;
}
var member = initializer.parent;
var currentType = getTypeOfSymbol(getSymbolOfNode(member.parent));
var enumType: Type;
var propertyName: string;
if (e.kind === SyntaxKind.Identifier) {
// unqualified names can refer to member that reside in different declaration of the enum so just doing name resolution won't work.
// instead pick current enum type and later try to fetch member from the type
enumType = currentType;
propertyName = (<Identifier>e).text;
}
else {
if (e.kind === SyntaxKind.IndexedAccess) {
if ((<IndexedAccess>e).index.kind !== SyntaxKind.StringLiteral) {
return undefined;
}
var enumType = getTypeOfNode((<IndexedAccess>e).object);
propertyName = (<LiteralExpression>(<IndexedAccess>e).index).text;
}
else {
var enumType = getTypeOfNode((<PropertyAccess>e).left);
propertyName = (<PropertyAccess>e).right.text;
}
if (enumType !== currentType) {
return undefined;
}
}
if (propertyName === undefined) {
return undefined;
}
var property = getPropertyOfObjectType(enumType, propertyName);
if (!property || !(property.flags & SymbolFlags.EnumMember)) {
return undefined;
}
var propertyDecl = property.valueDeclaration;
// self references are illegal
if (member === propertyDecl) {
return undefined;
}
// illegal case: forward reference
if (!isDefinedBefore(propertyDecl, member)) {
return undefined;
}
return <number>getNodeLinks(propertyDecl).enumMemberValue;
}
}
}
}
function checkEnumDeclaration(node: EnumDeclaration) {
@@ -7758,6 +7919,16 @@ module ts {
var enumSymbol = getSymbolOfNode(node);
var firstDeclaration = getDeclarationOfKind(enumSymbol, node.kind);
if (node === firstDeclaration) {
if (enumSymbol.declarations.length > 1) {
var enumIsConst = isConstEnumDeclaration(node);
// check that const is placed\omitted on all enum declarations
forEach(enumSymbol.declarations, decl => {
if (isConstEnumDeclaration(<EnumDeclaration>decl) !== enumIsConst) {
error(decl.name, Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
}
});
}
var seenEnumMissingInitialInitializer = false;
forEach(enumSymbol.declarations, declaration => {
// return true if we hit a violation of the rule, false otherwise
@@ -7787,7 +7958,7 @@ module ts {
var declarations = symbol.declarations;
for (var i = 0; i < declarations.length; i++) {
var declaration = declarations[i];
if ((declaration.kind === SyntaxKind.ClassDeclaration || (declaration.kind === SyntaxKind.FunctionDeclaration && (<FunctionDeclaration>declaration).body)) && !isInAmbientContext(declaration)) {
if ((declaration.kind === SyntaxKind.ClassDeclaration || (declaration.kind === SyntaxKind.FunctionDeclaration && (<FunctionLikeDeclaration>declaration).body)) && !isInAmbientContext(declaration)) {
return declaration;
}
}
@@ -7848,7 +8019,7 @@ module ts {
checkExpression(node.entityName);
}
else {
error(moduleName, Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, identifierToString(moduleName));
error(moduleName, Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, declarationNameToString(moduleName));
}
}
if (target.flags & SymbolFlags.Type) {
@@ -7934,7 +8105,7 @@ module ts {
case SyntaxKind.ParenType:
return checkSourceElement((<ParenTypeNode>node).type);
case SyntaxKind.FunctionDeclaration:
return checkFunctionDeclaration(<FunctionDeclaration>node);
return checkFunctionDeclaration(<FunctionLikeDeclaration>node);
case SyntaxKind.Block:
return checkBlock(<Block>node);
case SyntaxKind.FunctionBlock:
@@ -8001,7 +8172,7 @@ module ts {
switch (node.kind) {
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
forEach((<FunctionDeclaration>node).parameters, checkFunctionExpressionBodies);
forEach((<FunctionLikeDeclaration>node).parameters, checkFunctionExpressionBodies);
checkFunctionExpressionBody(<FunctionExpression>node);
break;
case SyntaxKind.Method:
@@ -8009,7 +8180,7 @@ module ts {
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.FunctionDeclaration:
forEach((<FunctionDeclaration>node).parameters, checkFunctionExpressionBodies);
forEach((<FunctionLikeDeclaration>node).parameters, checkFunctionExpressionBodies);
break;
case SyntaxKind.WithStatement:
checkFunctionExpressionBodies((<WithStatement>node).expression);
@@ -8294,7 +8465,7 @@ module ts {
case SyntaxKind.Method:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return node === (<FunctionDeclaration>parent).type;
return node === (<FunctionLikeDeclaration>parent).type;
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
@@ -8550,7 +8721,7 @@ module ts {
return true;
}
function getLocalNameOfContainer(container: Declaration): string {
function getLocalNameOfContainer(container: ModuleDeclaration | EnumDeclaration): string {
var links = getNodeLinks(container);
if (!links.localModuleName) {
var prefix = "";
@@ -8567,7 +8738,7 @@ module ts {
var node = location;
while (node) {
if ((node.kind === SyntaxKind.ModuleDeclaration || node.kind === SyntaxKind.EnumDeclaration) && getSymbolOfNode(node) === symbol) {
return getLocalNameOfContainer(node);
return getLocalNameOfContainer(<ModuleDeclaration | EnumDeclaration>node);
}
node = node.parent;
}
@@ -8594,17 +8765,16 @@ module ts {
function getExportAssignmentName(node: SourceFile): string {
var symbol = getExportAssignmentSymbol(getSymbolOfNode(node));
return symbol && symbolIsValue(symbol) ? symbolToString(symbol): undefined;
return symbol && symbolIsValue(symbol) && !isConstEnumSymbol(symbol) ? symbolToString(symbol): undefined;
}
function isTopLevelValueImportedViaEntityName(node: ImportDeclaration): boolean {
function isTopLevelValueImportWithEntityName(node: ImportDeclaration): boolean {
if (node.parent.kind !== SyntaxKind.SourceFile || !node.entityName) {
// parent is not source file or it is not reference to internal module
return false;
}
var symbol = getSymbolOfNode(node);
var target = resolveImport(symbol);
return target !== unknownSymbol && ((target.flags & SymbolFlags.Value) !== 0);
return isImportResolvedToValue(getSymbolOfNode(node));
}
function hasSemanticErrors() {
@@ -8616,6 +8786,16 @@ module ts {
return forEach(getDiagnostics(sourceFile), d => d.isEarly);
}
function isImportResolvedToValue(symbol: Symbol): boolean {
var target = resolveImport(symbol);
// const enums and modules that contain only const enums are not considered values from the emit perespective
return target !== unknownSymbol && target.flags & SymbolFlags.Value && !isConstEnumOrConstEnumOnlyModule(target);
}
function isConstEnumOrConstEnumOnlyModule(s: Symbol): boolean {
return isConstEnumSymbol(s) || s.constEnumOnlyModule;
}
function isReferencedImportDeclaration(node: ImportDeclaration): boolean {
var symbol = getSymbolOfNode(node);
if (getSymbolLinks(symbol).referenced) {
@@ -8624,15 +8804,12 @@ module ts {
// logic below will answer 'true' for exported import declaration in a nested module that itself is not exported.
// As a consequence this might cause emitting extra.
if (node.flags & NodeFlags.Export) {
var target = resolveImport(symbol);
if (target !== unknownSymbol && target.flags & SymbolFlags.Value) {
return true;
}
return isImportResolvedToValue(symbol);
}
return false;
}
function isImplementationOfOverload(node: FunctionDeclaration) {
function isImplementationOfOverload(node: FunctionLikeDeclaration) {
if (node.body) {
var symbol = getSymbolOfNode(node);
var signaturesOfSymbol = getSignaturesOfSymbol(symbol);
@@ -8662,7 +8839,7 @@ module ts {
return getNodeLinks(node).enumMemberValue;
}
function getConstantValue(node: PropertyAccess): number {
function getConstantValue(node: PropertyAccess | IndexedAccess): number {
var symbol = getNodeLinks(node).resolvedSymbol;
if (symbol && (symbol.flags & SymbolFlags.EnumMember)) {
var declaration = symbol.valueDeclaration;
@@ -8697,7 +8874,7 @@ module ts {
isReferencedImportDeclaration: isReferencedImportDeclaration,
getNodeCheckFlags: getNodeCheckFlags,
getEnumMemberValue: getEnumMemberValue,
isTopLevelValueImportedViaEntityName: isTopLevelValueImportedViaEntityName,
isTopLevelValueImportWithEntityName: isTopLevelValueImportWithEntityName,
hasSemanticErrors: hasSemanticErrors,
hasEarlyErrors: hasEarlyErrors,
isDeclarationVisible: isDeclarationVisible,
+7 -2
View File
@@ -24,7 +24,7 @@ module ts {
type: "boolean",
},
{
name: "emitBOM",
name: "emitBOM",
type: "boolean"
},
{
@@ -102,7 +102,7 @@ module ts {
{
name: "target",
shortName: "t",
type: { "es3": ScriptTarget.ES3, "es5": ScriptTarget.ES5 , "es6": ScriptTarget.ES6 },
type: { "es3": ScriptTarget.ES3, "es5": ScriptTarget.ES5, "es6": ScriptTarget.ES6 },
description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES6_experimental,
paramType: Diagnostics.VERSION,
error: Diagnostics.Argument_for_target_option_must_be_es3_es5_or_es6
@@ -118,6 +118,11 @@ module ts {
shortName: "w",
type: "boolean",
description: Diagnostics.Watch_input_files,
},
{
name: "preserveConstEnums",
type: "boolean",
description: Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
}
];
+3 -3
View File
@@ -9,7 +9,7 @@ module ts {
// x | y is False if both x and y are False.
// x | y is Maybe if either x or y is Maybe, but neither x or y is True.
// x | y is True if either x or y is True.
export enum Ternary {
export const enum Ternary {
False = 0,
Maybe = 1,
True = -1
@@ -19,7 +19,7 @@ module ts {
[index: string]: T;
}
export enum Comparison {
export const enum Comparison {
LessThan = -1,
EqualTo = 0,
GreaterThan = 1
@@ -637,7 +637,7 @@ module ts {
getSignatureConstructor: () => <any>Signature
}
export enum AssertionLevel {
export const enum AssertionLevel {
None = 0,
Normal = 1,
Aggressive = 2,
@@ -146,7 +146,7 @@ module ts {
Named_properties_0_of_types_1_and_2_are_not_identical: { code: 2319, category: DiagnosticCategory.Error, key: "Named properties '{0}' of types '{1}' and '{2}' are not identical." },
Interface_0_cannot_simultaneously_extend_types_1_and_2: { code: 2320, category: DiagnosticCategory.Error, key: "Interface '{0}' cannot simultaneously extend types '{1}' and '{2}'." },
Excessive_stack_depth_comparing_types_0_and_1: { code: 2321, category: DiagnosticCategory.Error, key: "Excessive stack depth comparing types '{0}' and '{1}'." },
Type_0_is_not_assignable_to_type_1: { code: 2323, category: DiagnosticCategory.Error, key: "Type '{0}' is not assignable to type '{1}'." },
Type_0_is_not_assignable_to_type_1: { code: 2322, category: DiagnosticCategory.Error, key: "Type '{0}' is not assignable to type '{1}'." },
Property_0_is_missing_in_type_1: { code: 2324, category: DiagnosticCategory.Error, key: "Property '{0}' is missing in type '{1}'." },
Property_0_is_private_in_type_1_but_not_in_type_2: { code: 2325, category: DiagnosticCategory.Error, key: "Property '{0}' is private in type '{1}' but not in type '{2}'." },
Types_of_property_0_are_incompatible: { code: 2326, category: DiagnosticCategory.Error, key: "Types of property '{0}' are incompatible." },
@@ -354,6 +354,12 @@ module ts {
Exported_type_alias_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named: { code: 4079, category: DiagnosticCategory.Error, key: "Exported type alias '{0}' has or is using name '{1}' from external module {2} but cannot be named." },
Exported_type_alias_0_has_or_is_using_name_1_from_private_module_2: { code: 4080, category: DiagnosticCategory.Error, key: "Exported type alias '{0}' has or is using name '{1}' from private module '{2}'." },
Exported_type_alias_0_has_or_is_using_private_name_1: { code: 4081, category: DiagnosticCategory.Error, key: "Exported type alias '{0}' has or is using private name '{1}'." },
Enum_declarations_must_all_be_const_or_non_const: { code: 4082, category: DiagnosticCategory.Error, key: "Enum declarations must all be const or non-const." },
In_const_enum_declarations_member_initializer_must_be_constant_expression: { code: 4083, category: DiagnosticCategory.Error, key: "In 'const' enum declarations member initializer must be constant expression.", isEarly: true },
const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: { code: 4084, category: DiagnosticCategory.Error, key: "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment." },
Index_expression_arguments_in_const_enums_must_be_of_type_string: { code: 4085, category: DiagnosticCategory.Error, key: "Index expression arguments in 'const' enums must be of type 'string'." },
const_enum_member_initializer_was_evaluated_to_a_non_finite_value: { code: 4086, category: DiagnosticCategory.Error, key: "'const' enum member initializer was evaluated to a non-finite value." },
const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: { code: 4087, category: DiagnosticCategory.Error, key: "'const' enum member initializer was evaluated to disallowed value 'NaN'." },
The_current_host_does_not_support_the_0_option: { code: 5001, category: DiagnosticCategory.Error, key: "The current host does not support the '{0}' option." },
Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: DiagnosticCategory.Error, key: "Cannot find the common subdirectory path for the input files." },
Cannot_read_file_0_Colon_1: { code: 5012, category: DiagnosticCategory.Error, key: "Cannot read file '{0}': {1}" },
@@ -368,6 +374,7 @@ module ts {
Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: { code: 6004, category: DiagnosticCategory.Message, key: "Specifies the location where debugger should locate TypeScript files instead of source locations." },
Watch_input_files: { code: 6005, category: DiagnosticCategory.Message, key: "Watch input files." },
Redirect_output_structure_to_the_directory: { code: 6006, category: DiagnosticCategory.Message, key: "Redirect output structure to the directory." },
Do_not_erase_const_enum_declarations_in_generated_code: { code: 6007, category: DiagnosticCategory.Message, key: "Do not erase const enum declarations in generated code." },
Do_not_emit_comments_to_output: { code: 6009, category: DiagnosticCategory.Message, key: "Do not emit comments to output." },
Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES6_experimental: { code: 6015, category: DiagnosticCategory.Message, key: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES6' (experimental)" },
Specify_module_code_generation_Colon_commonjs_or_amd: { code: 6016, category: DiagnosticCategory.Message, key: "Specify module code generation: 'commonjs' or 'amd'" },
+29 -7
View File
@@ -580,10 +580,6 @@
"category": "Error",
"code": 2322
},
"Type '{0}' is not assignable to type '{1}'.": {
"category": "Error",
"code": 2323
},
"Property '{0}' is missing in type '{1}'.": {
"category": "Error",
"code": 2324
@@ -1417,13 +1413,35 @@
"category": "Error",
"code": 4081
},
"Enum declarations must all be const or non-const.": {
"category": "Error",
"code": 4082
},
"In 'const' enum declarations member initializer must be constant expression.": {
"category": "Error",
"code": 4083,
"isEarly": true
},
"'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment.": {
"category": "Error",
"code": 4084
},
"Index expression arguments in 'const' enums must be of type 'string'.": {
"category": "Error",
"code": 4085
},
"'const' enum member initializer was evaluated to a non-finite value.": {
"category": "Error",
"code": 4086
},
"'const' enum member initializer was evaluated to disallowed value 'NaN'.": {
"category": "Error",
"code": 4087
},
"The current host does not support the '{0}' option.": {
"category": "Error",
"code": 5001
},
"Cannot find the common subdirectory path for the input files.": {
"category": "Error",
"code": 5009
@@ -1476,6 +1494,10 @@
"category": "Message",
"code": 6006
},
"Do not erase const enum declarations in generated code.": {
"category": "Message",
"code": 6007
},
"Do not emit comments to output.": {
"category": "Message",
"code": 6009
+75 -37
View File
@@ -86,8 +86,9 @@ module ts {
var getAccessor: AccessorDeclaration;
var setAccessor: AccessorDeclaration;
forEach(node.members, (member: Declaration) => {
// TODO(jfreeman): Handle computed names for accessor matching
if ((member.kind === SyntaxKind.GetAccessor || member.kind === SyntaxKind.SetAccessor) &&
member.name.text === accessor.name.text &&
(<Identifier>member.name).text === (<Identifier>accessor.name).text &&
(member.flags & NodeFlags.Static) === (accessor.flags & NodeFlags.Static)) {
if (!firstAccessor) {
firstAccessor = <AccessorDeclaration>member;
@@ -577,7 +578,8 @@ module ts {
node.kind === SyntaxKind.EnumDeclaration) {
// Declaration and has associated name use it
if ((<Declaration>node).name) {
scopeName = (<Declaration>node).name.text;
// TODO(jfreeman): Ask shkamat about what this name should be for source maps
scopeName = (<Identifier>(<Declaration>node).name).text;
}
recordScopeNameStart(scopeName);
}
@@ -907,15 +909,15 @@ module ts {
// This function specifically handles numeric/string literals for enum and accessor 'identifiers'.
// In a sense, it does not actually emit identifiers as much as it declares a name for a specific property.
function emitQuotedIdentifier(node: Identifier) {
function emitExpressionForPropertyName(node: DeclarationName) {
if (node.kind === SyntaxKind.StringLiteral) {
emitLiteral(node);
emitLiteral(<LiteralExpression>node);
}
else {
write("\"");
if (node.kind === SyntaxKind.NumericLiteral) {
write(node.text);
write((<LiteralExpression>node).text);
}
else {
write(getSourceTextOfLocalNode(node));
@@ -1031,19 +1033,29 @@ module ts {
emitTrailingComments(node);
}
function emitPropertyAccess(node: PropertyAccess) {
function tryEmitConstantValue(node: PropertyAccess | IndexedAccess): boolean {
var constantValue = resolver.getConstantValue(node);
if (constantValue !== undefined) {
write(constantValue.toString() + " /* " + identifierToString(node.right) + " */");
var propertyName = node.kind === SyntaxKind.PropertyAccess ? declarationNameToString((<PropertyAccess>node).right) : getTextOfNode((<IndexedAccess>node).index);
write(constantValue.toString() + " /* " + propertyName + " */");
return true;
}
else {
emit(node.left);
write(".");
emit(node.right);
return false;
}
function emitPropertyAccess(node: PropertyAccess) {
if (tryEmitConstantValue(node)) {
return;
}
emit(node.left);
write(".");
emit(node.right);
}
function emitIndexedAccess(node: IndexedAccess) {
if (tryEmitConstantValue(node)) {
return;
}
emit(node.object);
write("[");
emit(node.index);
@@ -1341,6 +1353,10 @@ module ts {
emitToken(SyntaxKind.CloseBraceToken, node.clauses.end);
}
function isOnSameLine(node1: Node, node2: Node) {
return getLineOfLocalPosition(skipTrivia(currentSourceFile.text, node1.pos)) === getLineOfLocalPosition(skipTrivia(currentSourceFile.text, node2.pos));
}
function emitCaseOrDefaultClause(node: CaseOrDefaultClause) {
if (node.kind === SyntaxKind.CaseClause) {
write("case ");
@@ -1350,9 +1366,16 @@ module ts {
else {
write("default:");
}
increaseIndent();
emitLines(node.statements);
decreaseIndent();
if (node.statements.length === 1 && isOnSameLine(node, node.statements[0])) {
write(" ");
emit(node.statements[0]);
}
else {
increaseIndent();
emitLines(node.statements);
decreaseIndent();
}
}
function emitThrowStatement(node: ThrowStatement) {
@@ -1443,7 +1466,7 @@ module ts {
emitTrailingComments(node);
}
function emitDefaultValueAssignments(node: FunctionDeclaration) {
function emitDefaultValueAssignments(node: FunctionLikeDeclaration) {
forEach(node.parameters, param => {
if (param.initializer) {
writeLine();
@@ -1463,7 +1486,7 @@ module ts {
});
}
function emitRestParameter(node: FunctionDeclaration) {
function emitRestParameter(node: FunctionLikeDeclaration) {
if (hasRestParameters(node)) {
var restIndex = node.parameters.length - 1;
var restParam = node.parameters[restIndex];
@@ -1509,7 +1532,7 @@ module ts {
emitTrailingComments(node);
}
function emitFunctionDeclaration(node: FunctionDeclaration) {
function emitFunctionDeclaration(node: FunctionLikeDeclaration) {
if (!node.body) {
return emitPinnedOrTripleSlashComments(node);
}
@@ -1537,7 +1560,7 @@ module ts {
}
}
function emitSignatureParameters(node: FunctionDeclaration) {
function emitSignatureParameters(node: FunctionLikeDeclaration) {
increaseIndent();
write("(");
if (node) {
@@ -1547,7 +1570,7 @@ module ts {
decreaseIndent();
}
function emitSignatureAndBody(node: FunctionDeclaration) {
function emitSignatureAndBody(node: FunctionLikeDeclaration) {
emitSignatureParameters(node);
write(" {");
scopeEmitStart(node);
@@ -1644,7 +1667,8 @@ module ts {
});
}
function emitMemberAccess(memberName: Identifier) {
// TODO(jfreeman): Account for computed property name
function emitMemberAccess(memberName: DeclarationName) {
if (memberName.kind === SyntaxKind.StringLiteral || memberName.kind === SyntaxKind.NumericLiteral) {
write("[");
emitNode(memberName);
@@ -1717,7 +1741,7 @@ module ts {
write(".prototype");
}
write(", ");
emitQuotedIdentifier((<AccessorDeclaration>member).name);
emitExpressionForPropertyName((<AccessorDeclaration>member).name);
emitEnd((<AccessorDeclaration>member).name);
write(", {");
increaseIndent();
@@ -1876,6 +1900,11 @@ module ts {
}
function emitEnumDeclaration(node: EnumDeclaration) {
// const enums are completely erased during compilation.
var isConstEnum = isConstEnumDeclaration(node);
if (isConstEnum && !compilerOptions.preserveConstEnums) {
return;
}
emitLeadingComments(node);
if (!(node.flags & NodeFlags.Export)) {
emitStart(node);
@@ -1893,7 +1922,7 @@ module ts {
write(") {");
increaseIndent();
scopeEmitStart(node);
emitEnumMemberDeclarations();
emitEnumMemberDeclarations(isConstEnum);
decreaseIndent();
writeLine();
emitToken(SyntaxKind.CloseBraceToken, node.members.end);
@@ -1916,7 +1945,7 @@ module ts {
}
emitTrailingComments(node);
function emitEnumMemberDeclarations() {
function emitEnumMemberDeclarations(isConstEnum: boolean) {
forEach(node.members, member => {
writeLine();
emitLeadingComments(member);
@@ -1925,16 +1954,16 @@ module ts {
write("[");
write(resolver.getLocalNameOfContainer(node));
write("[");
emitQuotedIdentifier(member.name);
emitExpressionForPropertyName(member.name);
write("] = ");
if (member.initializer) {
if (member.initializer && !isConstEnum) {
emit(member.initializer);
}
else {
write(resolver.getEnumMemberValue(member).toString());
}
write("] = ");
emitQuotedIdentifier(member.name);
emitExpressionForPropertyName(member.name);
emitEnd(member);
write(";");
emitTrailingComments(member);
@@ -1950,7 +1979,7 @@ module ts {
}
function emitModuleDeclaration(node: ModuleDeclaration) {
if (!isInstantiated(node)) {
if (getModuleInstanceState(node) !== ModuleInstanceState.Instantiated) {
return emitPinnedOrTripleSlashComments(node);
}
emitLeadingComments(node);
@@ -2002,7 +2031,7 @@ module ts {
// preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when
// - current file is not external module
// - import declaration is top level and target is value imported by entity name
emitImportDeclaration = !isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportedViaEntityName(node);
emitImportDeclaration = !isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportWithEntityName(node);
}
if (emitImportDeclaration) {
@@ -2046,7 +2075,10 @@ module ts {
function getExternalImportDeclarations(node: SourceFile): ImportDeclaration[] {
var result: ImportDeclaration[] = [];
forEach(node.statements, stat => {
if (stat.kind === SyntaxKind.ImportDeclaration && (<ImportDeclaration>stat).externalModuleName && resolver.isReferencedImportDeclaration(stat)) {
if (stat.kind === SyntaxKind.ImportDeclaration
&& (<ImportDeclaration>stat).externalModuleName
&& resolver.isReferencedImportDeclaration(<ImportDeclaration>stat)) {
result.push(<ImportDeclaration>stat);
}
});
@@ -2235,7 +2267,7 @@ module ts {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
return emitFunctionDeclaration(<FunctionDeclaration>node);
return emitFunctionDeclaration(<FunctionLikeDeclaration>node);
case SyntaxKind.PrefixOperator:
case SyntaxKind.PostfixOperator:
return emitUnaryExpression(<UnaryExpression>node);
@@ -2478,7 +2510,7 @@ module ts {
var getSymbolVisibilityDiagnosticMessage: (symbolAccesibilityResult: SymbolAccessiblityResult) => {
errorNode: Node;
diagnosticMessage: DiagnosticMessage;
typeName?: Identifier
typeName?: DeclarationName
}
function createTextWriterWithSymbolWriter(): EmitTextWriterWithSymbolWriter {
@@ -2722,6 +2754,9 @@ module ts {
if (resolver.isDeclarationVisible(node)) {
emitJsDocComments(node);
emitDeclarationFlags(node);
if (isConstEnumDeclaration(node)) {
write("const ")
}
write("enum ");
emitSourceTextOfNode(node.name);
write(" {");
@@ -2801,7 +2836,7 @@ module ts {
break;
default:
Debug.fail("This is unknown parent for type parameter: " + SyntaxKind[node.parent.kind]);
Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
}
return {
@@ -2937,11 +2972,12 @@ module ts {
function emitPropertyDeclaration(node: PropertyDeclaration) {
emitJsDocComments(node);
emitDeclarationFlags(node);
emitVariableDeclaration(node);
emitVariableDeclaration(<VariableDeclaration>node);
write(";");
writeLine();
}
// TODO(jfreeman): Factor out common part of property definition, but treat name differently
function emitVariableDeclaration(node: VariableDeclaration) {
// If we are emitting property it isn't moduleElement and hence we already know it needs to be emitted
// so there is no check needed to see if declaration is visible
@@ -2969,6 +3005,7 @@ module ts {
}
// This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
else if (node.kind === SyntaxKind.Property) {
// TODO(jfreeman): Deal with computed properties in error reporting.
if (node.flags & NodeFlags.Static) {
diagnosticMessage = symbolAccesibilityResult.errorModuleName ?
symbolAccesibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ?
@@ -3052,6 +3089,7 @@ module ts {
return {
diagnosticMessage: diagnosticMessage,
errorNode: <Node>node.parameters[0],
// TODO(jfreeman): Investigate why we are passing node.name instead of node.parameters[0].name
typeName: node.name
};
}
@@ -3079,7 +3117,7 @@ module ts {
}
}
function emitFunctionDeclaration(node: FunctionDeclaration) {
function emitFunctionDeclaration(node: FunctionLikeDeclaration) {
// If we are emitting Method/Constructor it isn't moduleElement and hence already determined to be emitting
// so no need to verify if the declaration is visible
if ((node.kind !== SyntaxKind.FunctionDeclaration || resolver.isDeclarationVisible(node)) &&
@@ -3197,7 +3235,7 @@ module ts {
break;
default:
Debug.fail("This is unknown kind for signature: " + SyntaxKind[node.kind]);
Debug.fail("This is unknown kind for signature: " + node.kind);
}
return {
@@ -3282,7 +3320,7 @@ module ts {
break;
default:
Debug.fail("This is unknown parent for parameter: " + SyntaxKind[node.parent.kind]);
Debug.fail("This is unknown parent for parameter: " + node.parent.kind);
}
return {
@@ -3298,7 +3336,7 @@ module ts {
case SyntaxKind.Constructor:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.Method:
return emitFunctionDeclaration(<FunctionDeclaration>node);
return emitFunctionDeclaration(<FunctionLikeDeclaration>node);
case SyntaxKind.ConstructSignature:
return emitConstructSignatureDeclaration(<SignatureDeclaration>node);
case SyntaxKind.CallSignature:
+71 -39
View File
@@ -62,9 +62,10 @@ module ts {
return identifier.length >= 3 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ && identifier.charCodeAt(2) === CharacterCodes._ ? identifier.substr(1) : identifier;
}
// TODO(jfreeman): Implement declarationNameToString for computed properties
// Return display name of an identifier
export function identifierToString(identifier: Identifier) {
return identifier.kind === SyntaxKind.Missing ? "(Missing)" : getTextOfNode(identifier);
export function declarationNameToString(name: DeclarationName) {
return name.kind === SyntaxKind.Missing ? "(Missing)" : getTextOfNode(name);
}
export function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): Diagnostic {
@@ -115,6 +116,10 @@ module ts {
return (file.flags & NodeFlags.DeclarationFile) !== 0;
}
export function isConstEnumDeclaration(node: EnumDeclaration): boolean {
return (node.flags & NodeFlags.Const) !== 0;
}
export function isPrologueDirective(node: Node): boolean {
return node.kind === SyntaxKind.ExpressionStatement && (<ExpressionStatement>node).expression.kind === SyntaxKind.StringLiteral;
}
@@ -209,11 +214,11 @@ module ts {
case SyntaxKind.FunctionExpression:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ArrowFunction:
return child((<FunctionDeclaration>node).name) ||
children((<FunctionDeclaration>node).typeParameters) ||
children((<FunctionDeclaration>node).parameters) ||
child((<FunctionDeclaration>node).type) ||
child((<FunctionDeclaration>node).body);
return child((<FunctionLikeDeclaration>node).name) ||
children((<FunctionLikeDeclaration>node).typeParameters) ||
children((<FunctionLikeDeclaration>node).parameters) ||
child((<FunctionLikeDeclaration>node).type) ||
child((<FunctionLikeDeclaration>node).body);
case SyntaxKind.TypeReference:
return child((<TypeReferenceNode>node).typeName) ||
children((<TypeReferenceNode>node).typeArguments);
@@ -694,7 +699,7 @@ module ts {
Count // Number of parsing contexts
}
enum Tristate {
const enum Tristate {
False,
True,
Unknown
@@ -724,13 +729,13 @@ module ts {
}
};
enum LookAheadMode {
const enum LookAheadMode {
NotLookingAhead,
NoErrorYet,
Error
}
enum ModifierContext {
const enum ModifierContext {
SourceElements, // Top level elements in a source file
ModuleElements, // Elements in module declaration
ClassMembers, // Members in class declaration
@@ -739,7 +744,7 @@ module ts {
// Tracks whether we nested (directly or indirectly) in a certain control block.
// Used for validating break and continue statements.
enum ControlBlockContext {
const enum ControlBlockContext {
NotNested,
Nested,
CrossingFunctionBoundary
@@ -935,7 +940,7 @@ module ts {
}
function reportInvalidUseInStrictMode(node: Identifier): void {
// identifierToString cannot be used here since it uses a backreference to 'parent' that is not yet set
// declarationNameToString cannot be used here since it uses a backreference to 'parent' that is not yet set
var name = sourceText.substring(skipTrivia(sourceText, node.pos), node.end);
grammarErrorOnNode(node, Diagnostics.Invalid_use_of_0_in_strict_mode, name);
}
@@ -1645,7 +1650,7 @@ module ts {
// Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code
// or if its FunctionBody is strict code(11.1.5).
// It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
// strict mode FunctionDeclaration or FunctionExpression(13.1)
// strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
if (isInStrictMode && isEvalOrArgumentsIdentifier(parameter.name)) {
reportInvalidUseInStrictMode(parameter.name);
return;
@@ -2726,9 +2731,13 @@ module ts {
var SetAccesor = 4;
var GetOrSetAccessor = GetAccessor | SetAccesor;
forEach(node.properties, (p: Declaration) => {
// TODO(jfreeman): continue if we have a computed property
if (p.kind === SyntaxKind.OmittedExpression) {
return;
}
var name = <Identifier>p.name;
// ECMA-262 11.1.5 Object Initialiser
// If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
// a.This production is contained in strict code and IsDataDescriptor(previous) is true and
@@ -2748,29 +2757,29 @@ module ts {
currentKind = SetAccesor;
}
else {
Debug.fail("Unexpected syntax kind:" + SyntaxKind[p.kind]);
Debug.fail("Unexpected syntax kind:" + p.kind);
}
if (!hasProperty(seen, p.name.text)) {
seen[p.name.text] = currentKind;
if (!hasProperty(seen, name.text)) {
seen[name.text] = currentKind;
}
else {
var existingKind = seen[p.name.text];
var existingKind = seen[name.text];
if (currentKind === Property && existingKind === Property) {
if (isInStrictMode) {
grammarErrorOnNode(p.name, Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode);
grammarErrorOnNode(name, Diagnostics.An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode);
}
}
else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) {
if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) {
seen[p.name.text] = currentKind | existingKind;
seen[name.text] = currentKind | existingKind;
}
else {
grammarErrorOnNode(p.name, Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
grammarErrorOnNode(name, Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
}
}
else {
grammarErrorOnNode(p.name, Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
grammarErrorOnNode(name, Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
}
}
});
@@ -2785,7 +2794,7 @@ module ts {
var body = parseBody(/* ignoreMissingOpenBrace */ false);
if (name && isInStrictMode && isEvalOrArgumentsIdentifier(name)) {
// It is a SyntaxError to use within strict mode code the identifiers eval or arguments as the
// Identifier of a FunctionDeclaration or FunctionExpression or as a formal parameter name(13.1)
// Identifier of a FunctionLikeDeclaration or FunctionExpression or as a formal parameter name(13.1)
reportInvalidUseInStrictMode(name);
}
return makeFunctionExpression(SyntaxKind.FunctionExpression, pos, name, sig, body);
@@ -3264,7 +3273,6 @@ module ts {
case SyntaxKind.OpenBraceToken:
case SyntaxKind.VarKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.ConstKeyword:
case SyntaxKind.FunctionKeyword:
case SyntaxKind.IfKeyword:
case SyntaxKind.DoKeyword:
@@ -3283,6 +3291,12 @@ module ts {
case SyntaxKind.CatchKeyword:
case SyntaxKind.FinallyKeyword:
return true;
case SyntaxKind.ConstKeyword:
// const keyword can precede enum keyword when defining constant enums
// 'const enum' do not start statement.
// In ES 6 'enum' is a future reserved keyword, so it should not be used as identifier
var isConstEnum = lookAhead(() => nextToken() === SyntaxKind.EnumKeyword);
return !isConstEnum;
case SyntaxKind.InterfaceKeyword:
case SyntaxKind.ClassKeyword:
case SyntaxKind.ModuleKeyword:
@@ -3293,6 +3307,7 @@ module ts {
if (isDeclarationStart()) {
return false;
}
case SyntaxKind.PublicKeyword:
case SyntaxKind.PrivateKeyword:
case SyntaxKind.ProtectedKeyword:
@@ -3314,6 +3329,7 @@ module ts {
case SyntaxKind.VarKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.ConstKeyword:
// const here should always be parsed as const declaration because of check in 'isStatement'
return parseVariableStatement(allowLetAndConstDeclarations);
case SyntaxKind.FunctionKeyword:
return parseFunctionDeclaration();
@@ -3501,8 +3517,8 @@ module ts {
return node;
}
function parseFunctionDeclaration(pos?: number, flags?: NodeFlags): FunctionDeclaration {
var node = <FunctionDeclaration>createNode(SyntaxKind.FunctionDeclaration, pos);
function parseFunctionDeclaration(pos?: number, flags?: NodeFlags): FunctionLikeDeclaration {
var node = <FunctionLikeDeclaration>createNode(SyntaxKind.FunctionDeclaration, pos);
if (flags) node.flags = flags;
parseExpected(SyntaxKind.FunctionKeyword);
node.name = parseIdentifier();
@@ -3511,10 +3527,10 @@ module ts {
node.parameters = sig.parameters;
node.type = sig.type;
node.body = parseAndCheckFunctionBody(/*isConstructor*/ false);
if (isInStrictMode && isEvalOrArgumentsIdentifier(node.name)) {
if (isInStrictMode && isEvalOrArgumentsIdentifier(node.name) && node.name.kind === SyntaxKind.Identifier) {
// It is a SyntaxError to use within strict mode code the identifiers eval or arguments as the
// Identifier of a FunctionDeclaration or FunctionExpression or as a formal parameter name(13.1)
reportInvalidUseInStrictMode(node.name);
// Identifier of a FunctionLikeDeclaration or FunctionExpression or as a formal parameter name(13.1)
reportInvalidUseInStrictMode(<Identifier>node.name);
}
return finishNode(node);
}
@@ -3631,7 +3647,7 @@ module ts {
// A common error is to try to declare an accessor in an ambient class.
if (inAmbientContext && canParseSemicolon()) {
parseSemicolon();
node.body = createMissingNode();
node.body = <Block>createMissingNode();
}
else {
node.body = parseBody(/* ignoreMissingOpenBrace */ false);
@@ -3935,6 +3951,7 @@ module ts {
}
function parseAndCheckEnumDeclaration(pos: number, flags: NodeFlags): EnumDeclaration {
var enumIsConst = flags & NodeFlags.Const;
function isIntegerLiteral(expression: Expression): boolean {
function isInteger(literalExpression: LiteralExpression): boolean {
// Allows for scientific notation since literalExpression.text was formed by
@@ -3969,22 +3986,29 @@ module ts {
node.name = parsePropertyName();
node.initializer = parseInitializer(/*inParameter*/ false);
if (inAmbientContext) {
if (node.initializer && !isIntegerLiteral(node.initializer) && errorCountBeforeEnumMember === file.syntacticErrors.length) {
grammarErrorOnNode(node.name, Diagnostics.Ambient_enum_elements_can_only_have_integer_literal_initializers);
// skip checks below for const enums - they allow arbitrary initializers as long as they can be evaluated to constant expressions.
// since all values are known in compile time - it is not necessary to check that constant enum section precedes computed enum members.
if (!enumIsConst) {
if (inAmbientContext) {
if (node.initializer && !isIntegerLiteral(node.initializer) && errorCountBeforeEnumMember === file.syntacticErrors.length) {
grammarErrorOnNode(node.name, Diagnostics.Ambient_enum_elements_can_only_have_integer_literal_initializers);
}
}
else if (node.initializer) {
inConstantEnumMemberSection = isIntegerLiteral(node.initializer);
}
else if (!inConstantEnumMemberSection && errorCountBeforeEnumMember === file.syntacticErrors.length) {
grammarErrorOnNode(node.name, Diagnostics.Enum_member_must_have_initializer);
}
}
else if (node.initializer) {
inConstantEnumMemberSection = isIntegerLiteral(node.initializer);
}
else if (!inConstantEnumMemberSection && errorCountBeforeEnumMember === file.syntacticErrors.length) {
grammarErrorOnNode(node.name, Diagnostics.Enum_member_must_have_initializer);
}
return finishNode(node);
}
var node = <EnumDeclaration>createNode(SyntaxKind.EnumDeclaration, pos);
node.flags = flags;
if (enumIsConst) {
parseExpected(SyntaxKind.ConstKeyword);
}
parseExpected(SyntaxKind.EnumKeyword);
node.name = parseIdentifier();
if (parseExpected(SyntaxKind.OpenBraceToken)) {
@@ -4141,9 +4165,17 @@ module ts {
switch (token) {
case SyntaxKind.VarKeyword:
case SyntaxKind.LetKeyword:
case SyntaxKind.ConstKeyword:
result = parseVariableStatement(/*allowLetAndConstDeclarations*/ true, pos, flags);
break;
case SyntaxKind.ConstKeyword:
var isConstEnum = lookAhead(() => nextToken() === SyntaxKind.EnumKeyword);
if (isConstEnum) {
result = parseAndCheckEnumDeclaration(pos, flags | NodeFlags.Const);
}
else {
result = parseVariableStatement(/*allowLetAndConstDeclarations*/ true, pos, flags);
}
break;
case SyntaxKind.FunctionKeyword:
result = parseFunctionDeclaration(pos, flags);
break;
+107 -59
View File
@@ -1,5 +1,4 @@
/// <reference path="core.ts"/>
/// <reference path="scanner.ts"/>
module ts {
@@ -9,7 +8,7 @@ module ts {
}
// token > SyntaxKind.Identifer => token is a keyword
export enum SyntaxKind {
export const enum SyntaxKind {
Unknown,
EndOfFileToken,
SingleLineCommentTrivia,
@@ -253,7 +252,7 @@ module ts {
LastTemplateToken = TemplateTail
}
export enum NodeFlags {
export const enum NodeFlags {
Export = 0x00000001, // Declarations
Ambient = 0x00000002, // Declarations
QuestionMark = 0x00000004, // Parameter/Property/Method
@@ -306,17 +305,25 @@ module ts {
type?: TypeNode;
}
export type DeclarationName = Identifier | LiteralExpression | ComputedPropertyName;
export interface Declaration extends Node {
name?: Identifier;
name?: DeclarationName;
}
export interface ComputedPropertyName extends Node {
expression: Expression;
}
export interface TypeParameterDeclaration extends Declaration {
name: Identifier;
constraint?: TypeNode;
}
export interface SignatureDeclaration extends Declaration, ParsedSignature { }
export interface VariableDeclaration extends Declaration {
name: Identifier;
pattern?: BindingPattern;
type?: TypeNode;
initializer?: Expression;
@@ -338,19 +345,43 @@ module ts {
pattern?: BindingPattern;
}
export interface PropertyDeclaration extends VariableDeclaration { }
export interface PropertyDeclaration extends Declaration {
type?: TypeNode;
initializer?: Expression;
}
export interface ParameterDeclaration extends VariableDeclaration { }
export interface FunctionDeclaration extends Declaration, ParsedSignature {
/**
* Several node kinds share function-like features such as a signature,
* a name, and a body. These nodes should extend FunctionLikeDeclaration.
* Examples:
* FunctionDeclaration
* MethodDeclaration
* ConstructorDeclaration
* AccessorDeclaration
* FunctionExpression
*/
export interface FunctionLikeDeclaration extends Declaration, ParsedSignature {
body?: Block | Expression;
}
export interface MethodDeclaration extends FunctionDeclaration { }
export interface FunctionDeclaration extends FunctionLikeDeclaration {
name: Identifier;
body?: Block;
}
export interface ConstructorDeclaration extends FunctionDeclaration { }
export interface MethodDeclaration extends FunctionLikeDeclaration {
body?: Block;
}
export interface AccessorDeclaration extends FunctionDeclaration { }
export interface ConstructorDeclaration extends FunctionLikeDeclaration {
body?: Block;
}
export interface AccessorDeclaration extends FunctionLikeDeclaration {
body?: Block;
}
export interface TypeNode extends Node { }
@@ -408,7 +439,8 @@ module ts {
whenFalse: Expression;
}
export interface FunctionExpression extends Expression, FunctionDeclaration {
export interface FunctionExpression extends Expression, FunctionLikeDeclaration {
name?: Identifier;
body: Block | Expression; // Required, whereas the member inherited from FunctionDeclaration is optional
}
@@ -559,6 +591,7 @@ module ts {
}
export interface ClassDeclaration extends Declaration {
name: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
baseType?: TypeReferenceNode;
implementedTypes?: NodeArray<TypeReferenceNode>;
@@ -566,28 +599,34 @@ module ts {
}
export interface InterfaceDeclaration extends Declaration {
name: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
baseTypes?: NodeArray<TypeReferenceNode>;
members: NodeArray<Node>;
}
export interface TypeAliasDeclaration extends Declaration {
name: Identifier;
type: TypeNode;
}
export interface EnumMember extends Declaration {
name: Identifier | LiteralExpression;
initializer?: Expression;
}
export interface EnumDeclaration extends Declaration {
name: Identifier;
members: NodeArray<EnumMember>;
}
export interface ModuleDeclaration extends Declaration {
name: Identifier | LiteralExpression;
body: Block | ModuleDeclaration;
}
export interface ImportDeclaration extends Declaration {
name: Identifier;
entityName?: EntityName;
externalModuleName?: LiteralExpression;
}
@@ -702,7 +741,7 @@ module ts {
getContextualType(node: Node): Type;
getResolvedSignature(node: CallExpression, candidatesOutArray?: Signature[]): Signature;
getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature;
isImplementationOfOverload(node: FunctionDeclaration): boolean;
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean;
isUndefinedSymbol(symbol: Symbol): boolean;
isArgumentsSymbol(symbol: Symbol): boolean;
hasEarlyErrors(sourceFile?: SourceFile): boolean;
@@ -743,7 +782,7 @@ module ts {
trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void;
}
export enum TypeFormatFlags {
export const enum TypeFormatFlags {
None = 0x00000000,
WriteArrayAsGenericType = 0x00000001, // Write Array<T> instead T[]
UseTypeOfFunction = 0x00000002, // Write typeof instead of function type literal
@@ -754,7 +793,7 @@ module ts {
InElementType = 0x00000040, // Writing an array or union element type
}
export enum SymbolFormatFlags {
export const enum SymbolFormatFlags {
None = 0x00000000,
WriteTypeParametersOrArguments = 0x00000001, // Write symbols's type argument if it is instantiated symbol
// eg. class C<T> { p: T } <-- Show p as C<T>.p here
@@ -765,7 +804,7 @@ module ts {
// When this flag is specified m.c will be used to refer to the class instead of alias symbol x
}
export enum SymbolAccessibility {
export const enum SymbolAccessibility {
Accessible,
NotAccessible,
CannotBeNamed
@@ -780,26 +819,26 @@ module ts {
export interface EmitResolver {
getProgram(): Program;
getLocalNameOfContainer(container: Declaration): string;
getLocalNameOfContainer(container: ModuleDeclaration | EnumDeclaration): string;
getExpressionNamePrefix(node: Identifier): string;
getExportAssignmentName(node: SourceFile): string;
isReferencedImportDeclaration(node: ImportDeclaration): boolean;
isTopLevelValueImportedViaEntityName(node: ImportDeclaration): boolean;
isTopLevelValueImportWithEntityName(node: ImportDeclaration): boolean;
getNodeCheckFlags(node: Node): NodeCheckFlags;
getEnumMemberValue(node: EnumMember): number;
hasSemanticErrors(): boolean;
isDeclarationVisible(node: Declaration): boolean;
isImplementationOfOverload(node: FunctionDeclaration): boolean;
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean;
writeTypeAtLocation(location: Node, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void;
isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessiblityResult;
isImportDeclarationEntityNameReferenceDeclarationVisibile(entityName: EntityName): SymbolAccessiblityResult;
// Returns the constant value this property access resolves to, or 'undefined' for a non-constant
getConstantValue(node: PropertyAccess): number;
getConstantValue(node: PropertyAccess | IndexedAccess): number;
hasEarlyErrors(sourceFile?: SourceFile): boolean;
}
export enum SymbolFlags {
export const enum SymbolFlags {
FunctionScopedVariable = 0x00000001, // Variable (var) or parameter
BlockScopedVariable = 0x00000002, // A block-scoped variable (let or const)
Property = 0x00000004, // Property or enum member
@@ -807,32 +846,34 @@ module ts {
Function = 0x00000010, // Function
Class = 0x00000020, // Class
Interface = 0x00000040, // Interface
Enum = 0x00000080, // Enum
ValueModule = 0x00000100, // Instantiated module
NamespaceModule = 0x00000200, // Uninstantiated module
TypeLiteral = 0x00000400, // Type Literal
ObjectLiteral = 0x00000800, // Object Literal
Method = 0x00001000, // Method
Constructor = 0x00002000, // Constructor
GetAccessor = 0x00004000, // Get accessor
SetAccessor = 0x00008000, // Set accessor
CallSignature = 0x00010000, // Call signature
ConstructSignature = 0x00020000, // Construct signature
IndexSignature = 0x00040000, // Index signature
TypeParameter = 0x00080000, // Type parameter
TypeAlias = 0x00100000, // Type alias
ConstEnum = 0x00000080, // Const enum
RegularEnum = 0x00000100, // Enum
ValueModule = 0x00000200, // Instantiated module
NamespaceModule = 0x00000400, // Uninstantiated module
TypeLiteral = 0x00000800, // Type Literal
ObjectLiteral = 0x00001000, // Object Literal
Method = 0x00002000, // Method
Constructor = 0x00004000, // Constructor
GetAccessor = 0x00008000, // Get accessor
SetAccessor = 0x00010000, // Set accessor
CallSignature = 0x00020000, // Call signature
ConstructSignature = 0x00040000, // Construct signature
IndexSignature = 0x00080000, // Index signature
TypeParameter = 0x00100000, // Type parameter
TypeAlias = 0x00200000, // Type alias
// Export markers (see comment in declareModuleMember in binder)
ExportValue = 0x00200000, // Exported value marker
ExportType = 0x00400000, // Exported type marker
ExportNamespace = 0x00800000, // Exported namespace marker
Import = 0x01000000, // Import
Instantiated = 0x02000000, // Instantiated symbol
Merged = 0x04000000, // Merged symbol (created during program binding)
Transient = 0x08000000, // Transient symbol (created during type check)
Prototype = 0x10000000, // Prototype property (no source representation)
UnionProperty = 0x20000000, // Property in union type
ExportValue = 0x00400000, // Exported value marker
ExportType = 0x00800000, // Exported type marker
ExportNamespace = 0x01000000, // Exported namespace marker
Import = 0x02000000, // Import
Instantiated = 0x04000000, // Instantiated symbol
Merged = 0x08000000, // Merged symbol (created during program binding)
Transient = 0x10000000, // Transient symbol (created during type check)
Prototype = 0x20000000, // Prototype property (no source representation)
UnionProperty = 0x40000000, // Property in union type
Enum = RegularEnum | ConstEnum,
Variable = FunctionScopedVariable | BlockScopedVariable,
Value = Variable | Property | EnumMember | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor,
Type = Class | Interface | Enum | TypeLiteral | ObjectLiteral | TypeParameter | TypeAlias,
@@ -855,8 +896,9 @@ module ts {
FunctionExcludes = Value & ~(Function | ValueModule),
ClassExcludes = (Value | Type) & ~ValueModule,
InterfaceExcludes = Type & ~Interface,
EnumExcludes = (Value | Type) & ~(Enum | ValueModule),
ValueModuleExcludes = Value & ~(Function | Class | Enum | ValueModule),
RegularEnumExcludes = (Value | Type) & ~(RegularEnum | ValueModule), // regular enums merge only with regular enums and modules
ConstEnumExcludes = (Value | Type) & ~ConstEnum, // const enums merge only with const enums
ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule),
NamespaceModuleExcludes = 0,
MethodExcludes = Value & ~Method,
GetAccessorExcludes = Value & ~SetAccessor,
@@ -888,7 +930,8 @@ module ts {
members?: SymbolTable; // Class, interface or literal instance members
exports?: SymbolTable; // Module exports
exportSymbol?: Symbol; // Exported symbol associated with this symbol
valueDeclaration?: Declaration // First value declaration of the symbol
valueDeclaration?: Declaration // First value declaration of the symbol,
constEnumOnlyModule?: boolean // For modules - if true - module contains only const enums or other modules with only const enums.
}
export interface SymbolLinks {
@@ -907,7 +950,7 @@ module ts {
[index: string]: Symbol;
}
export enum NodeCheckFlags {
export const enum NodeCheckFlags {
TypeChecked = 0x00000001, // Node has been type checked
LexicalThis = 0x00000002, // Lexical 'this' reference
CaptureThis = 0x00000004, // Lexical 'this' used in body
@@ -932,7 +975,7 @@ module ts {
assignmentChecks?: Map<boolean>; // Cache of assignment checks
}
export enum TypeFlags {
export const enum TypeFlags {
Any = 0x00000001,
String = 0x00000002,
Number = 0x00000004,
@@ -1030,7 +1073,7 @@ module ts {
mapper?: TypeMapper; // Instantiation mapper
}
export enum SignatureKind {
export const enum SignatureKind {
Call,
Construct,
}
@@ -1050,7 +1093,7 @@ module ts {
isolatedSignatureType?: ObjectType; // A manufactured type that just contains the signature for purposes of signature comparison
}
export enum IndexKind {
export const enum IndexKind {
String,
Number,
}
@@ -1059,14 +1102,18 @@ module ts {
(t: Type): Type;
}
export interface TypeInferences {
primary: Type[]; // Inferences made directly to a type parameter
secondary: Type[]; // Inferences made to a type parameter in a union type
}
export interface InferenceContext {
typeParameters: TypeParameter[]; // Type parameters for which inferences are made
inferUnionTypes: boolean; // Infer union types for disjoint candidates (otherwise undefinedType)
inferenceCount: number; // Incremented for every inference made (whether new or not)
inferences: Type[][]; // Inferences made for each type parameter
inferredTypes: Type[]; // Inferred type for each type parameter
failedTypeParameterIndex?: number; // Index of type parameter for which inference failed
// It is optional because in contextual signature instantiation, nothing fails
typeParameters: TypeParameter[]; // Type parameters for which inferences are made
inferUnionTypes: boolean; // Infer union types for disjoint candidates (otherwise undefinedType)
inferences: TypeInferences[]; // Inferences made for each type parameter
inferredTypes: Type[]; // Inferred type for each type parameter
failedTypeParameterIndex?: number; // Index of type parameter for which inference failed
// It is optional because in contextual signature instantiation, nothing fails
}
export interface DiagnosticMessage {
@@ -1126,10 +1173,11 @@ module ts {
target?: ScriptTarget;
version?: boolean;
watch?: boolean;
preserveConstEnums?: boolean;
[option: string]: string | number | boolean;
}
export enum ModuleKind {
export const enum ModuleKind {
None,
CommonJS,
AMD,
@@ -1144,7 +1192,7 @@ module ts {
}
export enum ScriptTarget {
export const enum ScriptTarget {
ES3,
ES5,
ES6,
@@ -1166,7 +1214,7 @@ module ts {
error?: DiagnosticMessage; // The error given when the argument does not fit a customized 'type'.
}
export enum CharacterCodes {
export const enum CharacterCodes {
nullCharacter = 0,
maxAsciiCharacter = 0x7F,
+1 -1
View File
@@ -3,7 +3,7 @@
/// <reference path='typeWriter.ts' />
/// <reference path='syntacticCleaner.ts' />
enum CompilerTestType {
const enum CompilerTestType {
Conformance,
Regressions,
Test262
+1 -1
View File
@@ -2368,7 +2368,7 @@ module FourSlash {
};
}
enum State {
const enum State {
none,
inSlashStarMarker,
inObjectMarker
+5 -4
View File
@@ -30,7 +30,7 @@ module Utils {
var global = <any>Function("return this").call(null);
// Setup some globals based on the current environment
export enum ExecutionEnvironment {
export const enum ExecutionEnvironment {
Node,
Browser,
CScript
@@ -757,7 +757,6 @@ module Harness {
case 'codepage':
case 'createFileLog':
case 'filename':
case 'propagateenumconstants':
case 'removecomments':
case 'watch':
case 'allowautomaticsemicoloninsertion':
@@ -772,7 +771,9 @@ module Harness {
case 'errortruncation':
options.noErrorTruncation = setting.value === 'false';
break;
case 'preserveconstenums':
options.preserveConstEnums = setting.value === 'true';
break;
default:
throw new Error('Unsupported compiler setting ' + setting.flag);
}
@@ -1147,7 +1148,7 @@ module Harness {
var optionRegex = /^[\/]{2}\s*@(\w+)\s*:\s*(\S*)/gm; // multiple matches on multiple lines
// List of allowed metadata names
var fileMetadataNames = ["filename", "comments", "declaration", "module", "nolib", "sourcemap", "target", "out", "outdir", "noimplicitany", "noresolve", "newline", "newlines", "emitbom", "errortruncation", "usecasesensitivefilenames"];
var fileMetadataNames = ["filename", "comments", "declaration", "module", "nolib", "sourcemap", "target", "out", "outdir", "noimplicitany", "noresolve", "newline", "newlines", "emitbom", "errortruncation", "usecasesensitivefilenames", "preserveconstenums"];
function extractCompilerSettings(content: string): CompilerSetting[] {
+2 -2
View File
@@ -1,7 +1,7 @@
interface TypeWriterResult {
line: number;
column: number;
syntaxKind: string;
syntaxKind: number;
sourceText: string;
type: string;
}
@@ -84,7 +84,7 @@ class TypeWriterWalker {
this.results.push({
line: lineAndCharacter.line - 1,
column: lineAndCharacter.character,
syntaxKind: ts.SyntaxKind[node.kind],
syntaxKind: node.kind,
sourceText: sourceText,
type: this.checker.typeToString(type, node.parent, ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.WriteOwnNameForAnyLike)
});
+10 -10
View File
@@ -74,7 +74,7 @@ module ts.BreakpointResolver {
return textSpan(node);
}
if (node.parent.kind == SyntaxKind.ArrowFunction && (<FunctionDeclaration>node.parent).body == node) {
if (node.parent.kind == SyntaxKind.ArrowFunction && (<FunctionLikeDeclaration>node.parent).body == node) {
// If this is body of arrow function, it is allowed to have the breakpoint
return textSpan(node);
}
@@ -99,7 +99,7 @@ module ts.BreakpointResolver {
case SyntaxKind.Constructor:
case SyntaxKind.FunctionExpression:
case SyntaxKind.ArrowFunction:
return spanInFunctionDeclaration(<FunctionDeclaration>node);
return spanInFunctionDeclaration(<FunctionLikeDeclaration>node);
case SyntaxKind.FunctionBlock:
return spanInFunctionBlock(<Block>node);
@@ -178,7 +178,7 @@ module ts.BreakpointResolver {
case SyntaxKind.ModuleDeclaration:
// span on complete module if it is instantiated
if (!isInstantiated(node)) {
if (getModuleInstanceState(node) !== ModuleInstanceState.Instantiated) {
return undefined;
}
@@ -246,7 +246,7 @@ module ts.BreakpointResolver {
}
// return type of function go to previous token
if (isAnyFunction(node.parent) && (<FunctionDeclaration>node.parent).type === node) {
if (isAnyFunction(node.parent) && (<FunctionLikeDeclaration>node.parent).type === node) {
return spanInPreviousNode(node);
}
@@ -305,7 +305,7 @@ module ts.BreakpointResolver {
return textSpan(parameter);
}
else {
var functionDeclaration = <FunctionDeclaration>parameter.parent;
var functionDeclaration = <FunctionLikeDeclaration>parameter.parent;
var indexOfParameter = indexOf(functionDeclaration.parameters, parameter);
if (indexOfParameter) {
// Not a first parameter, go to previous parameter
@@ -318,12 +318,12 @@ module ts.BreakpointResolver {
}
}
function canFunctionHaveSpanInWholeDeclaration(functionDeclaration: FunctionDeclaration) {
function canFunctionHaveSpanInWholeDeclaration(functionDeclaration: FunctionLikeDeclaration) {
return !!(functionDeclaration.flags & NodeFlags.Export) ||
(functionDeclaration.parent.kind === SyntaxKind.ClassDeclaration && functionDeclaration.kind !== SyntaxKind.Constructor);
}
function spanInFunctionDeclaration(functionDeclaration: FunctionDeclaration): TypeScript.TextSpan {
function spanInFunctionDeclaration(functionDeclaration: FunctionLikeDeclaration): TypeScript.TextSpan {
// No breakpoints in the function signature
if (!functionDeclaration.body) {
return undefined;
@@ -340,7 +340,7 @@ module ts.BreakpointResolver {
function spanInFunctionBlock(block: Block): TypeScript.TextSpan {
var nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken();
if (canFunctionHaveSpanInWholeDeclaration(<FunctionDeclaration>block.parent)) {
if (canFunctionHaveSpanInWholeDeclaration(<FunctionLikeDeclaration>block.parent)) {
return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock);
}
@@ -350,7 +350,7 @@ module ts.BreakpointResolver {
function spanInBlock(block: Block): TypeScript.TextSpan {
switch (block.parent.kind) {
case SyntaxKind.ModuleDeclaration:
if (!isInstantiated(block.parent)) {
if (getModuleInstanceState(block.parent) !== ModuleInstanceState.Instantiated) {
return undefined;
}
@@ -407,7 +407,7 @@ module ts.BreakpointResolver {
switch (node.parent.kind) {
case SyntaxKind.ModuleBlock:
// If this is not instantiated module block no bp span
if (!isInstantiated(node.parent.parent)) {
if (getModuleInstanceState(node.parent.parent) !== ModuleInstanceState.Instantiated) {
return undefined;
}
+6 -6
View File
@@ -99,26 +99,26 @@ module TypeScript {
var start = new Date().getTime();
// Look for:
// import foo = module("foo")
while (token.kind() !== SyntaxKind.EndOfFileToken) {
if (token.kind() === SyntaxKind.ImportKeyword) {
while (token.kind !== SyntaxKind.EndOfFileToken) {
if (token.kind === SyntaxKind.ImportKeyword) {
var importToken = token;
token = scanner.scan(/*allowRegularExpression:*/ false);
if (SyntaxFacts.isIdentifierNameOrAnyKeyword(token)) {
token = scanner.scan(/*allowRegularExpression:*/ false);
if (token.kind() === SyntaxKind.EqualsToken) {
if (token.kind === SyntaxKind.EqualsToken) {
token = scanner.scan(/*allowRegularExpression:*/ false);
if (token.kind() === SyntaxKind.ModuleKeyword || token.kind() === SyntaxKind.RequireKeyword) {
if (token.kind === SyntaxKind.ModuleKeyword || token.kind === SyntaxKind.RequireKeyword) {
token = scanner.scan(/*allowRegularExpression:*/ false);
if (token.kind() === SyntaxKind.OpenParenToken) {
if (token.kind === SyntaxKind.OpenParenToken) {
token = scanner.scan(/*allowRegularExpression:*/ false);
lineMap.fillLineAndCharacterFromPosition(TypeScript.start(importToken, text), lineChar);
if (token.kind() === SyntaxKind.StringLiteral) {
if (token.kind === SyntaxKind.StringLiteral) {
var ref = {
line: lineChar.line,
character: lineChar.character,
+1 -1
View File
@@ -78,7 +78,7 @@ module TypeScript.Services.Formatting {
}
// Push the token
var currentTokenSpan = new TokenSpan(token.kind(), position, width(token));
var currentTokenSpan = new TokenSpan(token.kind, position, width(token));
if (!this.parent().hasSkippedOrMissingTokenChild()) {
if (this.previousTokenSpan) {
// Note that formatPair calls TrimWhitespaceInLineRange in between the 2 tokens
+4 -4
View File
@@ -42,12 +42,12 @@ module TypeScript.Services.Formatting {
var sourceUnit = this.syntaxTree.sourceUnit();
var semicolonPositionedToken = findToken(sourceUnit, caretPosition - 1);
if (semicolonPositionedToken.kind() === SyntaxKind.SemicolonToken) {
if (semicolonPositionedToken.kind === SyntaxKind.SemicolonToken) {
// Find the outer most parent that this semicolon terminates
var current: ISyntaxElement = semicolonPositionedToken;
while (current.parent !== null &&
end(current.parent) === end(semicolonPositionedToken) &&
current.parent.kind() !== SyntaxKind.List) {
current.parent.kind !== SyntaxKind.List) {
current = current.parent;
}
@@ -65,12 +65,12 @@ module TypeScript.Services.Formatting {
var sourceUnit = this.syntaxTree.sourceUnit();
var closeBracePositionedToken = findToken(sourceUnit, caretPosition - 1);
if (closeBracePositionedToken.kind() === SyntaxKind.CloseBraceToken) {
if (closeBracePositionedToken.kind === SyntaxKind.CloseBraceToken) {
// Find the outer most parent that this closing brace terminates
var current: ISyntaxElement = closeBracePositionedToken;
while (current.parent !== null &&
end(current.parent) === end(closeBracePositionedToken) &&
current.parent.kind() !== SyntaxKind.List) {
current.parent.kind !== SyntaxKind.List) {
current = current.parent;
}
@@ -66,7 +66,7 @@ module TypeScript.Services.Formatting {
}
public kind(): SyntaxKind {
return this._node.kind();
return this._node.kind;
}
public hasSkippedOrMissingTokenChild(): boolean {
@@ -103,7 +103,7 @@ module TypeScript.Services.Formatting {
if (isToken(element)) {
this.visitToken(<ISyntaxToken>element);
}
else if (element.kind() === SyntaxKind.List) {
else if (element.kind === SyntaxKind.List) {
for (var i = 0, n = childCount(element); i < n; i++) {
this.walk(childAt(element, i));
}
@@ -148,9 +148,9 @@ module TypeScript.Services.Formatting {
// }
// Also in a do-while statement, the while should be indented like the parent.
if (firstToken(this._parent.node()) === token ||
token.kind() === SyntaxKind.OpenBraceToken || token.kind() === SyntaxKind.CloseBraceToken ||
token.kind() === SyntaxKind.OpenBracketToken || token.kind() === SyntaxKind.CloseBracketToken ||
(token.kind() === SyntaxKind.WhileKeyword && this._parent.node().kind() == SyntaxKind.DoStatement)) {
token.kind === SyntaxKind.OpenBraceToken || token.kind === SyntaxKind.CloseBraceToken ||
token.kind === SyntaxKind.OpenBracketToken || token.kind === SyntaxKind.CloseBracketToken ||
(token.kind === SyntaxKind.WhileKeyword && this._parent.node().kind == SyntaxKind.DoStatement)) {
return this._parent.indentationAmount();
}
@@ -161,7 +161,7 @@ module TypeScript.Services.Formatting {
// If this is token terminating an indentation scope, leading comments should be indented to follow the children
// indentation level and not the node
if (token.kind() === SyntaxKind.CloseBraceToken || token.kind() === SyntaxKind.CloseBracketToken) {
if (token.kind === SyntaxKind.CloseBraceToken || token.kind === SyntaxKind.CloseBracketToken) {
return (this._parent.indentationAmount() + this._parent.childIndentationAmountDelta());
}
return this._parent.indentationAmount();
@@ -213,7 +213,7 @@ module TypeScript.Services.Formatting {
var indentationAmountDelta: number;
var parentNode = parent.node();
switch (node.kind()) {
switch (node.kind) {
default:
// General case
// This node should follow the child indentation set by its parent
@@ -119,7 +119,7 @@ module TypeScript.Services.Formatting {
}
if (token.kind() !== SyntaxKind.EndOfFileToken && indentNextTokenOrTrivia) {
if (token.kind !== SyntaxKind.EndOfFileToken && indentNextTokenOrTrivia) {
// If the last trivia item was a new line, or no trivia items were encounterd record the
// indentation edit at the token position
if (indentationString.length > 0) {
+1 -1
View File
@@ -361,7 +361,7 @@ module ts.formatting {
case SyntaxKind.FunctionExpression:
case SyntaxKind.Method:
case SyntaxKind.ArrowFunction:
return !(<FunctionDeclaration>n).body || isCompletedNode((<FunctionDeclaration>n).body, sourceFile);
return !(<FunctionLikeDeclaration>n).body || isCompletedNode((<FunctionLikeDeclaration>n).body, sourceFile);
case SyntaxKind.ModuleDeclaration:
return (<ModuleDeclaration>n).body && isCompletedNode((<ModuleDeclaration>n).body, sourceFile);
case SyntaxKind.IfStatement:
+10 -6
View File
@@ -73,13 +73,14 @@ module ts.NavigationBar {
function sortNodes(nodes: Node[]): Node[] {
return nodes.slice(0).sort((n1: Declaration, n2: Declaration) => {
if (n1.name && n2.name) {
return n1.name.text.localeCompare(n2.name.text);
// TODO(jfreeman): How do we sort declarations with computed names?
return (<Identifier>n1.name).text.localeCompare((<Identifier>n2.name).text);
}
else if (n1.name) {
return 1;
}
else if (n2.name) {
-1;
return -1;
}
else {
return n1.kind - n2.kind;
@@ -106,7 +107,7 @@ module ts.NavigationBar {
break;
case SyntaxKind.FunctionDeclaration:
var functionDeclaration = <FunctionDeclaration>node;
var functionDeclaration = <FunctionLikeDeclaration>node;
if (isTopLevelFunctionDeclaration(functionDeclaration)) {
topLevelNodes.push(node);
addTopLevelNodes((<Block>functionDeclaration.body).statements, topLevelNodes);
@@ -116,11 +117,12 @@ module ts.NavigationBar {
}
}
function isTopLevelFunctionDeclaration(functionDeclaration: FunctionDeclaration) {
function isTopLevelFunctionDeclaration(functionDeclaration: FunctionLikeDeclaration) {
if (functionDeclaration.kind === SyntaxKind.FunctionDeclaration) {
// A function declaration is 'top level' if it contains any function declarations
// within it.
if (functionDeclaration.body && functionDeclaration.body.kind === SyntaxKind.FunctionBlock) {
// Proper function declarations can only have identifier names
if (forEach((<Block>functionDeclaration.body).statements,
s => s.kind === SyntaxKind.FunctionDeclaration && !isEmpty((<FunctionDeclaration>s).name.text))) {
@@ -230,7 +232,7 @@ module ts.NavigationBar {
return createItem(node, getTextOfNode((<PropertyDeclaration>node).name), ts.ScriptElementKind.memberVariableElement);
case SyntaxKind.FunctionDeclaration:
return createItem(node, getTextOfNode((<FunctionDeclaration>node).name), ts.ScriptElementKind.functionElement);
return createItem(node, getTextOfNode((<FunctionLikeDeclaration>node).name), ts.ScriptElementKind.functionElement);
case SyntaxKind.VariableDeclaration:
if (node.flags & NodeFlags.Const) {
@@ -371,8 +373,10 @@ module ts.NavigationBar {
});
// Add the constructor parameters in as children of the class (for property parameters).
// Note that *all* parameters will be added to the nodes array, but parameters that
// are not properties will be filtered out later by createChildItem.
var nodes: Node[] = constructor
? constructor.parameters.concat(node.members)
? node.members.concat(constructor.parameters)
: node.members;
var childItems = getItemsWorker(sortNodes(nodes), createChildItem);
@@ -95,6 +95,7 @@ module TypeScript {
Expression_expected: "Expression expected.",
Type_expected: "Type expected.",
Template_literal_cannot_be_used_as_an_element_name: "Template literal cannot be used as an element name.",
Computed_property_names_cannot_be_used_here: "Computed property names cannot be used here.",
Duplicate_identifier_0: "Duplicate identifier '{0}'.",
The_name_0_does_not_exist_in_the_current_scope: "The name '{0}' does not exist in the current scope.",
The_name_0_does_not_refer_to_a_value: "The name '{0}' does not refer to a value.",
@@ -97,6 +97,7 @@ module TypeScript {
"Expression expected.": { "code": 1109, "category": DiagnosticCategory.Error },
"Type expected.": { "code": 1110, "category": DiagnosticCategory.Error },
"Template literal cannot be used as an element name.": { "code": 1111, "category": DiagnosticCategory.Error },
"Computed property names cannot be used here.": { "code": 1112, "category": DiagnosticCategory.Error },
"Duplicate identifier '{0}'.": { "code": 2000, "category": DiagnosticCategory.Error },
"The name '{0}' does not exist in the current scope.": { "code": 2001, "category": DiagnosticCategory.Error },
"The name '{0}' does not refer to a value.": { "code": 2002, "category": DiagnosticCategory.Error },
@@ -375,6 +375,10 @@
"category": "Error",
"code": 1111
},
"Computed property names cannot be used here.": {
"category": "Error",
"code": 1112
},
"Duplicate identifier '{0}'.": {
"category": "Error",
"code": 2000
+51 -21
View File
@@ -628,7 +628,7 @@ module ts {
if (this.documentationComment === undefined) {
this.documentationComment = this.declaration ? getJsDocCommentsFromDeclarations(
[this.declaration],
this.declaration.name ? this.declaration.name.text : "",
/*name*/ undefined,
/*canUseParsedParamTagComments*/ false) : [];
}
@@ -674,7 +674,7 @@ module ts {
switch (node.kind) {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.Method:
var functionDeclaration = <FunctionDeclaration>node;
var functionDeclaration = <FunctionLikeDeclaration>node;
if (functionDeclaration.name && functionDeclaration.name.kind !== SyntaxKind.Missing) {
var lastDeclaration = namedDeclarations.length > 0 ?
@@ -685,7 +685,7 @@ module ts {
if (lastDeclaration && functionDeclaration.symbol === lastDeclaration.symbol) {
// Overwrite the last declaration if it was an overload
// and this one is an implementation.
if (functionDeclaration.body && !(<FunctionDeclaration>lastDeclaration).body) {
if (functionDeclaration.body && !(<FunctionLikeDeclaration>lastDeclaration).body) {
namedDeclarations[namedDeclarations.length - 1] = functionDeclaration;
}
}
@@ -1065,7 +1065,7 @@ module ts {
emitOutputStatus: EmitReturnStatus;
}
export enum OutputFileType {
export const enum OutputFileType {
JavaScript,
SourceMap,
Declaration
@@ -1077,7 +1077,7 @@ module ts {
text: string;
}
export enum EndOfLineState {
export const enum EndOfLineState {
Start,
InMultiLineCommentTrivia,
InSingleQuoteStringLiteral,
@@ -1780,7 +1780,7 @@ module ts {
var buckets: Map<Map<DocumentRegistryEntry>> = {};
function getKeyFromCompilationSettings(settings: CompilerOptions): string {
return "_" + ScriptTarget[settings.target]; // + "|" + settings.propagateEnumConstantoString()
return "_" + settings.target; // + "|" + settings.propagateEnumConstantoString()
}
function getBucketForCompilationSettings(settings: CompilerOptions, createIfMissing: boolean): Map<DocumentRegistryEntry> {
@@ -1963,7 +1963,7 @@ module ts {
function isNameOfFunctionDeclaration(node: Node): boolean {
return node.kind === SyntaxKind.Identifier &&
isAnyFunction(node.parent) && (<FunctionDeclaration>node.parent).name === node;
isAnyFunction(node.parent) && (<FunctionLikeDeclaration>node.parent).name === node;
}
/** Returns true if node is a name of an object literal property, e.g. "a" in x = { "a": 1 } */
@@ -2028,7 +2028,7 @@ module ts {
}
}
enum SemanticMeaning {
const enum SemanticMeaning {
None = 0x0,
Value = 0x1,
Type = 0x2,
@@ -2036,7 +2036,7 @@ module ts {
All = Value | Type | Namespace
}
enum BreakContinueSearchType {
const enum BreakContinueSearchType {
None = 0x0,
Unlabeled = 0x1,
Labeled = 0x2,
@@ -2335,24 +2335,35 @@ module ts {
filename = TypeScript.switchToForwardSlashes(filename);
var syntacticStart = new Date().getTime();
var sourceFile = getSourceFile(filename);
var start = new Date().getTime();
var currentToken = getTokenAtPosition(sourceFile, position);
host.log("getCompletionsAtPosition: Get current token: " + (new Date().getTime() - start));
var start = new Date().getTime();
// Completion not allowed inside comments, bail out if this is the case
if (isInsideComment(sourceFile, currentToken, position)) {
var insideComment = isInsideComment(sourceFile, currentToken, position);
host.log("getCompletionsAtPosition: Is inside comment: " + (new Date().getTime() - start));
if (insideComment) {
host.log("Returning an empty list because completion was inside a comment.");
return undefined;
}
// The decision to provide completion depends on the previous token, so find it
// Note: previousToken can be undefined if we are the beginning of the file
var start = new Date().getTime();
var previousToken = findPrecedingToken(position, sourceFile);
host.log("getCompletionsAtPosition: Get previous token 1: " + (new Date().getTime() - start));
// The caret is at the end of an identifier; this is a partial identifier that we want to complete: e.g. a.toS|
// Skip this partial identifier to the previous token
if (previousToken && position <= previousToken.end && previousToken.kind === SyntaxKind.Identifier) {
var start = new Date().getTime();
previousToken = findPrecedingToken(previousToken.pos, sourceFile);
host.log("getCompletionsAtPosition: Get previous token 2: " + (new Date().getTime() - start));
}
// Check if this is a valid completion location
@@ -2383,8 +2394,10 @@ module ts {
symbols: {},
typeChecker: typeInfoResolver
};
host.log("getCompletionsAtPosition: Syntactic work: " + (new Date().getTime() - syntacticStart));
// Populate the completion list
var semanticStart = new Date().getTime();
if (isRightOfDot) {
// Right of dot member completion list
var symbols: Symbol[] = [];
@@ -2454,6 +2467,7 @@ module ts {
if (!isMemberCompletion) {
Array.prototype.push.apply(activeCompletionSession.entries, keywordCompletions);
}
host.log("getCompletionsAtPosition: Semantic work: " + (new Date().getTime() - semanticStart));
return {
isMemberCompletion: isMemberCompletion,
@@ -2461,6 +2475,7 @@ module ts {
};
function getCompletionEntriesFromSymbols(symbols: Symbol[], session: CompletionSession): void {
var start = new Date().getTime();
forEach(symbols, symbol => {
var entry = createCompletionEntry(symbol, session.typeChecker);
if (entry && !lookUp(session.symbols, entry.name)) {
@@ -2468,12 +2483,16 @@ module ts {
session.symbols[entry.name] = symbol;
}
});
host.log("getCompletionsAtPosition: getCompletionEntriesFromSymbols: " + (new Date().getTime() - semanticStart));
}
function isCompletionListBlocker(previousToken: Node): boolean {
return isInStringOrRegularExpressionOrTemplateLiteral(previousToken) ||
var start = new Date().getTime();
var result = isInStringOrRegularExpressionOrTemplateLiteral(previousToken) ||
isIdentifierDefinitionLocation(previousToken) ||
isRightOfIllegalDot(previousToken);
host.log("getCompletionsAtPosition: isCompletionListBlocker: " + (new Date().getTime() - semanticStart));
return result;
}
function isInStringOrRegularExpressionOrTemplateLiteral(previousToken: Node): boolean {
@@ -2639,7 +2658,8 @@ module ts {
return;
}
existingMemberNames[m.name.text] = true;
// TODO(jfreeman): Account for computed property name
existingMemberNames[(<Identifier>m.name).text] = true;
});
var filteredMembers: Symbol[] = [];
@@ -2926,7 +2946,7 @@ module ts {
(location.kind === SyntaxKind.ConstructorKeyword && location.parent.kind === SyntaxKind.Constructor)) { // At constructor keyword of constructor declaration
// get the signature from the declaration and write it
var signature: Signature;
var functionDeclaration = <FunctionDeclaration>location.parent;
var functionDeclaration = <FunctionLikeDeclaration>location.parent;
var allSignatures = functionDeclaration.kind === SyntaxKind.Constructor ? type.getConstructSignatures() : type.getCallSignatures();
if (!typeResolver.isImplementationOfOverload(functionDeclaration)) {
signature = typeResolver.getSignatureFromDeclaration(functionDeclaration);
@@ -3206,7 +3226,7 @@ module ts {
if ((selectConstructors && d.kind === SyntaxKind.Constructor) ||
(!selectConstructors && (d.kind === SyntaxKind.FunctionDeclaration || d.kind === SyntaxKind.Method))) {
declarations.push(d);
if ((<FunctionDeclaration>d).body) definition = d;
if ((<FunctionLikeDeclaration>d).body) definition = d;
}
});
@@ -3453,7 +3473,7 @@ module ts {
}
function getReturnOccurrences(returnStatement: ReturnStatement): ReferenceEntry[] {
var func = <FunctionDeclaration>getContainingFunction(returnStatement);
var func = <FunctionLikeDeclaration>getContainingFunction(returnStatement);
// If we didn't find a containing function with a block body, bail out.
if (!(func && hasKind(func.body, SyntaxKind.FunctionBlock))) {
@@ -3852,7 +3872,7 @@ module ts {
function getNormalizedSymbolName(symbolName: string, declarations: Declaration[]): string {
// Special case for function expressions, whose names are solely local to their bodies.
var functionExpression = forEach(declarations, d => d.kind === SyntaxKind.FunctionExpression ? d : undefined);
var functionExpression = forEach(declarations, d => d.kind === SyntaxKind.FunctionExpression ? <FunctionExpression>d : undefined);
if (functionExpression && functionExpression.name) {
var name = functionExpression.name.text;
@@ -4411,7 +4431,8 @@ module ts {
var declarations = sourceFile.getNamedDeclarations();
for (var i = 0, n = declarations.length; i < n; i++) {
var declaration = declarations[i];
var name = declaration.name.text;
// TODO(jfreeman): Skip this declaration if it has a computed name
var name = (<Identifier>declaration.name).text;
var matchKind = getMatchKind(searchTerms, name);
if (matchKind !== MatchKind.none) {
var container = <Declaration>getContainerNode(declaration);
@@ -4422,7 +4443,8 @@ module ts {
matchKind: MatchKind[matchKind],
fileName: filename,
textSpan: TypeScript.TextSpan.fromBounds(declaration.getStart(), declaration.getEnd()),
containerName: container.name ? container.name.text : "",
// TODO(jfreeman): What should be the containerName when the container has a computed name?
containerName: container.name ? (<Identifier>container.name).text : "",
containerKind: container.name ? getNodeKind(container) : ""
});
}
@@ -4572,7 +4594,7 @@ module ts {
if ((<ModuleDeclaration>node).name.kind === SyntaxKind.StringLiteral) {
return SemanticMeaning.Namespace | SemanticMeaning.Value;
}
else if (isInstantiated(node)) {
else if (getModuleInstanceState(node) === ModuleInstanceState.Instantiated) {
return SemanticMeaning.Namespace | SemanticMeaning.Value;
}
else {
@@ -4849,7 +4871,7 @@ module ts {
*/
function hasValueSideModule(symbol: Symbol): boolean {
return forEach(symbol.declarations, declaration => {
return declaration.kind === SyntaxKind.ModuleDeclaration && isInstantiated(declaration);
return declaration.kind === SyntaxKind.ModuleDeclaration && getModuleInstanceState(declaration) == ModuleInstanceState.Instantiated;
});
}
}
@@ -5135,9 +5157,17 @@ module ts {
}
function getTodoComments(filename: string, descriptors: TodoCommentDescriptor[]): TodoComment[] {
// Note: while getting todo comments seems like a syntactic operation, we actually
// treat it as a semantic operation here. This is because we expect our host to call
// this on every single file. If we treat this syntactically, then that will cause
// us to populate and throw away the tree in our syntax tree cache for each file. By
// treating this as a semantic operation, we can access any tree without throwing
// anything away.
synchronizeHostData();
filename = TypeScript.switchToForwardSlashes(filename);
var sourceFile = getCurrentSourceFile(filename);
var sourceFile = getSourceFile(filename);
cancellationToken.throwIfCancellationRequested();
+2 -2
View File
@@ -171,13 +171,13 @@ module ts {
}
/// TODO: delete this, it is only needed until the VS interface is updated
export enum LanguageVersion {
export const enum LanguageVersion {
EcmaScript3 = 0,
EcmaScript5 = 1,
EcmaScript6 = 2,
}
export enum ModuleGenTarget {
export const enum ModuleGenTarget {
Unspecified = 0,
Synchronous = 1,
Asynchronous = 2,
+1 -1
View File
@@ -244,7 +244,7 @@ module ts.SignatureHelp {
// If the node is not a subspan of its parent, this is a big problem.
// There have been crashes that might be caused by this violation.
if (n.pos < n.parent.pos || n.end > n.parent.end) {
Debug.fail("Node of kind " + SyntaxKind[n.kind] + " is not a subspan of its parent of kind " + SyntaxKind[n.parent.kind]);
Debug.fail("Node of kind " + n.kind + " is not a subspan of its parent of kind " + n.parent.kind);
}
var argumentInfo = getImmediatelyContainingArgumentInfo(n);
+65 -105
View File
@@ -620,8 +620,9 @@ var TypeScript;
SyntaxKind[SyntaxKind["Parameter"] = 208] = "Parameter";
SyntaxKind[SyntaxKind["EnumElement"] = 209] = "EnumElement";
SyntaxKind[SyntaxKind["TypeAnnotation"] = 210] = "TypeAnnotation";
SyntaxKind[SyntaxKind["ExternalModuleReference"] = 211] = "ExternalModuleReference";
SyntaxKind[SyntaxKind["ModuleNameModuleReference"] = 212] = "ModuleNameModuleReference";
SyntaxKind[SyntaxKind["ComputedPropertyName"] = 211] = "ComputedPropertyName";
SyntaxKind[SyntaxKind["ExternalModuleReference"] = 212] = "ExternalModuleReference";
SyntaxKind[SyntaxKind["ModuleNameModuleReference"] = 213] = "ModuleNameModuleReference";
SyntaxKind[SyntaxKind["FirstStandardKeyword"] = SyntaxKind.BreakKeyword] = "FirstStandardKeyword";
SyntaxKind[SyntaxKind["LastStandardKeyword"] = SyntaxKind.WithKeyword] = "LastStandardKeyword";
SyntaxKind[SyntaxKind["FirstFutureReservedKeyword"] = SyntaxKind.ClassKeyword] = "FirstFutureReservedKeyword";
@@ -1040,7 +1041,7 @@ var definitions = [
name: 'VariableDeclaratorSyntax',
baseType: 'ISyntaxNode',
children: [
{ name: 'propertyName', isToken: true },
{ name: 'propertyName', type: 'IPropertyNameSyntax' },
{ name: 'typeAnnotation', type: 'TypeAnnotationSyntax', isOptional: true, isTypeScriptSpecific: true },
{ name: 'equalsValueClause', type: 'EqualsValueClauseSyntax', isOptional: true }
]
@@ -1300,7 +1301,7 @@ var definitions = [
interfaces: ['IMemberExpressionSyntax', 'ICallExpressionSyntax'],
children: [
{ name: 'expression', type: 'ILeftHandSideExpressionSyntax' },
{ name: 'templateExpression', type: 'IPrimaryExpressionSyntax' },
{ name: 'templateExpression', type: 'IPrimaryExpressionSyntax' }
]
},
{
@@ -1309,7 +1310,7 @@ var definitions = [
interfaces: ['IPrimaryExpressionSyntax'],
children: [
{ name: 'templateStartToken', isToken: true, excludeFromAST: true },
{ name: 'templateClauses', isList: true, elementType: 'TemplateClauseSyntax' },
{ name: 'templateClauses', isList: true, elementType: 'TemplateClauseSyntax' }
]
},
{
@@ -1317,7 +1318,7 @@ var definitions = [
baseType: 'ISyntaxNode',
children: [
{ name: 'expression', type: 'IExpressionSyntax' },
{ name: 'templateMiddleOrEndToken', isToken: true, elementType: 'TemplateSpanSyntax' },
{ name: 'templateMiddleOrEndToken', isToken: true, elementType: 'TemplateSpanSyntax' }
]
},
{
@@ -1376,7 +1377,7 @@ var definitions = [
baseType: 'ISyntaxNode',
interfaces: ['ITypeMemberSyntax'],
children: [
{ name: 'propertyName', isToken: true, tokenKinds: ['IdentifierName', 'StringLiteral', 'NumericLiteral'] },
{ name: 'propertyName', type: 'IPropertyNameSyntax' },
{ name: 'questionToken', isToken: true, isOptional: true, itTypeScriptSpecific: true },
{ name: 'callSignature', type: 'CallSignatureSyntax' }
]
@@ -1398,7 +1399,7 @@ var definitions = [
baseType: 'ISyntaxNode',
interfaces: ['ITypeMemberSyntax'],
children: [
{ name: 'propertyName', isToken: true, tokenKinds: ['IdentifierName', 'StringLiteral', 'NumericLiteral'] },
{ name: 'propertyName', type: 'IPropertyNameSyntax' },
{ name: 'questionToken', isToken: true, isOptional: true },
{ name: 'typeAnnotation', type: 'TypeAnnotationSyntax', isOptional: true }
],
@@ -1500,7 +1501,7 @@ var definitions = [
interfaces: ['IMemberDeclarationSyntax'],
children: [
{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken' },
{ name: 'propertyName', isToken: true, tokenKinds: ['IdentifierName', 'StringLiteral', 'NumericLiteral'] },
{ name: 'propertyName', type: 'IPropertyNameSyntax' },
{ name: 'callSignature', type: 'CallSignatureSyntax' },
{ name: 'block', type: 'BlockSyntax', isOptional: true },
{ name: 'semicolonToken', isToken: true, isOptional: true, excludeFromAST: true }
@@ -1510,11 +1511,11 @@ var definitions = [
{
name: 'GetAccessorSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IMemberDeclarationSyntax', 'IPropertyAssignmentSyntax'],
interfaces: ['IAccessorSyntax'],
children: [
{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken', isTypeScriptSpecific: true },
{ name: 'getKeyword', isToken: true, excludeFromAST: true },
{ name: 'propertyName', isToken: true, tokenKinds: ['IdentifierName', 'StringLiteral', 'NumericLiteral'] },
{ name: 'propertyName', type: 'IPropertyNameSyntax' },
{ name: 'callSignature', type: 'CallSignatureSyntax' },
{ name: 'block', type: 'BlockSyntax' }
]
@@ -1522,11 +1523,11 @@ var definitions = [
{
name: 'SetAccessorSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IMemberDeclarationSyntax', 'IPropertyAssignmentSyntax'],
interfaces: ['IAccessorSyntax'],
children: [
{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken', isTypeScriptSpecific: true },
{ name: 'setKeyword', isToken: true, excludeFromAST: true },
{ name: 'propertyName', isToken: true, tokenKinds: ['IdentifierName', 'StringLiteral', 'NumericLiteral'] },
{ name: 'propertyName', type: 'IPropertyNameSyntax' },
{ name: 'callSignature', type: 'CallSignatureSyntax' },
{ name: 'block', type: 'BlockSyntax' }
],
@@ -1713,7 +1714,7 @@ var definitions = [
name: 'EnumElementSyntax',
baseType: 'ISyntaxNode',
children: [
{ name: 'propertyName', isToken: true, tokenKinds: ['IdentifierName', 'StringLiteral', 'NumericLiteral'] },
{ name: 'propertyName', type: 'IPropertyNameSyntax' },
{ name: 'equalsValueClause', type: 'EqualsValueClauseSyntax', isOptional: true }
]
},
@@ -1739,12 +1740,22 @@ var definitions = [
{ name: 'closeBraceToken', isToken: true, excludeFromAST: true }
]
},
{
name: 'ComputedPropertyNameSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IPropertyNameSyntax'],
children: [
{ name: 'openBracketToken', isToken: true },
{ name: 'expression', type: 'IExpressionSyntax' },
{ name: 'closeBracketToken', isToken: true }
]
},
{
name: 'SimplePropertyAssignmentSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IPropertyAssignmentSyntax'],
children: [
{ name: 'propertyName', isToken: true, tokenKinds: ['IdentifierName', 'StringLiteral', 'NumericLiteral'] },
{ name: 'propertyName', type: 'IPropertyNameSyntax' },
{ name: 'colonToken', isToken: true, excludeFromAST: true },
{ name: 'expression', type: 'IExpressionSyntax' }
]
@@ -1754,7 +1765,7 @@ var definitions = [
baseType: 'ISyntaxNode',
interfaces: ['IPropertyAssignmentSyntax'],
children: [
{ name: 'propertyName', isToken: true, tokenKinds: ['IdentifierName', 'StringLiteral', 'NumericLiteral'] },
{ name: 'propertyName', type: 'IPropertyNameSyntax' },
{ name: 'callSignature', type: 'CallSignatureSyntax' },
{ name: 'block', type: 'BlockSyntax' }
]
@@ -1907,43 +1918,6 @@ function getSafeName(child) {
}
return child.name;
}
function generateBrands(definition, accessibility) {
var properties = "";
var types = [];
if (definition.interfaces) {
var ifaces = definition.interfaces.slice(0);
var i;
for (i = 0; i < ifaces.length; i++) {
var current = ifaces[i];
while (current !== undefined) {
if (!TypeScript.ArrayUtilities.contains(ifaces, current)) {
ifaces.push(current);
}
current = interfaces[current];
}
}
for (i = 0; i < ifaces.length; i++) {
var type = ifaces[i];
type = getStringWithoutSuffix(type);
if (isInterface(type)) {
type = "_" + type.substr(1, 1).toLowerCase() + type.substr(2) + "Brand";
}
types.push(type);
}
}
types.push("_syntaxNodeOrTokenBrand");
if (types.length > 0) {
properties += " ";
for (var i = 0; i < types.length; i++) {
if (accessibility) {
properties += " public ";
}
properties += types[i] + ": any;";
}
properties += "\r\n";
}
return properties;
}
function generateConstructorFunction(definition) {
var result = " export var " + definition.name + ": " + getNameWithoutSuffix(definition) + "Constructor = <any>function(data: number";
for (var i = 0; i < definition.children.length; i++) {
@@ -1982,7 +1956,20 @@ function generateConstructorFunction(definition) {
result += ";\r\n";
}
result += " };\r\n";
result += " " + definition.name + ".prototype.kind = function() { return SyntaxKind." + getNameWithoutSuffix(definition) + "; }\r\n";
result += " " + definition.name + ".prototype.kind = SyntaxKind." + getNameWithoutSuffix(definition) + ";\r\n";
result += " " + definition.name + ".prototype.childCount = " + definition.children.length + ";\r\n";
result += " " + definition.name + ".prototype.childAt = function(index: number): ISyntaxElement {\r\n";
if (definition.children.length) {
result += " switch (index) {\r\n";
for (var j = 0; j < definition.children.length; j++) {
result += " case " + j + ": return this." + definition.children[j].name + ";\r\n";
}
result += " }\r\n";
}
else {
result += " throw Errors.invalidOperation();\r\n";
}
result += " }\r\n";
return result;
}
function generateSyntaxInterfaces() {
@@ -2154,16 +2141,28 @@ function max(array, func) {
}
return max;
}
function generateUtilities() {
var result = "";
result += " var fixedWidthArray = [";
for (var i = 0; i <= TypeScript.SyntaxKind.LastFixedWidth; i++) {
if (i) {
result += ", ";
}
if (i < TypeScript.SyntaxKind.FirstFixedWidth) {
result += "0";
}
else {
result += TypeScript.SyntaxFacts.getText(i).length;
}
}
result += "];\r\n";
result += " function fixedWidthTokenLength(kind: SyntaxKind) {\r\n";
result += " return fixedWidthArray[kind];\r\n";
result += " }\r\n";
return result;
}
function generateScannerUtilities() {
var result = "///<reference path='references.ts' />\r\n" + "\r\n" + "module TypeScript {\r\n" + " export module ScannerUtilities {\r\n";
result += " export function fixedWidthTokenLength(kind: SyntaxKind) {\r\n";
result += " switch (kind) {\r\n";
for (var k = TypeScript.SyntaxKind.FirstFixedWidth; k <= TypeScript.SyntaxKind.LastFixedWidth; k++) {
result += " case SyntaxKind." + syntaxKindName(k) + ": return " + TypeScript.SyntaxFacts.getText(k).length + ";\r\n";
}
result += " default: throw new Error();\r\n";
result += " }\r\n";
result += " }\r\n\r\n";
var i;
var keywords = [];
for (i = TypeScript.SyntaxKind.FirstKeyword; i <= TypeScript.SyntaxKind.LastKeyword; i++) {
@@ -2202,7 +2201,7 @@ function generateVisitor() {
result += "module TypeScript {\r\n";
result += " export function visitNodeOrToken(visitor: ISyntaxVisitor, element: ISyntaxNodeOrToken): any {\r\n";
result += " if (element === undefined) { return undefined; }\r\n";
result += " switch (element.kind()) {\r\n";
result += " switch (element.kind) {\r\n";
for (var i = 0; i < definitions.length; i++) {
var definition = definitions[i];
result += " case SyntaxKind." + getNameWithoutSuffix(definition) + ": ";
@@ -2221,55 +2220,16 @@ function generateVisitor() {
result += "\r\n}";
return result;
}
function generateServicesUtilities() {
var result = "";
result += "module TypeScript {\r\n";
result += " export function childCount(element: ISyntaxElement): number {\r\n";
result += " if (isList(element)) { return (<ISyntaxNodeOrToken[]>element).length; }\r\n";
result += " switch (element.kind()) {\r\n";
for (var i = 0; i < definitions.length; i++) {
var definition = definitions[i];
result += " case SyntaxKind." + getNameWithoutSuffix(definition) + ": return " + definition.children.length + ";\r\n";
}
result += " default: return 0;\r\n";
result += " }\r\n";
result += " }\r\n\r\n";
for (var i = 0; i < definitions.length; i++) {
var definition = definitions[i];
result += " function " + camelCase(getNameWithoutSuffix(definition)) + "ChildAt(node: " + definition.name + ", index: number): ISyntaxElement {\r\n";
if (definition.children.length) {
result += " switch (index) {\r\n";
for (var j = 0; j < definition.children.length; j++) {
result += " case " + j + ": return node." + definition.children[j].name + ";\r\n";
}
result += " }\r\n";
}
else {
result += " throw Errors.invalidOperation();\r\n";
}
result += " }\r\n";
}
result += " export function childAt(element: ISyntaxElement, index: number): ISyntaxElement {\r\n";
result += " if (isList(element)) { return (<ISyntaxNodeOrToken[]>element)[index]; }\r\n";
result += " switch (element.kind()) {\r\n";
for (var i = 0; i < definitions.length; i++) {
var definition = definitions[i];
result += " case SyntaxKind." + getNameWithoutSuffix(definition) + ": return " + camelCase(getNameWithoutSuffix(definition)) + "ChildAt(<" + definition.name + ">element, index);\r\n";
}
result += " }\r\n";
result += " }\r\n";
result += "}";
return result;
}
var syntaxNodesConcrete = generateNodes();
var syntaxInterfaces = generateSyntaxInterfaces();
var walker = generateWalker();
var scannerUtilities = generateScannerUtilities();
var visitor = generateVisitor();
var servicesUtilities = generateServicesUtilities();
var utilities = generateUtilities();
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\syntaxNodes.concrete.generated.ts", syntaxNodesConcrete, false);
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\syntaxInterfaces.generated.ts", syntaxInterfaces, false);
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\syntaxWalker.generated.ts", walker, false);
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\scannerUtilities.generated.ts", scannerUtilities, false);
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\syntaxVisitor.generated.ts", visitor, false);
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\syntaxUtilities.generated.ts", servicesUtilities, false);
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\utilities.generated.ts", utilities, false);
//# sourceMappingURL=file:///C:/VSPro_1/src/typescript/public_cyrusn/src/services/syntax/SyntaxGenerator.js.map
File diff suppressed because one or more lines are too long
+21 -13
View File
@@ -235,7 +235,20 @@ module TypeScript.IncrementalParser {
!_oldSourceUnitCursor.isFinished();
}
function updateTokens(nodeOrToken: ISyntaxNodeOrToken): void {
function updateTokenPosition(token: ISyntaxToken): void {
// If we got a node or token, and we're past the range of edited text, then walk its
// constituent tokens, making sure all their positions are correct. We don't need to
// do this for the tokens before the edited range (since their positions couldn't have
// been affected by the edit), and we don't need to do this for the tokens in the
// edited range, as their positions will be correct when the underlying parser source
// creates them.
if (isPastChangeRange()) {
token.setFullStart(absolutePosition());
}
}
function updateNodePosition(node: ISyntaxNode): void {
// If we got a node or token, and we're past the range of edited text, then walk its
// constituent tokens, making sure all their positions are correct. We don't need to
// do this for the tokens before the edited range (since their positions couldn't have
@@ -246,18 +259,13 @@ module TypeScript.IncrementalParser {
if (isPastChangeRange()) {
var position = absolutePosition();
if (isToken(nodeOrToken)) {
(<ISyntaxToken>nodeOrToken).setFullStart(position);
}
else {
var tokens = getTokens(<ISyntaxNode>nodeOrToken);
var tokens = getTokens(node);
for (var i = 0, n = tokens.length; i < n; i++) {
var token = tokens[i];
token.setFullStart(position);
for (var i = 0, n = tokens.length; i < n; i++) {
var token = tokens[i];
token.setFullStart(position);
position += token.fullWidth();
}
position += token.fullWidth();
}
}
}
@@ -284,7 +292,7 @@ module TypeScript.IncrementalParser {
var node = tryGetNodeFromOldSourceUnit();
if (node) {
// Make sure the positions for the tokens in this node are correct.
updateTokens(node);
updateNodePosition(node);
return node;
}
}
@@ -298,7 +306,7 @@ module TypeScript.IncrementalParser {
var token = tryGetTokenFromOldSourceUnit();
if (token) {
// Make sure the token's position/text is correct.
updateTokens(token);
updateTokenPosition(token);
return token;
}
}
File diff suppressed because it is too large Load Diff
+22 -16
View File
@@ -20,7 +20,7 @@ module TypeScript.PrettyPrinter {
return 0;
}
if (lastToken(element1).kind() === SyntaxKind.CloseBraceToken) {
if (lastToken(element1).kind === SyntaxKind.CloseBraceToken) {
return 2;
}
@@ -35,12 +35,12 @@ module TypeScript.PrettyPrinter {
return 1;
}
private newLineCountBetweenStatements(element1: IClassElementSyntax, element2: IClassElementSyntax): number {
private newLineCountBetweenStatements(element1: IStatementSyntax, element2: IStatementSyntax): number {
if (!element1 || !element2) {
return 0;
}
if (lastToken(element1).kind() === SyntaxKind.CloseBraceToken) {
if (lastToken(element1).kind === SyntaxKind.CloseBraceToken) {
return 2;
}
@@ -353,7 +353,7 @@ module TypeScript.PrettyPrinter {
}
public visitVariableDeclarator(node: VariableDeclaratorSyntax): void {
this.appendToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
this.appendNode(node.equalsValueClause);
}
@@ -552,7 +552,7 @@ module TypeScript.PrettyPrinter {
public visitBinaryExpression(node: BinaryExpressionSyntax): void {
visitNodeOrToken(this, node.left);
if (node.operatorToken.kind() !== SyntaxKind.CommaToken) {
if (node.operatorToken.kind !== SyntaxKind.CommaToken) {
this.ensureSpace();
}
@@ -579,7 +579,7 @@ module TypeScript.PrettyPrinter {
}
public visitMethodSignature(node: MethodSignatureSyntax): void {
this.appendToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
this.appendToken(node.questionToken);
visitNodeOrToken(this, node.callSignature);
}
@@ -592,7 +592,7 @@ module TypeScript.PrettyPrinter {
}
public visitPropertySignature(node: PropertySignatureSyntax): void {
this.appendToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
this.appendToken(node.questionToken);
this.appendNode(node.typeAnnotation);
}
@@ -628,7 +628,7 @@ module TypeScript.PrettyPrinter {
}
private appendBlockOrStatement(node: IStatementSyntax): void {
if (node.kind() === SyntaxKind.Block) {
if (node.kind === SyntaxKind.Block) {
this.ensureSpace();
visitNodeOrToken(this, node);
}
@@ -654,7 +654,7 @@ module TypeScript.PrettyPrinter {
this.ensureNewLine();
this.appendToken(node.elseKeyword);
if (node.statement.kind() === SyntaxKind.IfStatement) {
if (node.statement.kind === SyntaxKind.IfStatement) {
this.ensureSpace();
visitNodeOrToken(this, node.statement);
}
@@ -684,7 +684,7 @@ module TypeScript.PrettyPrinter {
public visitMemberFunctionDeclaration(node: MemberFunctionDeclarationSyntax): void {
this.appendSpaceList(node.modifiers);
this.ensureSpace();
this.appendToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
visitNodeOrToken(this, node.callSignature);
this.appendBlockOrSemicolon(node.block, node.semicolonToken);
}
@@ -694,7 +694,7 @@ module TypeScript.PrettyPrinter {
this.ensureSpace();
this.appendToken(node.getKeyword);
this.ensureSpace();
this.appendToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
visitNodeOrToken(this, node.callSignature);
this.ensureSpace();
visitNodeOrToken(this, node.block);
@@ -705,7 +705,7 @@ module TypeScript.PrettyPrinter {
this.ensureSpace();
this.appendToken(node.setKeyword);
this.ensureSpace();
this.appendToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
visitNodeOrToken(this, node.callSignature)
this.ensureSpace();
visitNodeOrToken(this, node.block);
@@ -774,7 +774,7 @@ module TypeScript.PrettyPrinter {
}
private appendSwitchClauseStatements(node: ISwitchClauseSyntax): void {
if (childCount(node.statements) === 1 && childAt(node.statements, 0).kind() === SyntaxKind.Block) {
if (childCount(node.statements) === 1 && childAt(node.statements, 0).kind === SyntaxKind.Block) {
this.ensureSpace();
visitNodeOrToken(this, node.statements[0]);
}
@@ -895,7 +895,7 @@ module TypeScript.PrettyPrinter {
}
public visitEnumElement(node: EnumElementSyntax): void {
this.appendToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
this.ensureSpace();
this.appendNode(node.equalsValueClause);
}
@@ -926,15 +926,21 @@ module TypeScript.PrettyPrinter {
this.appendToken(node.closeBraceToken);
}
public visitComputedPropertyName(node: ComputedPropertyNameSyntax): void {
this.appendToken(node.openBracketToken);
visitNodeOrToken(this, node.expression);
this.appendToken(node.closeBracketToken);
}
public visitSimplePropertyAssignment(node: SimplePropertyAssignmentSyntax): void {
this.appendToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
this.appendToken(node.colonToken);
this.ensureSpace();
visitNodeOrToken(this, node.expression);
}
public visitFunctionPropertyAssignment(node: FunctionPropertyAssignmentSyntax): void {
this.appendToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
visitNodeOrToken(this, node.callSignature);
this.ensureSpace();
visitNodeOrToken(this, node.block);
-1
View File
@@ -28,7 +28,6 @@
///<reference path='syntaxTrivia.ts' />
///<reference path='syntaxTriviaList.ts' />
///<reference path='syntaxUtilities.ts' />
///<reference path='syntaxUtilities.generated.ts' />
///<reference path='syntaxVisitor.generated.ts' />
///<reference path='syntaxWalker.generated.ts' />
+77 -215
View File
@@ -60,84 +60,52 @@ module TypeScript.Scanner {
// This gives us 23bit for width (or 8MB of width which should be enough for any codebase).
enum ScannerConstants {
LargeTokenFullStartShift = 4,
LargeTokenFullWidthShift = 7,
LargeTokenLeadingTriviaBitMask = 0x01, // 00000001
LargeTokenLeadingCommentBitMask = 0x02, // 00000010
LargeTokenTrailingTriviaBitMask = 0x04, // 00000100
LargeTokenTrailingCommentBitMask = 0x08, // 00001000
LargeTokenTriviaBitMask = 0x0F, // 00001111
LargeTokenFullWidthShift = 6,
LargeTokenLeadingTriviaShift = 3,
FixedWidthTokenFullStartShift = 7,
FixedWidthTokenMaxFullStart = 0x7FFFFF, // 23 ones.
WhitespaceTrivia = 0x01, // 00000001
NewlineTrivia = 0x02, // 00000010
CommentTrivia = 0x04, // 00000100
TriviaMask = 0x07, // 00000111
SmallTokenFullWidthShift = 7,
SmallTokenFullStartShift = 12,
SmallTokenMaxFullStart = 0x3FFFF, // 18 ones.
SmallTokenMaxFullWidth = 0x1F, // 5 ones
SmallTokenFullWidthMask = 0x1F, // 00011111
KindMask = 0x7F, // 01111111
IsVariableWidthMask = 0x80, // 10000000
KindMask = 0x7F, // 01111111
IsVariableWidthMask = 0x80, // 10000000
}
// Make sure our math works for packing/unpacking large fullStarts.
Debug.assert(largeTokenUnpackFullStart(largeTokenPackFullStartAndInfo(1 << 26, 3)) === (1 << 26));
Debug.assert(largeTokenUnpackFullStart(largeTokenPackFullStartAndInfo(3 << 25, 1)) === (3 << 25));
Debug.assert(largeTokenUnpackFullStart(largeTokenPackFullStartAndInfo(10 << 23, 2)) === (10 << 23));
function fixedWidthTokenPackData(fullStart: number, kind: SyntaxKind) {
return (fullStart << ScannerConstants.FixedWidthTokenFullStartShift) | kind;
function largeTokenPackData(fullWidth: number, leadingTriviaInfo: number, trailingTriviaInfo: number) {
return (fullWidth << ScannerConstants.LargeTokenFullWidthShift) | (leadingTriviaInfo << ScannerConstants.LargeTokenLeadingTriviaShift) | trailingTriviaInfo;
}
function fixedWidthTokenUnpackFullStart(packedData: number) {
return packedData >> ScannerConstants.FixedWidthTokenFullStartShift;
function largeTokenUnpackFullWidth(packedFullWidthAndInfo: number): number {
return packedFullWidthAndInfo >> ScannerConstants.LargeTokenFullWidthShift;
}
function smallTokenPackData(fullStart: number, fullWidth: number, kind: SyntaxKind) {
return (fullStart << ScannerConstants.SmallTokenFullStartShift) |
(fullWidth << ScannerConstants.SmallTokenFullWidthShift) |
kind;
function largeTokenUnpackLeadingTriviaInfo(packedFullWidthAndInfo: number): number {
return (packedFullWidthAndInfo >> ScannerConstants.LargeTokenLeadingTriviaShift) & ScannerConstants.TriviaMask;
}
function smallTokenUnpackFullWidth(packedData: number): SyntaxKind {
return (packedData >> ScannerConstants.SmallTokenFullWidthShift) & ScannerConstants.SmallTokenFullWidthMask;
}
function smallTokenUnpackFullStart(packedData: number): number {
return packedData >> ScannerConstants.SmallTokenFullStartShift;
}
function largeTokenPackFullStartAndInfo(fullStart: number, triviaInfo: number): number {
return (fullStart << ScannerConstants.LargeTokenFullStartShift) | triviaInfo;
}
function largeTokenUnpackFullWidth(packedFullWidthAndKind: number) {
return packedFullWidthAndKind >> ScannerConstants.LargeTokenFullWidthShift;
}
function largeTokenUnpackFullStart(packedFullStartAndInfo: number): number {
return packedFullStartAndInfo >> ScannerConstants.LargeTokenFullStartShift;
function largeTokenUnpackTrailingTriviaInfo(packedFullWidthAndInfo: number): number {
return packedFullWidthAndInfo & ScannerConstants.TriviaMask;
}
function largeTokenUnpackHasLeadingTrivia(packed: number): boolean {
return (packed & ScannerConstants.LargeTokenLeadingTriviaBitMask) !== 0;
return largeTokenUnpackLeadingTriviaInfo(packed) !== 0;
}
function largeTokenUnpackHasTrailingTrivia(packed: number): boolean {
return (packed & ScannerConstants.LargeTokenTrailingTriviaBitMask) !== 0;
return largeTokenUnpackTrailingTriviaInfo(packed) !== 0;
}
function hasComment(info: number) {
return (info & ScannerConstants.CommentTrivia) !== 0;
}
function largeTokenUnpackHasLeadingComment(packed: number): boolean {
return (packed & ScannerConstants.LargeTokenLeadingCommentBitMask) !== 0;
return hasComment(largeTokenUnpackLeadingTriviaInfo(packed));
}
function largeTokenUnpackHasTrailingComment(packed: number): boolean {
return (packed & ScannerConstants.LargeTokenTrailingCommentBitMask) !== 0;
}
function largeTokenUnpackTriviaInfo(packed: number): number {
return packed & ScannerConstants.LargeTokenTriviaBitMask;
return hasComment(largeTokenUnpackTrailingTriviaInfo(packed));
}
var isKeywordStartCharacter: number[] = ArrayUtilities.createArray<number>(CharacterCodes.maxAsciiCharacter, 0);
@@ -166,7 +134,7 @@ module TypeScript.Scanner {
// These tokens are contextually created based on parsing decisions. We can't reuse
// them in incremental scenarios as we may be in a context where the parser would not
// create them.
switch (token.kind()) {
switch (token.kind) {
// Created by the parser when it sees / or /= in a location where it needs an expression.
case SyntaxKind.RegularExpressionLiteral:
@@ -251,55 +219,57 @@ module TypeScript.Scanner {
}
class FixedWidthTokenWithNoTrivia implements ISyntaxToken {
public _primaryExpressionBrand: any; public _memberExpressionBrand: any; public _leftHandSideExpressionBrand: any; public _postfixExpressionBrand: any; public _unaryExpressionBrand: any; public _expressionBrand: any; public _typeBrand: any; public _syntaxNodeOrTokenBrand: any;
public _primaryExpressionBrand: any; public _memberExpressionBrand: any; public _leftHandSideExpressionBrand: any; public _postfixExpressionBrand: any; public _unaryExpressionBrand: any; public _expressionBrand: any; public _typeBrand: any; public _nameBrand: any; public _propertyAssignmentBrand: any; public _propertyNameBrand: any;
public parent: ISyntaxElement;
public childCount: number;
constructor(private _packedData: number) {
constructor(private _fullStart: number, public kind: SyntaxKind) {
}
public setFullStart(fullStart: number): void {
this._packedData = fixedWidthTokenPackData(fullStart, this.kind());
this._fullStart = fullStart;
}
public childCount() { return 0 }
public childAt(index: number): ISyntaxElement { throw Errors.invalidOperation() }
public accept(visitor: ISyntaxVisitor): any { return visitor.visitToken(this) }
public isIncrementallyUnusable(): boolean { return false; }
public isKeywordConvertedToIdentifier(): boolean { return false; }
public hasSkippedToken(): boolean { return false; }
public fullText(): string { return SyntaxFacts.getText(this.kind()); }
public fullText(): string { return SyntaxFacts.getText(this.kind); }
public text(): string { return this.fullText(); }
public leadingTrivia(): ISyntaxTriviaList { return Syntax.emptyTriviaList; }
public trailingTrivia(): ISyntaxTriviaList { return Syntax.emptyTriviaList; }
public leadingTriviaWidth(): number { return 0; }
public trailingTriviaWidth(): number { return 0; }
public kind(): SyntaxKind { return this._packedData & ScannerConstants.KindMask; }
public fullWidth(): number { return fixedWidthTokenLength(this._packedData & ScannerConstants.KindMask); }
public fullStart(): number { return fixedWidthTokenUnpackFullStart(this._packedData); }
public fullWidth(): number { return fixedWidthTokenLength(this.kind); }
public fullStart(): number { return this._fullStart; }
public hasLeadingTrivia(): boolean { return false; }
public hasTrailingTrivia(): boolean { return false; }
public hasLeadingComment(): boolean { return false; }
public hasTrailingComment(): boolean { return false; }
public clone(): ISyntaxToken { return new FixedWidthTokenWithNoTrivia(this._packedData); }
public clone(): ISyntaxToken { return new FixedWidthTokenWithNoTrivia(this._fullStart, this.kind); }
}
FixedWidthTokenWithNoTrivia.prototype.childCount = 0;
class LargeScannerToken implements ISyntaxToken {
public _primaryExpressionBrand: any; public _memberExpressionBrand: any; public _leftHandSideExpressionBrand: any; public _postfixExpressionBrand: any; public _unaryExpressionBrand: any; public _expressionBrand: any; public _typeBrand: any; public _syntaxNodeOrTokenBrand: any;
public _primaryExpressionBrand: any; public _memberExpressionBrand: any; public _leftHandSideExpressionBrand: any; public _postfixExpressionBrand: any; public _unaryExpressionBrand: any; public _expressionBrand: any; public _typeBrand: any; public _nameBrand: any; public _propertyAssignmentBrand: any; public _propertyNameBrand: any;
public parent: ISyntaxElement;
public childCount: number;
private cachedText: string;
constructor(private _packedFullStartAndInfo: number, private _packedFullWidthAndKind: number, cachedText: string) {
constructor(private _fullStart: number, public kind: SyntaxKind, private _packedFullWidthAndInfo: number, cachedText: string) {
if (cachedText !== undefined) {
this.cachedText = cachedText;
}
}
public setFullStart(fullStart: number): void {
this._packedFullStartAndInfo = largeTokenPackFullStartAndInfo(fullStart,
largeTokenUnpackTriviaInfo(this._packedFullStartAndInfo));
this._fullStart = fullStart;
}
public childCount() { return 0 }
public childAt(index: number): ISyntaxElement { throw Errors.invalidOperation() }
public accept(visitor: ISyntaxVisitor): any { return visitor.visitToken(this) }
@@ -319,7 +289,7 @@ module TypeScript.Scanner {
public text(): string {
var cachedText = this.cachedText;
return cachedText !== undefined ? cachedText : SyntaxFacts.getText(this.kind());
return cachedText !== undefined ? cachedText : SyntaxFacts.getText(this.kind);
}
public leadingTrivia(text?: ISimpleText): ISyntaxTriviaList { return leadingTrivia(this, this.syntaxTreeText(text)); }
@@ -333,15 +303,15 @@ module TypeScript.Scanner {
return trailingTriviaWidth(this, this.syntaxTreeText(text));
}
public kind(): SyntaxKind { return this._packedFullWidthAndKind & ScannerConstants.KindMask; }
public fullWidth(): number { return largeTokenUnpackFullWidth(this._packedFullWidthAndKind); }
public fullStart(): number { return largeTokenUnpackFullStart(this._packedFullStartAndInfo); }
public hasLeadingTrivia(): boolean { return largeTokenUnpackHasLeadingTrivia(this._packedFullStartAndInfo); }
public hasTrailingTrivia(): boolean { return largeTokenUnpackHasTrailingTrivia(this._packedFullStartAndInfo); }
public hasLeadingComment(): boolean { return largeTokenUnpackHasLeadingComment(this._packedFullStartAndInfo); }
public hasTrailingComment(): boolean { return largeTokenUnpackHasTrailingComment(this._packedFullStartAndInfo); }
public clone(): ISyntaxToken { return new LargeScannerToken(this._packedFullStartAndInfo, this._packedFullWidthAndKind, this.cachedText); }
public fullWidth(): number { return largeTokenUnpackFullWidth(this._packedFullWidthAndInfo); }
public fullStart(): number { return this._fullStart; }
public hasLeadingTrivia(): boolean { return largeTokenUnpackHasLeadingTrivia(this._packedFullWidthAndInfo); }
public hasTrailingTrivia(): boolean { return largeTokenUnpackHasTrailingTrivia(this._packedFullWidthAndInfo); }
public hasLeadingComment(): boolean { return largeTokenUnpackHasLeadingComment(this._packedFullWidthAndInfo); }
public hasTrailingComment(): boolean { return largeTokenUnpackHasTrailingComment(this._packedFullWidthAndInfo); }
public clone(): ISyntaxToken { return new LargeScannerToken(this._fullStart, this.kind, this._packedFullWidthAndInfo, this.cachedText); }
}
LargeScannerToken.prototype.childCount = 0;
export interface DiagnosticCallback {
(position: number, width: number, key: string, arguments: any[]): void;
@@ -381,12 +351,13 @@ module TypeScript.Scanner {
}
function reset(_text: ISimpleText, _start: number, _end: number) {
Debug.assert(_start <= _text.length(), "Token's start was not within the bounds of text: " + _start + " - [0, " + _text.length() + ")");
Debug.assert(_end <= _text.length(), "Token's end was not within the bounds of text: " + _end + " - [0, " + _text.length() + ")");
var textLength = _text.length();
Debug.assert(_start <= textLength, "Token's start was not within the bounds of text.");
Debug.assert(_end <= textLength, "Token's end was not within the bounds of text:");
if (!str || text !== _text) {
text = _text;
str = _text.substr(0, _text.length());
str = _text.substr(0, textLength);
}
start = _start;
@@ -413,20 +384,14 @@ module TypeScript.Scanner {
((kindAndIsVariableWidth & ScannerConstants.IsVariableWidthMask) === 0);
if (isFixedWidth &&
leadingTriviaInfo === 0 && trailingTriviaInfo === 0 &&
fullStart <= ScannerConstants.FixedWidthTokenMaxFullStart &&
(kindAndIsVariableWidth & ScannerConstants.IsVariableWidthMask) === 0) {
leadingTriviaInfo === 0 && trailingTriviaInfo === 0) {
return new FixedWidthTokenWithNoTrivia((fullStart << ScannerConstants.FixedWidthTokenFullStartShift) | kind);
return new FixedWidthTokenWithNoTrivia(fullStart, kind);
}
else {
// inline the packing logic for perf.
var packedFullStartAndTriviaInfo = (fullStart << ScannerConstants.LargeTokenFullStartShift) |
leadingTriviaInfo | (trailingTriviaInfo << 2);
var packedFullWidthAndKind = (fullWidth << ScannerConstants.LargeTokenFullWidthShift) | kind;
var packedFullWidthAndInfo = largeTokenPackData(fullWidth, leadingTriviaInfo, trailingTriviaInfo);
var cachedText = isFixedWidth ? undefined : text.substr(start, end - start);
return new LargeScannerToken(packedFullStartAndTriviaInfo, packedFullWidthAndKind, cachedText);
return new LargeScannerToken(fullStart, kind, packedFullWidthAndInfo, cachedText);
}
}
@@ -536,7 +501,7 @@ module TypeScript.Scanner {
case CharacterCodes.formFeed:
index++;
// we have trivia
result |= 1;
result |= ScannerConstants.WhitespaceTrivia;
continue;
case CharacterCodes.carriageReturn:
@@ -545,10 +510,12 @@ module TypeScript.Scanner {
}
// fall through.
case CharacterCodes.lineFeed:
case CharacterCodes.paragraphSeparator:
case CharacterCodes.lineSeparator:
index++;
// we have trivia
result |= 1;
result |= ScannerConstants.NewlineTrivia;
// If we're consuming leading trivia, then we will continue consuming more
// trivia (including newlines) up to the first token we see. If we're
@@ -564,14 +531,14 @@ module TypeScript.Scanner {
var ch2 = str.charCodeAt(index + 1);
if (ch2 === CharacterCodes.slash) {
// we have a comment, and we have trivia
result |= 3;
result |= ScannerConstants.CommentTrivia;
skipSingleLineCommentTrivia();
continue;
}
if (ch2 === CharacterCodes.asterisk) {
// we have a comment, and we have trivia
result |= 3;
result |= ScannerConstants.CommentTrivia;
skipMultiLineCommentTrivia();
continue;
}
@@ -581,8 +548,8 @@ module TypeScript.Scanner {
return result;
default:
if (ch > CharacterCodes.maxAsciiCharacter && slowScanTriviaInfo(ch)) {
result |= 1;
if (ch > CharacterCodes.maxAsciiCharacter && slowScanWhitespaceTriviaInfo(ch)) {
result |= ScannerConstants.WhitespaceTrivia;
continue;
}
@@ -593,7 +560,7 @@ module TypeScript.Scanner {
return result;
}
function slowScanTriviaInfo(ch: number): boolean {
function slowScanWhitespaceTriviaInfo(ch: number): boolean {
switch (ch) {
case CharacterCodes.nonBreakingSpace:
case CharacterCodes.enQuad:
@@ -611,8 +578,6 @@ module TypeScript.Scanner {
case CharacterCodes.narrowNoBreakSpace:
case CharacterCodes.ideographicSpace:
case CharacterCodes.byteOrderMark:
case CharacterCodes.paragraphSeparator:
case CharacterCodes.lineSeparator:
index++;
return true;
@@ -1685,11 +1650,14 @@ module TypeScript.Scanner {
function resetToPosition(absolutePosition: number): void {
Debug.assert(absolutePosition <= text.length(), "Trying to set the position outside the bounds of the text!");
var resetBackward = absolutePosition <= _absolutePosition;
_absolutePosition = absolutePosition;
// First, remove any diagnostics that came after this position.
removeDiagnosticsOnOrAfterPosition(absolutePosition);
if (resetBackward) {
// First, remove any diagnostics that came after this position.
removeDiagnosticsOnOrAfterPosition(absolutePosition);
}
// Now, tell our sliding window to throw away all tokens after this position as well.
slidingWindow.disgardAllItemsFromCurrentIndexOnwards();
@@ -1701,7 +1669,7 @@ module TypeScript.Scanner {
function currentContextualToken(): ISyntaxToken {
// We better be on a / or > token right now.
// Debug.assert(SyntaxFacts.isAnyDivideToken(currentToken().kind()));
// Debug.assert(SyntaxFacts.isAnyDivideToken(currentToken().kind));
// First, we're going to rewind all our data to the point where this / or /= token started.
// That's because if it does turn out to be a regular expression, then any tokens or token
@@ -1721,7 +1689,7 @@ module TypeScript.Scanner {
// We have better gotten some sort of regex token. Otherwise, something *very* wrong has
// occurred.
// Debug.assert(SyntaxFacts.isAnyDivideOrRegularExpressionToken(token.kind()));
// Debug.assert(SyntaxFacts.isAnyDivideOrRegularExpressionToken(token.kind));
return token;
}
@@ -1746,114 +1714,8 @@ module TypeScript.Scanner {
};
}
var fixedWidthArray = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 4, 5, 8, 8, 7, 6, 2, 4, 5, 7, 3, 8, 2, 2, 10, 3, 4, 6, 6, 4, 5, 4, 3, 6, 3, 4, 5, 4, 5, 5, 4, 6, 7, 6, 5, 10, 9, 3, 7, 7, 9, 6, 6, 5, 3, 7, 11, 7, 3, 6, 7, 6, 3, 6, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 1, 1, 1, 1, 2, 2, 2, 2, 3, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 2, 2, 2, 1, 2];
function fixedWidthTokenLength(kind: SyntaxKind) {
switch (kind) {
case SyntaxKind.BreakKeyword: return 5;
case SyntaxKind.CaseKeyword: return 4;
case SyntaxKind.CatchKeyword: return 5;
case SyntaxKind.ContinueKeyword: return 8;
case SyntaxKind.DebuggerKeyword: return 8;
case SyntaxKind.DefaultKeyword: return 7;
case SyntaxKind.DeleteKeyword: return 6;
case SyntaxKind.DoKeyword: return 2;
case SyntaxKind.ElseKeyword: return 4;
case SyntaxKind.FalseKeyword: return 5;
case SyntaxKind.FinallyKeyword: return 7;
case SyntaxKind.ForKeyword: return 3;
case SyntaxKind.FunctionKeyword: return 8;
case SyntaxKind.IfKeyword: return 2;
case SyntaxKind.InKeyword: return 2;
case SyntaxKind.InstanceOfKeyword: return 10;
case SyntaxKind.NewKeyword: return 3;
case SyntaxKind.NullKeyword: return 4;
case SyntaxKind.ReturnKeyword: return 6;
case SyntaxKind.SwitchKeyword: return 6;
case SyntaxKind.ThisKeyword: return 4;
case SyntaxKind.ThrowKeyword: return 5;
case SyntaxKind.TrueKeyword: return 4;
case SyntaxKind.TryKeyword: return 3;
case SyntaxKind.TypeOfKeyword: return 6;
case SyntaxKind.VarKeyword: return 3;
case SyntaxKind.VoidKeyword: return 4;
case SyntaxKind.WhileKeyword: return 5;
case SyntaxKind.WithKeyword: return 4;
case SyntaxKind.ClassKeyword: return 5;
case SyntaxKind.ConstKeyword: return 5;
case SyntaxKind.EnumKeyword: return 4;
case SyntaxKind.ExportKeyword: return 6;
case SyntaxKind.ExtendsKeyword: return 7;
case SyntaxKind.ImportKeyword: return 6;
case SyntaxKind.SuperKeyword: return 5;
case SyntaxKind.ImplementsKeyword: return 10;
case SyntaxKind.InterfaceKeyword: return 9;
case SyntaxKind.LetKeyword: return 3;
case SyntaxKind.PackageKeyword: return 7;
case SyntaxKind.PrivateKeyword: return 7;
case SyntaxKind.ProtectedKeyword: return 9;
case SyntaxKind.PublicKeyword: return 6;
case SyntaxKind.StaticKeyword: return 6;
case SyntaxKind.YieldKeyword: return 5;
case SyntaxKind.AnyKeyword: return 3;
case SyntaxKind.BooleanKeyword: return 7;
case SyntaxKind.ConstructorKeyword: return 11;
case SyntaxKind.DeclareKeyword: return 7;
case SyntaxKind.GetKeyword: return 3;
case SyntaxKind.ModuleKeyword: return 6;
case SyntaxKind.RequireKeyword: return 7;
case SyntaxKind.NumberKeyword: return 6;
case SyntaxKind.SetKeyword: return 3;
case SyntaxKind.StringKeyword: return 6;
case SyntaxKind.OpenBraceToken: return 1;
case SyntaxKind.CloseBraceToken: return 1;
case SyntaxKind.OpenParenToken: return 1;
case SyntaxKind.CloseParenToken: return 1;
case SyntaxKind.OpenBracketToken: return 1;
case SyntaxKind.CloseBracketToken: return 1;
case SyntaxKind.DotToken: return 1;
case SyntaxKind.DotDotDotToken: return 3;
case SyntaxKind.SemicolonToken: return 1;
case SyntaxKind.CommaToken: return 1;
case SyntaxKind.LessThanToken: return 1;
case SyntaxKind.GreaterThanToken: return 1;
case SyntaxKind.LessThanEqualsToken: return 2;
case SyntaxKind.GreaterThanEqualsToken: return 2;
case SyntaxKind.EqualsEqualsToken: return 2;
case SyntaxKind.EqualsGreaterThanToken: return 2;
case SyntaxKind.ExclamationEqualsToken: return 2;
case SyntaxKind.EqualsEqualsEqualsToken: return 3;
case SyntaxKind.ExclamationEqualsEqualsToken: return 3;
case SyntaxKind.PlusToken: return 1;
case SyntaxKind.MinusToken: return 1;
case SyntaxKind.AsteriskToken: return 1;
case SyntaxKind.PercentToken: return 1;
case SyntaxKind.PlusPlusToken: return 2;
case SyntaxKind.MinusMinusToken: return 2;
case SyntaxKind.LessThanLessThanToken: return 2;
case SyntaxKind.GreaterThanGreaterThanToken: return 2;
case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: return 3;
case SyntaxKind.AmpersandToken: return 1;
case SyntaxKind.BarToken: return 1;
case SyntaxKind.CaretToken: return 1;
case SyntaxKind.ExclamationToken: return 1;
case SyntaxKind.TildeToken: return 1;
case SyntaxKind.AmpersandAmpersandToken: return 2;
case SyntaxKind.BarBarToken: return 2;
case SyntaxKind.QuestionToken: return 1;
case SyntaxKind.ColonToken: return 1;
case SyntaxKind.EqualsToken: return 1;
case SyntaxKind.PlusEqualsToken: return 2;
case SyntaxKind.MinusEqualsToken: return 2;
case SyntaxKind.AsteriskEqualsToken: return 2;
case SyntaxKind.PercentEqualsToken: return 2;
case SyntaxKind.LessThanLessThanEqualsToken: return 3;
case SyntaxKind.GreaterThanGreaterThanEqualsToken: return 3;
case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: return 4;
case SyntaxKind.AmpersandEqualsToken: return 2;
case SyntaxKind.BarEqualsToken: return 2;
case SyntaxKind.CaretEqualsToken: return 2;
case SyntaxKind.SlashToken: return 1;
case SyntaxKind.SlashEqualsToken: return 2;
default: throw new Error();
}
return fixedWidthArray[kind];
}
}
@@ -2,117 +2,6 @@
module TypeScript {
export module ScannerUtilities {
export function fixedWidthTokenLength(kind: SyntaxKind) {
switch (kind) {
case SyntaxKind.BreakKeyword: return 5;
case SyntaxKind.CaseKeyword: return 4;
case SyntaxKind.CatchKeyword: return 5;
case SyntaxKind.ContinueKeyword: return 8;
case SyntaxKind.DebuggerKeyword: return 8;
case SyntaxKind.DefaultKeyword: return 7;
case SyntaxKind.DeleteKeyword: return 6;
case SyntaxKind.DoKeyword: return 2;
case SyntaxKind.ElseKeyword: return 4;
case SyntaxKind.FalseKeyword: return 5;
case SyntaxKind.FinallyKeyword: return 7;
case SyntaxKind.ForKeyword: return 3;
case SyntaxKind.FunctionKeyword: return 8;
case SyntaxKind.IfKeyword: return 2;
case SyntaxKind.InKeyword: return 2;
case SyntaxKind.InstanceOfKeyword: return 10;
case SyntaxKind.NewKeyword: return 3;
case SyntaxKind.NullKeyword: return 4;
case SyntaxKind.ReturnKeyword: return 6;
case SyntaxKind.SwitchKeyword: return 6;
case SyntaxKind.ThisKeyword: return 4;
case SyntaxKind.ThrowKeyword: return 5;
case SyntaxKind.TrueKeyword: return 4;
case SyntaxKind.TryKeyword: return 3;
case SyntaxKind.TypeOfKeyword: return 6;
case SyntaxKind.VarKeyword: return 3;
case SyntaxKind.VoidKeyword: return 4;
case SyntaxKind.WhileKeyword: return 5;
case SyntaxKind.WithKeyword: return 4;
case SyntaxKind.ClassKeyword: return 5;
case SyntaxKind.ConstKeyword: return 5;
case SyntaxKind.EnumKeyword: return 4;
case SyntaxKind.ExportKeyword: return 6;
case SyntaxKind.ExtendsKeyword: return 7;
case SyntaxKind.ImportKeyword: return 6;
case SyntaxKind.SuperKeyword: return 5;
case SyntaxKind.ImplementsKeyword: return 10;
case SyntaxKind.InterfaceKeyword: return 9;
case SyntaxKind.LetKeyword: return 3;
case SyntaxKind.PackageKeyword: return 7;
case SyntaxKind.PrivateKeyword: return 7;
case SyntaxKind.ProtectedKeyword: return 9;
case SyntaxKind.PublicKeyword: return 6;
case SyntaxKind.StaticKeyword: return 6;
case SyntaxKind.YieldKeyword: return 5;
case SyntaxKind.AnyKeyword: return 3;
case SyntaxKind.BooleanKeyword: return 7;
case SyntaxKind.ConstructorKeyword: return 11;
case SyntaxKind.DeclareKeyword: return 7;
case SyntaxKind.GetKeyword: return 3;
case SyntaxKind.ModuleKeyword: return 6;
case SyntaxKind.RequireKeyword: return 7;
case SyntaxKind.NumberKeyword: return 6;
case SyntaxKind.SetKeyword: return 3;
case SyntaxKind.StringKeyword: return 6;
case SyntaxKind.OpenBraceToken: return 1;
case SyntaxKind.CloseBraceToken: return 1;
case SyntaxKind.OpenParenToken: return 1;
case SyntaxKind.CloseParenToken: return 1;
case SyntaxKind.OpenBracketToken: return 1;
case SyntaxKind.CloseBracketToken: return 1;
case SyntaxKind.DotToken: return 1;
case SyntaxKind.DotDotDotToken: return 3;
case SyntaxKind.SemicolonToken: return 1;
case SyntaxKind.CommaToken: return 1;
case SyntaxKind.LessThanToken: return 1;
case SyntaxKind.GreaterThanToken: return 1;
case SyntaxKind.LessThanEqualsToken: return 2;
case SyntaxKind.GreaterThanEqualsToken: return 2;
case SyntaxKind.EqualsEqualsToken: return 2;
case SyntaxKind.EqualsGreaterThanToken: return 2;
case SyntaxKind.ExclamationEqualsToken: return 2;
case SyntaxKind.EqualsEqualsEqualsToken: return 3;
case SyntaxKind.ExclamationEqualsEqualsToken: return 3;
case SyntaxKind.PlusToken: return 1;
case SyntaxKind.MinusToken: return 1;
case SyntaxKind.AsteriskToken: return 1;
case SyntaxKind.PercentToken: return 1;
case SyntaxKind.PlusPlusToken: return 2;
case SyntaxKind.MinusMinusToken: return 2;
case SyntaxKind.LessThanLessThanToken: return 2;
case SyntaxKind.GreaterThanGreaterThanToken: return 2;
case SyntaxKind.GreaterThanGreaterThanGreaterThanToken: return 3;
case SyntaxKind.AmpersandToken: return 1;
case SyntaxKind.BarToken: return 1;
case SyntaxKind.CaretToken: return 1;
case SyntaxKind.ExclamationToken: return 1;
case SyntaxKind.TildeToken: return 1;
case SyntaxKind.AmpersandAmpersandToken: return 2;
case SyntaxKind.BarBarToken: return 2;
case SyntaxKind.QuestionToken: return 1;
case SyntaxKind.ColonToken: return 1;
case SyntaxKind.EqualsToken: return 1;
case SyntaxKind.PlusEqualsToken: return 2;
case SyntaxKind.MinusEqualsToken: return 2;
case SyntaxKind.AsteriskEqualsToken: return 2;
case SyntaxKind.PercentEqualsToken: return 2;
case SyntaxKind.LessThanLessThanEqualsToken: return 3;
case SyntaxKind.GreaterThanGreaterThanEqualsToken: return 3;
case SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken: return 4;
case SyntaxKind.AmpersandEqualsToken: return 2;
case SyntaxKind.BarEqualsToken: return 2;
case SyntaxKind.CaretEqualsToken: return 2;
case SyntaxKind.SlashToken: return 1;
case SyntaxKind.SlashEqualsToken: return 2;
default: throw new Error();
}
}
export function identifierKind(str: string, start: number, length: number): SyntaxKind {
switch (length) {
case 2: // do, if, in
+8 -8
View File
@@ -9,7 +9,7 @@ module TypeScript.Syntax {
if (isToken(child)) {
var token = <ISyntaxToken>child;
// If a token is skipped, return true. Or if it is a missing token. The only empty token that is not missing is EOF
if (token.hasSkippedToken() || (width(token) === 0 && token.kind() !== SyntaxKind.EndOfFileToken)) {
if (token.hasSkippedToken() || (width(token) === 0 && token.kind !== SyntaxKind.EndOfFileToken)) {
return true;
}
}
@@ -19,7 +19,7 @@ module TypeScript.Syntax {
}
export function isUnterminatedStringLiteral(token: ISyntaxToken): boolean {
if (token && token.kind() === SyntaxKind.StringLiteral) {
if (token && token.kind === SyntaxKind.StringLiteral) {
var text = token.text();
return text.length < 2 || text.charCodeAt(text.length - 1) !== text.charCodeAt(0);
}
@@ -55,7 +55,7 @@ module TypeScript.Syntax {
var triviaList: ISyntaxTriviaList = undefined;
var lastTriviaBeforeToken: ISyntaxTrivia = undefined;
if (positionedToken.kind() === SyntaxKind.EndOfFileToken) {
if (positionedToken.kind === SyntaxKind.EndOfFileToken) {
// Check if the trivia is leading on the EndOfFile token
if (positionedToken.hasLeadingTrivia()) {
triviaList = positionedToken.leadingTrivia();
@@ -106,14 +106,14 @@ module TypeScript.Syntax {
var positionedToken = findToken(sourceUnit, position);
if (positionedToken) {
if (positionedToken.kind() === SyntaxKind.EndOfFileToken) {
if (positionedToken.kind === SyntaxKind.EndOfFileToken) {
// EndOfFile token, enusre it did not follow an unterminated string literal
positionedToken = previousToken(positionedToken);
return positionedToken && positionedToken.trailingTriviaWidth() === 0 && isUnterminatedStringLiteral(positionedToken);
}
else if (position > start(positionedToken)) {
// Ensure position falls enterily within the literal if it is terminated, or the line if it is not
return (position < end(positionedToken) && (positionedToken.kind() === TypeScript.SyntaxKind.StringLiteral || positionedToken.kind() === TypeScript.SyntaxKind.RegularExpressionLiteral)) ||
return (position < end(positionedToken) && (positionedToken.kind === TypeScript.SyntaxKind.StringLiteral || positionedToken.kind === TypeScript.SyntaxKind.RegularExpressionLiteral)) ||
(position <= end(positionedToken) && isUnterminatedStringLiteral(positionedToken));
}
}
@@ -123,7 +123,7 @@ module TypeScript.Syntax {
export function getAncestorOfKind(positionedToken: ISyntaxElement, kind: SyntaxKind): ISyntaxElement {
while (positionedToken && positionedToken.parent) {
if (positionedToken.parent.kind() === kind) {
if (positionedToken.parent.kind === kind) {
return positionedToken.parent;
}
@@ -139,10 +139,10 @@ module TypeScript.Syntax {
export function isIntegerLiteral(expression: IExpressionSyntax): boolean {
if (expression) {
switch (expression.kind()) {
switch (expression.kind) {
case SyntaxKind.PrefixUnaryExpression:
var prefixExpr = <PrefixUnaryExpressionSyntax>expression;
if (prefixExpr.operatorToken.kind() == SyntaxKind.PlusToken || prefixExpr.operatorToken.kind() === SyntaxKind.MinusToken) {
if (prefixExpr.operatorToken.kind == SyntaxKind.PlusToken || prefixExpr.operatorToken.kind === SyntaxKind.MinusToken) {
// Note: if there is a + or - sign, we can only allow a normal integer following
// (and not a hex integer). i.e. -0xA is a legal expression, but it is not a
// *literal*.
+95 -25
View File
@@ -6,7 +6,7 @@ module TypeScript {
// Debug.assert(!isShared(element));
while (element) {
if (element.kind() === SyntaxKind.SourceUnit) {
if (element.kind === SyntaxKind.SourceUnit) {
return (<SourceUnitSyntax>element).syntaxTree;
}
@@ -53,7 +53,7 @@ module TypeScript {
throw Errors.argumentOutOfRange("position");
}
var token = findTokenWorker(sourceUnit, 0, position);
var token = findTokenInNodeOrToken(sourceUnit, 0, position);
if (token) {
Debug.assert(token.fullWidth() > 0);
return token;
@@ -113,13 +113,39 @@ module TypeScript {
}
function findTokenWorker(element: ISyntaxElement, elementPosition: number, position: number): ISyntaxToken {
if (isToken(element)) {
return <ISyntaxToken>element;
if (isList(element)) {
return findTokenInList(<ISyntaxNodeOrToken[]>element, elementPosition, position);
}
else {
return findTokenInNodeOrToken(<ISyntaxNodeOrToken>element, elementPosition, position);
}
}
function findTokenInList(list: ISyntaxNodeOrToken[], elementPosition: number, position: number): ISyntaxToken {
for (var i = 0, n = list.length; i < n; i++) {
var child = list[i];
var childFullWidth = fullWidth(child);
var elementEndPosition = elementPosition + childFullWidth;
if (position < elementEndPosition) {
return findTokenWorker(child, elementPosition, position);
}
elementPosition = elementEndPosition;
}
// Consider: we could use a binary search here to find the child more quickly.
for (var i = 0, n = childCount(element); i < n; i++) {
var child = childAt(element, i);
return undefined;
}
function findTokenInNodeOrToken(nodeOrToken: ISyntaxNodeOrToken, elementPosition: number, position: number): ISyntaxToken {
if (isToken(nodeOrToken)) {
return <ISyntaxToken>nodeOrToken;
}
for (var i = 0, n = childCount(nodeOrToken); i < n; i++) {
var child = nodeOrToken.childAt(i);
if (child) {
var childFullWidth = fullWidth(child);
@@ -137,7 +163,7 @@ module TypeScript {
}
function tryGetEndOfFileAt(element: ISyntaxElement, position: number): ISyntaxToken {
if (element.kind() === SyntaxKind.SourceUnit && position === fullWidth(element)) {
if (element.kind === SyntaxKind.SourceUnit && position === fullWidth(element)) {
var sourceUnit = <SourceUnitSyntax>element;
return sourceUnit.endOfFileToken;
}
@@ -146,7 +172,7 @@ module TypeScript {
}
export function nextToken(token: ISyntaxToken, text?: ISimpleText): ISyntaxToken {
if (token.kind() === SyntaxKind.EndOfFileToken) {
if (token.kind === SyntaxKind.EndOfFileToken) {
return undefined;
}
@@ -155,7 +181,7 @@ module TypeScript {
export function isNode(element: ISyntaxElement): boolean {
if (element) {
var kind = element.kind();
var kind = element.kind;
return kind >= SyntaxKind.FirstNode && kind <= SyntaxKind.LastNode;
}
@@ -168,7 +194,7 @@ module TypeScript {
export function isToken(element: ISyntaxElement): boolean {
if (element) {
return isTokenKind(element.kind());
return isTokenKind(element.kind);
}
return false;
@@ -227,7 +253,7 @@ module TypeScript {
export function firstToken(element: ISyntaxElement): ISyntaxToken {
if (element) {
var kind = element.kind();
var kind = element.kind;
if (isTokenKind(kind)) {
return (<ISyntaxToken>element).fullWidth() > 0 || kind === SyntaxKind.EndOfFileToken ? <ISyntaxToken>element : undefined;
@@ -246,10 +272,10 @@ module TypeScript {
export function lastToken(element: ISyntaxElement): ISyntaxToken {
if (isToken(element)) {
return fullWidth(element) > 0 || element.kind() === SyntaxKind.EndOfFileToken ? <ISyntaxToken>element : undefined;
return fullWidth(element) > 0 || element.kind === SyntaxKind.EndOfFileToken ? <ISyntaxToken>element : undefined;
}
if (element.kind() === SyntaxKind.SourceUnit) {
if (element.kind === SyntaxKind.SourceUnit) {
return (<SourceUnitSyntax>element).endOfFileToken;
}
@@ -308,27 +334,52 @@ module TypeScript {
return info;
}
function computeData(element: ISyntaxElement): number {
var slotCount = childCount(element);
function combineData(fullWidth: number, isIncrementallyUnusable: boolean) {
return (fullWidth << SyntaxConstants.NodeFullWidthShift)
| (isIncrementallyUnusable ? SyntaxConstants.NodeIncrementallyUnusableMask : 0)
| SyntaxConstants.NodeDataComputed;
}
function listComputeData(list: ISyntaxNodeOrToken[]): number {
var fullWidth = 0;
var isIncrementallyUnusable = false;
for (var i = 0, n = list.length; i < n; i++) {
var child: ISyntaxElement = list[i];
fullWidth += TypeScript.fullWidth(child);
isIncrementallyUnusable = isIncrementallyUnusable || TypeScript.isIncrementallyUnusable(child);
}
return combineData(fullWidth, isIncrementallyUnusable);
}
function computeData(element: ISyntaxElement): number {
if (isList(element)) {
return listComputeData(<ISyntaxNodeOrToken[]>element);
}
else {
return nodeOrTokenComputeData(<ISyntaxNodeOrToken>element);
}
}
function nodeOrTokenComputeData(nodeOrToken: ISyntaxNodeOrToken) {
var fullWidth = 0;
var slotCount = nodeOrToken.childCount;
// If we have no children (like an OmmittedExpressionSyntax), we're automatically not reusable.
var isIncrementallyUnusable = slotCount === 0 && !isList(element);
var isIncrementallyUnusable = slotCount === 0;
for (var i = 0, n = slotCount; i < n; i++) {
var child = childAt(element, i);
var child = nodeOrToken.childAt(i);
if (child) {
fullWidth += TypeScript.fullWidth(child);
isIncrementallyUnusable = isIncrementallyUnusable || TypeScript.isIncrementallyUnusable(child);
}
}
return (fullWidth << SyntaxConstants.NodeFullWidthShift)
| (isIncrementallyUnusable ? SyntaxConstants.NodeIncrementallyUnusableMask : 0)
| SyntaxConstants.NodeDataComputed;
return combineData(fullWidth, isIncrementallyUnusable);
}
export function start(element: ISyntaxElement, text?: ISimpleText): number {
@@ -366,8 +417,8 @@ module TypeScript {
}
export interface ISyntaxElement {
kind(): SyntaxKind;
parent?: ISyntaxElement;
kind: SyntaxKind;
parent: ISyntaxElement;
}
export interface ISyntaxNode extends ISyntaxNodeOrToken {
@@ -380,6 +431,7 @@ module TypeScript {
}
export interface IModuleElementSyntax extends ISyntaxNode {
_moduleElementBrand: any;
}
export interface IStatementSyntax extends IModuleElementSyntax {
@@ -387,15 +439,28 @@ module TypeScript {
}
export interface ITypeMemberSyntax extends ISyntaxNode {
_typeMemberBrand: any;
}
export interface IClassElementSyntax extends ISyntaxNode {
_classElementBrand: any;
}
export interface IMemberDeclarationSyntax extends IClassElementSyntax {
_memberDeclarationBrand: any;
}
export interface IPropertyAssignmentSyntax extends IClassElementSyntax {
export interface IPropertyAssignmentSyntax extends ISyntaxNodeOrToken {
_propertyAssignmentBrand: any;
}
export interface IAccessorSyntax extends IPropertyAssignmentSyntax, IMemberDeclarationSyntax {
_accessorBrand: any;
modifiers: ISyntaxToken[];
propertyName: IPropertyNameSyntax;
callSignature: CallSignatureSyntax;
block: BlockSyntax;
}
export interface ISwitchClauseSyntax extends ISyntaxNode {
@@ -437,5 +502,10 @@ module TypeScript {
}
export interface INameSyntax extends ITypeSyntax {
_nameBrand: any;
}
export interface IPropertyNameSyntax extends ISyntaxNodeOrToken {
_propertyNameBrand: any;
}
}
+3 -11
View File
@@ -2,16 +2,8 @@
module TypeScript.SyntaxFacts {
export function isDirectivePrologueElement(node: ISyntaxNodeOrToken): boolean {
if (node.kind() === SyntaxKind.ExpressionStatement) {
var expressionStatement = <ExpressionStatementSyntax>node;
var expression = expressionStatement.expression;
if (expression.kind() === SyntaxKind.StringLiteral) {
return true;
}
}
return false;
return node.kind === SyntaxKind.ExpressionStatement &&
(<ExpressionStatementSyntax>node).expression.kind === SyntaxKind.StringLiteral;
}
export function isUseStrictDirective(node: ISyntaxNodeOrToken): boolean {
@@ -23,7 +15,7 @@ module TypeScript.SyntaxFacts {
}
export function isIdentifierNameOrAnyKeyword(token: ISyntaxToken): boolean {
var tokenKind = token.kind();
var tokenKind = token.kind;
return tokenKind === SyntaxKind.IdentifierName || SyntaxFacts.isAnyKeyword(tokenKind);
}
+75 -131
View File
@@ -187,7 +187,7 @@ var definitions:ITypeDefinition[] = [
name: 'VariableDeclaratorSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'propertyName', isToken: true },
<any>{ name: 'propertyName', type: 'IPropertyNameSyntax' },
<any>{ name: 'typeAnnotation', type: 'TypeAnnotationSyntax', isOptional: true, isTypeScriptSpecific: true },
<any>{ name: 'equalsValueClause', type: 'EqualsValueClauseSyntax', isOptional: true }
]
@@ -449,7 +449,7 @@ var definitions:ITypeDefinition[] = [
interfaces: ['IMemberExpressionSyntax', 'ICallExpressionSyntax'],
children: [
<any>{ name: 'expression', type: 'ILeftHandSideExpressionSyntax' },
<any>{ name: 'templateExpression', type: 'IPrimaryExpressionSyntax' },
<any>{ name: 'templateExpression', type: 'IPrimaryExpressionSyntax' }
]
},
<any>{
@@ -458,7 +458,7 @@ var definitions:ITypeDefinition[] = [
interfaces: ['IPrimaryExpressionSyntax'],
children: [
<any>{ name: 'templateStartToken', isToken: true, excludeFromAST: true },
<any>{ name: 'templateClauses', isList: true, elementType: 'TemplateClauseSyntax' },
<any>{ name: 'templateClauses', isList: true, elementType: 'TemplateClauseSyntax' }
]
},
<any>{
@@ -466,7 +466,7 @@ var definitions:ITypeDefinition[] = [
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'expression', type: 'IExpressionSyntax' },
<any>{ name: 'templateMiddleOrEndToken', isToken: true, elementType: 'TemplateSpanSyntax' },
<any>{ name: 'templateMiddleOrEndToken', isToken: true, elementType: 'TemplateSpanSyntax' }
]
},
<any>{
@@ -525,7 +525,7 @@ var definitions:ITypeDefinition[] = [
baseType: 'ISyntaxNode',
interfaces: ['ITypeMemberSyntax'],
children: [
<any>{ name: 'propertyName', isToken: true, tokenKinds: ['IdentifierName', 'StringLiteral', 'NumericLiteral'] },
<any>{ name: 'propertyName', type: 'IPropertyNameSyntax' },
<any>{ name: 'questionToken', isToken: true, isOptional: true, itTypeScriptSpecific: true },
<any>{ name: 'callSignature', type: 'CallSignatureSyntax' }
]
@@ -547,7 +547,7 @@ var definitions:ITypeDefinition[] = [
baseType: 'ISyntaxNode',
interfaces: ['ITypeMemberSyntax'],
children: [
<any>{ name: 'propertyName', isToken: true, tokenKinds: ['IdentifierName', 'StringLiteral', 'NumericLiteral'] },
<any>{ name: 'propertyName', type: 'IPropertyNameSyntax' },
<any>{ name: 'questionToken', isToken: true, isOptional: true },
<any>{ name: 'typeAnnotation', type: 'TypeAnnotationSyntax', isOptional: true }
],
@@ -650,7 +650,7 @@ var definitions:ITypeDefinition[] = [
interfaces: ['IMemberDeclarationSyntax'],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken' },
<any>{ name: 'propertyName', isToken: true, tokenKinds: ['IdentifierName', 'StringLiteral', 'NumericLiteral'] },
<any>{ name: 'propertyName', type: 'IPropertyNameSyntax' },
<any>{ name: 'callSignature', type: 'CallSignatureSyntax' },
<any>{ name: 'block', type: 'BlockSyntax', isOptional: true },
<any>{ name: 'semicolonToken', isToken: true, isOptional: true, excludeFromAST: true }
@@ -660,11 +660,11 @@ var definitions:ITypeDefinition[] = [
<any>{
name: 'GetAccessorSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IMemberDeclarationSyntax', 'IPropertyAssignmentSyntax' ],
interfaces: ['IAccessorSyntax' ],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken', isTypeScriptSpecific: true },
<any>{ name: 'getKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'propertyName', isToken: true, tokenKinds: ['IdentifierName', 'StringLiteral', 'NumericLiteral'] },
<any>{ name: 'propertyName', type: 'IPropertyNameSyntax' },
<any>{ name: 'callSignature', type: 'CallSignatureSyntax' },
<any>{ name: 'block', type: 'BlockSyntax' }
]
@@ -672,11 +672,11 @@ var definitions:ITypeDefinition[] = [
<any>{
name: 'SetAccessorSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IMemberDeclarationSyntax', 'IPropertyAssignmentSyntax'],
interfaces: ['IAccessorSyntax'],
children: [
<any>{ name: 'modifiers', isList: true, elementType: 'ISyntaxToken', isTypeScriptSpecific: true },
<any>{ name: 'setKeyword', isToken: true, excludeFromAST: true },
<any>{ name: 'propertyName', isToken: true, tokenKinds: ['IdentifierName', 'StringLiteral', 'NumericLiteral'] },
<any>{ name: 'propertyName', type: 'IPropertyNameSyntax' },
<any>{ name: 'callSignature', type: 'CallSignatureSyntax' },
<any>{ name: 'block', type: 'BlockSyntax' }
],
@@ -863,7 +863,7 @@ var definitions:ITypeDefinition[] = [
name: 'EnumElementSyntax',
baseType: 'ISyntaxNode',
children: [
<any>{ name: 'propertyName', isToken: true, tokenKinds: ['IdentifierName', 'StringLiteral', 'NumericLiteral'] },
<any>{ name: 'propertyName', type: 'IPropertyNameSyntax' },
<any>{ name: 'equalsValueClause', type: 'EqualsValueClauseSyntax', isOptional: true }
]
},
@@ -889,12 +889,22 @@ var definitions:ITypeDefinition[] = [
<any>{ name: 'closeBraceToken', isToken: true, excludeFromAST: true }
]
},
<any>{
name: 'ComputedPropertyNameSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IPropertyNameSyntax'],
children: [
<any>{ name: 'openBracketToken', isToken: true },
<any>{ name: 'expression', type: 'IExpressionSyntax' },
<any>{ name: 'closeBracketToken', isToken: true }
]
},
<any>{
name: 'SimplePropertyAssignmentSyntax',
baseType: 'ISyntaxNode',
interfaces: ['IPropertyAssignmentSyntax'],
children: [
<any>{ name: 'propertyName', isToken: true, tokenKinds: ['IdentifierName', 'StringLiteral', 'NumericLiteral'] },
<any>{ name: 'propertyName', type: 'IPropertyNameSyntax' },
<any>{ name: 'colonToken', isToken: true, excludeFromAST: true },
<any>{ name: 'expression', type: 'IExpressionSyntax' }
]
@@ -904,7 +914,7 @@ var definitions:ITypeDefinition[] = [
baseType: 'ISyntaxNode',
interfaces: ['IPropertyAssignmentSyntax'],
children: [
<any>{ name: 'propertyName', isToken: true, tokenKinds: ['IdentifierName', 'StringLiteral', 'NumericLiteral'] },
<any>{ name: 'propertyName', type: 'IPropertyNameSyntax' },
<any>{ name: 'callSignature', type: 'CallSignatureSyntax' },
<any>{ name: 'block', type: 'BlockSyntax' }
]
@@ -1055,54 +1065,6 @@ function getSafeName(child: IMemberDefinition) {
return child.name;
}
function generateBrands(definition: ITypeDefinition, accessibility: boolean): string {
var properties = "";
var types: string[] = [];
if (definition.interfaces) {
var ifaces = definition.interfaces.slice(0);
var i: number;
for (i = 0; i < ifaces.length; i++) {
var current = ifaces[i];
while (current !== undefined) {
if (!TypeScript.ArrayUtilities.contains(ifaces, current)) {
ifaces.push(current);
}
current = interfaces[current];
}
}
for (i = 0; i < ifaces.length; i++) {
var type = ifaces[i];
type = getStringWithoutSuffix(type);
if (isInterface(type)) {
type = "_" + type.substr(1, 1).toLowerCase() + type.substr(2) + "Brand";
}
types.push(type);
}
}
types.push("_syntaxNodeOrTokenBrand");
if (types.length > 0) {
properties += " ";
for (var i = 0; i < types.length; i++) {
if (accessibility) {
properties += " public ";
}
properties += types[i] + ": any;";
}
properties += "\r\n";
}
return properties;
}
function generateConstructorFunction(definition: ITypeDefinition) {
var result = " export var " + definition.name + ": " + getNameWithoutSuffix(definition) + "Constructor = <any>function(data: number";
@@ -1153,7 +1115,22 @@ function generateConstructorFunction(definition: ITypeDefinition) {
}
result += " };\r\n";
result += " " + definition.name + ".prototype.kind = function() { return SyntaxKind." + getNameWithoutSuffix(definition) + "; }\r\n";
result += " " + definition.name + ".prototype.kind = SyntaxKind." + getNameWithoutSuffix(definition) + ";\r\n";
result += " " + definition.name + ".prototype.childCount = " + definition.children.length + ";\r\n";
result += " " + definition.name + ".prototype.childAt = function(index: number): ISyntaxElement {\r\n";
if (definition.children.length) {
result += " switch (index) {\r\n";
for (var j = 0; j < definition.children.length; j++) {
result += " case " + j + ": return this." + definition.children[j].name + ";\r\n";
}
result += " }\r\n";
}
else {
result += " throw Errors.invalidOperation();\r\n";
}
result += " }\r\n";
return result;
}
@@ -1401,22 +1378,44 @@ function max<T>(array: T[], func: (v: T) => number): number {
return max;
}
function generateUtilities(): string {
var result = "";
result += " var fixedWidthArray = [";
for (var i = 0; i <= TypeScript.SyntaxKind.LastFixedWidth; i++) {
if (i) {
result += ", ";
}
if (i < TypeScript.SyntaxKind.FirstFixedWidth) {
result += "0";
}
else {
result += TypeScript.SyntaxFacts.getText(i).length;
}
}
result += "];\r\n";
result += " function fixedWidthTokenLength(kind: SyntaxKind) {\r\n";
result += " return fixedWidthArray[kind];\r\n";
//result += " switch (kind) {\r\n";
//for (var k = TypeScript.SyntaxKind.FirstFixedWidth; k <= TypeScript.SyntaxKind.LastFixedWidth; k++) {
// result += " case SyntaxKind." + syntaxKindName(k) + ": return " + TypeScript.SyntaxFacts.getText(k).length + ";\r\n";
//}
//result += " default: throw new Error();\r\n";
//result += " }\r\n";
result += " }\r\n";
return result;
}
function generateScannerUtilities(): string {
var result = "///<reference path='references.ts' />\r\n" +
"\r\n" +
"module TypeScript {\r\n" +
" export module ScannerUtilities {\r\n";
result += " export function fixedWidthTokenLength(kind: SyntaxKind) {\r\n";
result += " switch (kind) {\r\n";
for (var k = TypeScript.SyntaxKind.FirstFixedWidth; k <= TypeScript.SyntaxKind.LastFixedWidth; k++) {
result += " case SyntaxKind." + syntaxKindName(k) + ": return " + TypeScript.SyntaxFacts.getText(k).length + ";\r\n";
}
result += " default: throw new Error();\r\n";
result += " }\r\n";
result += " }\r\n\r\n";
var i: number;
var keywords: { text: string; kind: TypeScript.SyntaxKind; }[] = [];
@@ -1470,7 +1469,7 @@ function generateVisitor(): string {
result += " export function visitNodeOrToken(visitor: ISyntaxVisitor, element: ISyntaxNodeOrToken): any {\r\n";
result += " if (element === undefined) { return undefined; }\r\n";
result += " switch (element.kind()) {\r\n";
result += " switch (element.kind) {\r\n";
for (var i = 0; i < definitions.length; i++) {
var definition = definitions[i];
@@ -1498,71 +1497,16 @@ function generateVisitor(): string {
return result;
}
function generateServicesUtilities(): string {
var result = "";
result += "module TypeScript {\r\n";
result += " export function childCount(element: ISyntaxElement): number {\r\n";
result += " if (isList(element)) { return (<ISyntaxNodeOrToken[]>element).length; }\r\n";
result += " switch (element.kind()) {\r\n";
for (var i = 0; i < definitions.length; i++) {
var definition = definitions[i];
result += " case SyntaxKind." + getNameWithoutSuffix(definition) + ": return " + definition.children.length + ";\r\n";
}
result += " default: return 0;\r\n"
result += " }\r\n";
result += " }\r\n\r\n";
for (var i = 0; i < definitions.length; i++) {
var definition = definitions[i];
result += " function " + camelCase(getNameWithoutSuffix(definition)) + "ChildAt(node: " + definition.name + ", index: number): ISyntaxElement {\r\n";
if (definition.children.length) {
result += " switch (index) {\r\n";
for (var j = 0; j < definition.children.length; j++) {
result += " case " + j + ": return node." + definition.children[j].name + ";\r\n";
}
result += " }\r\n";
}
else {
result += " throw Errors.invalidOperation();\r\n";
}
result += " }\r\n";
}
result += " export function childAt(element: ISyntaxElement, index: number): ISyntaxElement {\r\n";
result += " if (isList(element)) { return (<ISyntaxNodeOrToken[]>element)[index]; }\r\n";
result += " switch (element.kind()) {\r\n";
for (var i = 0; i < definitions.length; i++) {
var definition = definitions[i];
result += " case SyntaxKind." + getNameWithoutSuffix(definition) + ": return " + camelCase(getNameWithoutSuffix(definition)) + "ChildAt(<" + definition.name + ">element, index);\r\n";
}
result += " }\r\n";
result += " }\r\n";
result += "}";
return result;
}
var syntaxNodesConcrete = generateNodes();
var syntaxInterfaces = generateSyntaxInterfaces();
var walker = generateWalker();
var scannerUtilities = generateScannerUtilities();
var visitor = generateVisitor();
var servicesUtilities = generateServicesUtilities();
var utilities = generateUtilities();
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\syntaxNodes.concrete.generated.ts", syntaxNodesConcrete, false);
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\syntaxInterfaces.generated.ts", syntaxInterfaces, false);
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\syntaxWalker.generated.ts", walker, false);
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\scannerUtilities.generated.ts", scannerUtilities, false);
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\syntaxVisitor.generated.ts", visitor, false);
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\syntaxUtilities.generated.ts", servicesUtilities, false);
sys.writeFile(sys.getCurrentDirectory() + "\\src\\services\\syntax\\utilities.generated.ts", utilities, false);
@@ -152,12 +152,12 @@ module TypeScript {
export interface MemberFunctionDeclarationSyntax extends ISyntaxNode, IMemberDeclarationSyntax {
modifiers: ISyntaxToken[];
propertyName: ISyntaxToken;
propertyName: IPropertyNameSyntax;
callSignature: CallSignatureSyntax;
block: BlockSyntax;
semicolonToken: ISyntaxToken;
}
export interface MemberFunctionDeclarationConstructor { new (data: number, modifiers: ISyntaxToken[], propertyName: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken): MemberFunctionDeclarationSyntax }
export interface MemberFunctionDeclarationConstructor { new (data: number, modifiers: ISyntaxToken[], propertyName: IPropertyNameSyntax, callSignature: CallSignatureSyntax, block: BlockSyntax, semicolonToken: ISyntaxToken): MemberFunctionDeclarationSyntax }
export interface MemberVariableDeclarationSyntax extends ISyntaxNode, IMemberDeclarationSyntax {
modifiers: ISyntaxToken[];
@@ -182,30 +182,30 @@ module TypeScript {
}
export interface IndexMemberDeclarationConstructor { new (data: number, modifiers: ISyntaxToken[], indexSignature: IndexSignatureSyntax, semicolonToken: ISyntaxToken): IndexMemberDeclarationSyntax }
export interface GetAccessorSyntax extends ISyntaxNode, IMemberDeclarationSyntax, IPropertyAssignmentSyntax {
export interface GetAccessorSyntax extends ISyntaxNode, IAccessorSyntax {
modifiers: ISyntaxToken[];
getKeyword: ISyntaxToken;
propertyName: ISyntaxToken;
propertyName: IPropertyNameSyntax;
callSignature: CallSignatureSyntax;
block: BlockSyntax;
}
export interface GetAccessorConstructor { new (data: number, modifiers: ISyntaxToken[], getKeyword: ISyntaxToken, propertyName: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax): GetAccessorSyntax }
export interface GetAccessorConstructor { new (data: number, modifiers: ISyntaxToken[], getKeyword: ISyntaxToken, propertyName: IPropertyNameSyntax, callSignature: CallSignatureSyntax, block: BlockSyntax): GetAccessorSyntax }
export interface SetAccessorSyntax extends ISyntaxNode, IMemberDeclarationSyntax, IPropertyAssignmentSyntax {
export interface SetAccessorSyntax extends ISyntaxNode, IAccessorSyntax {
modifiers: ISyntaxToken[];
setKeyword: ISyntaxToken;
propertyName: ISyntaxToken;
propertyName: IPropertyNameSyntax;
callSignature: CallSignatureSyntax;
block: BlockSyntax;
}
export interface SetAccessorConstructor { new (data: number, modifiers: ISyntaxToken[], setKeyword: ISyntaxToken, propertyName: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax): SetAccessorSyntax }
export interface SetAccessorConstructor { new (data: number, modifiers: ISyntaxToken[], setKeyword: ISyntaxToken, propertyName: IPropertyNameSyntax, callSignature: CallSignatureSyntax, block: BlockSyntax): SetAccessorSyntax }
export interface PropertySignatureSyntax extends ISyntaxNode, ITypeMemberSyntax {
propertyName: ISyntaxToken;
propertyName: IPropertyNameSyntax;
questionToken: ISyntaxToken;
typeAnnotation: TypeAnnotationSyntax;
}
export interface PropertySignatureConstructor { new (data: number, propertyName: ISyntaxToken, questionToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax): PropertySignatureSyntax }
export interface PropertySignatureConstructor { new (data: number, propertyName: IPropertyNameSyntax, questionToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax): PropertySignatureSyntax }
export interface CallSignatureSyntax extends ISyntaxNode, ITypeMemberSyntax {
typeParameterList: TypeParameterListSyntax;
@@ -229,11 +229,11 @@ module TypeScript {
export interface IndexSignatureConstructor { new (data: number, openBracketToken: ISyntaxToken, parameters: ISeparatedSyntaxList<ParameterSyntax>, closeBracketToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax): IndexSignatureSyntax }
export interface MethodSignatureSyntax extends ISyntaxNode, ITypeMemberSyntax {
propertyName: ISyntaxToken;
propertyName: IPropertyNameSyntax;
questionToken: ISyntaxToken;
callSignature: CallSignatureSyntax;
}
export interface MethodSignatureConstructor { new (data: number, propertyName: ISyntaxToken, questionToken: ISyntaxToken, callSignature: CallSignatureSyntax): MethodSignatureSyntax }
export interface MethodSignatureConstructor { new (data: number, propertyName: IPropertyNameSyntax, questionToken: ISyntaxToken, callSignature: CallSignatureSyntax): MethodSignatureSyntax }
export interface BlockSyntax extends ISyntaxNode, IStatementSyntax {
openBraceToken: ISyntaxToken;
@@ -535,11 +535,11 @@ module TypeScript {
export interface VariableDeclarationConstructor { new (data: number, varKeyword: ISyntaxToken, variableDeclarators: ISeparatedSyntaxList<VariableDeclaratorSyntax>): VariableDeclarationSyntax }
export interface VariableDeclaratorSyntax extends ISyntaxNode {
propertyName: ISyntaxToken;
propertyName: IPropertyNameSyntax;
typeAnnotation: TypeAnnotationSyntax;
equalsValueClause: EqualsValueClauseSyntax;
}
export interface VariableDeclaratorConstructor { new (data: number, propertyName: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, equalsValueClause: EqualsValueClauseSyntax): VariableDeclaratorSyntax }
export interface VariableDeclaratorConstructor { new (data: number, propertyName: IPropertyNameSyntax, typeAnnotation: TypeAnnotationSyntax, equalsValueClause: EqualsValueClauseSyntax): VariableDeclaratorSyntax }
export interface ArgumentListSyntax extends ISyntaxNode {
typeArgumentList: TypeArgumentListSyntax;
@@ -638,18 +638,18 @@ module TypeScript {
export interface ConstraintConstructor { new (data: number, extendsKeyword: ISyntaxToken, typeOrExpression: ISyntaxNodeOrToken): ConstraintSyntax }
export interface SimplePropertyAssignmentSyntax extends ISyntaxNode, IPropertyAssignmentSyntax {
propertyName: ISyntaxToken;
propertyName: IPropertyNameSyntax;
colonToken: ISyntaxToken;
expression: IExpressionSyntax;
}
export interface SimplePropertyAssignmentConstructor { new (data: number, propertyName: ISyntaxToken, colonToken: ISyntaxToken, expression: IExpressionSyntax): SimplePropertyAssignmentSyntax }
export interface SimplePropertyAssignmentConstructor { new (data: number, propertyName: IPropertyNameSyntax, colonToken: ISyntaxToken, expression: IExpressionSyntax): SimplePropertyAssignmentSyntax }
export interface FunctionPropertyAssignmentSyntax extends ISyntaxNode, IPropertyAssignmentSyntax {
propertyName: ISyntaxToken;
propertyName: IPropertyNameSyntax;
callSignature: CallSignatureSyntax;
block: BlockSyntax;
}
export interface FunctionPropertyAssignmentConstructor { new (data: number, propertyName: ISyntaxToken, callSignature: CallSignatureSyntax, block: BlockSyntax): FunctionPropertyAssignmentSyntax }
export interface FunctionPropertyAssignmentConstructor { new (data: number, propertyName: IPropertyNameSyntax, callSignature: CallSignatureSyntax, block: BlockSyntax): FunctionPropertyAssignmentSyntax }
export interface ParameterSyntax extends ISyntaxNode {
dotDotDotToken: ISyntaxToken;
@@ -662,10 +662,10 @@ module TypeScript {
export interface ParameterConstructor { new (data: number, dotDotDotToken: ISyntaxToken, modifiers: ISyntaxToken[], identifier: ISyntaxToken, questionToken: ISyntaxToken, typeAnnotation: TypeAnnotationSyntax, equalsValueClause: EqualsValueClauseSyntax): ParameterSyntax }
export interface EnumElementSyntax extends ISyntaxNode {
propertyName: ISyntaxToken;
propertyName: IPropertyNameSyntax;
equalsValueClause: EqualsValueClauseSyntax;
}
export interface EnumElementConstructor { new (data: number, propertyName: ISyntaxToken, equalsValueClause: EqualsValueClauseSyntax): EnumElementSyntax }
export interface EnumElementConstructor { new (data: number, propertyName: IPropertyNameSyntax, equalsValueClause: EqualsValueClauseSyntax): EnumElementSyntax }
export interface TypeAnnotationSyntax extends ISyntaxNode {
colonToken: ISyntaxToken;
@@ -673,6 +673,13 @@ module TypeScript {
}
export interface TypeAnnotationConstructor { new (data: number, colonToken: ISyntaxToken, type: ITypeSyntax): TypeAnnotationSyntax }
export interface ComputedPropertyNameSyntax extends ISyntaxNode, IPropertyNameSyntax {
openBracketToken: ISyntaxToken;
expression: IExpressionSyntax;
closeBracketToken: ISyntaxToken;
}
export interface ComputedPropertyNameConstructor { new (data: number, openBracketToken: ISyntaxToken, expression: IExpressionSyntax, closeBracketToken: ISyntaxToken): ComputedPropertyNameSyntax }
export interface ExternalModuleReferenceSyntax extends ISyntaxNode, IModuleReferenceSyntax {
requireKeyword: ISyntaxToken;
openParenToken: ISyntaxToken;
+1 -2
View File
@@ -261,14 +261,13 @@ module TypeScript {
// Property Assignment
SimplePropertyAssignment,
// GetAccessorPropertyAssignment,
// SetAccessorPropertyAssignment,
FunctionPropertyAssignment,
// Misc.
Parameter,
EnumElement,
TypeAnnotation,
ComputedPropertyName,
ExternalModuleReference,
ModuleNameModuleReference,
+6 -8
View File
@@ -3,7 +3,7 @@
interface Array<T> {
__data: number;
kind(): TypeScript.SyntaxKind;
kind: TypeScript.SyntaxKind;
parent: TypeScript.ISyntaxElement;
}
@@ -36,18 +36,16 @@ module TypeScript {
}
module TypeScript.Syntax {
function addArrayFunction(name: string, func: Function) {
if (Object.defineProperty) {
Object.defineProperty(Array.prototype, name, { value: func, writable: true });
function addArrayPrototypeValue(name: string, val: any) {
if (Object.defineProperty && (<any>Array.prototype)[name] === undefined) {
Object.defineProperty(Array.prototype, name, { value: val, writable: false });
}
else {
(<any>Array.prototype)[name] = func;
(<any>Array.prototype)[name] = val;
}
}
addArrayFunction("kind", function () {
return SyntaxKind.List;
});
addArrayPrototypeValue("kind", SyntaxKind.List);
export function list<T extends ISyntaxNodeOrToken>(nodes: T[]): T[] {
for (var i = 0, n = nodes.length; i < n; i++) {
+2 -1
View File
@@ -2,6 +2,7 @@
module TypeScript {
export interface ISyntaxNodeOrToken extends ISyntaxElement {
_syntaxNodeOrTokenBrand: any;
childCount: number;
childAt(index: number): ISyntaxElement;
}
}
File diff suppressed because it is too large Load Diff
+31 -34
View File
@@ -1,7 +1,7 @@
///<reference path='references.ts' />
module TypeScript {
export interface ISyntaxToken extends ISyntaxNodeOrToken, INameSyntax, IPrimaryExpressionSyntax {
export interface ISyntaxToken extends ISyntaxNodeOrToken, INameSyntax, IPrimaryExpressionSyntax, IPropertyAssignmentSyntax, IPropertyNameSyntax {
// Adjusts the full start of this token. Should only be called by the parser.
setFullStart(fullStart: number): void;
@@ -74,7 +74,7 @@ module TypeScript {
return undefined;
}
var kind = token.kind();
var kind = token.kind;
var text = token.text();
if (kind === SyntaxKind.IdentifierName) {
@@ -284,7 +284,7 @@ module TypeScript {
module TypeScript.Syntax {
export function realizeToken(token: ISyntaxToken, text: ISimpleText): ISyntaxToken {
return new RealizedToken(token.fullStart(), token.kind(), token.isKeywordConvertedToIdentifier(), token.leadingTrivia(text), token.text(), token.trailingTrivia(text));
return new RealizedToken(token.fullStart(), token.kind, token.isKeywordConvertedToIdentifier(), token.leadingTrivia(text), token.text(), token.trailingTrivia(text));
}
export function convertKeywordToIdentifier(token: ISyntaxToken): ISyntaxToken {
@@ -292,11 +292,11 @@ module TypeScript.Syntax {
}
export function withLeadingTrivia(token: ISyntaxToken, leadingTrivia: ISyntaxTriviaList, text: ISimpleText): ISyntaxToken {
return new RealizedToken(token.fullStart(), token.kind(), token.isKeywordConvertedToIdentifier(), leadingTrivia, token.text(), token.trailingTrivia(text));
return new RealizedToken(token.fullStart(), token.kind, token.isKeywordConvertedToIdentifier(), leadingTrivia, token.text(), token.trailingTrivia(text));
}
export function withTrailingTrivia(token: ISyntaxToken, trailingTrivia: ISyntaxTriviaList, text: ISimpleText): ISyntaxToken {
return new RealizedToken(token.fullStart(), token.kind(), token.isKeywordConvertedToIdentifier(), token.leadingTrivia(text), token.text(), trailingTrivia);
return new RealizedToken(token.fullStart(), token.kind, token.isKeywordConvertedToIdentifier(), token.leadingTrivia(text), token.text(), trailingTrivia);
}
export function emptyToken(kind: SyntaxKind): ISyntaxToken {
@@ -304,25 +304,23 @@ module TypeScript.Syntax {
}
class EmptyToken implements ISyntaxToken {
public _primaryExpressionBrand: any; public _memberExpressionBrand: any; public _leftHandSideExpressionBrand: any; public _postfixExpressionBrand: any; public _unaryExpressionBrand: any; public _expressionBrand: any; public _typeBrand: any; public _syntaxNodeOrTokenBrand: any;
public _primaryExpressionBrand: any; public _memberExpressionBrand: any; public _leftHandSideExpressionBrand: any; public _postfixExpressionBrand: any; public _unaryExpressionBrand: any; public _expressionBrand: any; public _typeBrand: any; public _nameBrand: any; public _propertyAssignmentBrand: any; public _propertyNameBrand: any;
constructor(private _kind: SyntaxKind) {
public parent: ISyntaxElement;
public childCount: number;
constructor(public kind: SyntaxKind) {
}
public setFullStart(fullStart: number): void {
// An empty token is always at the -1 position.
}
public kind(): SyntaxKind {
return this._kind;
}
public childCount() { return 0 }
public childAt(index: number): ISyntaxElement { throw Errors.invalidOperation() }
public accept(visitor: ISyntaxVisitor): any { return visitor.visitToken(this) }
public clone(): ISyntaxToken {
return new EmptyToken(this.kind());
return new EmptyToken(this.kind);
}
// Empty tokens are never incrementally reusable.
@@ -362,7 +360,7 @@ module TypeScript.Syntax {
while (true) {
var parent = current.parent;
if (parent === undefined) {
Debug.assert(current.kind() === SyntaxKind.SourceUnit, "We had a node without a parent that was not the root node!");
Debug.assert(current.kind === SyntaxKind.SourceUnit, "We had a node without a parent that was not the root node!");
// We walked all the way to the top, and never found a previous element. This
// can happen with code like:
@@ -418,25 +416,27 @@ module TypeScript.Syntax {
public leadingTrivia(): ISyntaxTriviaList { return Syntax.emptyTriviaList; }
public trailingTrivia(): ISyntaxTriviaList { return Syntax.emptyTriviaList; }
}
EmptyToken.prototype.childCount = 0;
class RealizedToken implements ISyntaxToken {
public _primaryExpressionBrand: any; public _memberExpressionBrand: any; public _leftHandSideExpressionBrand: any; public _postfixExpressionBrand: any; public _unaryExpressionBrand: any; public _expressionBrand: any; public _typeBrand: any; public _nameBrand: any; public _propertyAssignmentBrand: any; public _propertyNameBrand: any;
private _fullStart: number;
private _kind: SyntaxKind;
private _isKeywordConvertedToIdentifier: boolean;
private _leadingTrivia: ISyntaxTriviaList;
private _text: string;
private _trailingTrivia: ISyntaxTriviaList;
public _primaryExpressionBrand: any; public _memberExpressionBrand: any; public _leftHandSideExpressionBrand: any; public _postfixExpressionBrand: any; public _unaryExpressionBrand: any; public _expressionBrand: any; public _typeBrand: any; public _syntaxNodeOrTokenBrand: any;
public parent: ISyntaxElement;
public childCount: number;
constructor(fullStart: number,
kind: SyntaxKind,
isKeywordConvertedToIdentifier: boolean,
leadingTrivia: ISyntaxTriviaList,
text: string,
trailingTrivia: ISyntaxTriviaList) {
public kind: SyntaxKind,
isKeywordConvertedToIdentifier: boolean,
leadingTrivia: ISyntaxTriviaList,
text: string,
trailingTrivia: ISyntaxTriviaList) {
this._fullStart = fullStart;
this._kind = kind;
this._isKeywordConvertedToIdentifier = isKeywordConvertedToIdentifier;
this._text = text;
@@ -456,16 +456,11 @@ module TypeScript.Syntax {
this._fullStart = fullStart;
}
public kind(): SyntaxKind {
return this._kind;
}
public childCount() { return 0 }
public childAt(index: number): ISyntaxElement { throw Errors.invalidOperation() }
public accept(visitor: ISyntaxVisitor): any { return visitor.visitToken(this) }
public clone(): ISyntaxToken {
return new RealizedToken(this._fullStart, this.kind(), this._isKeywordConvertedToIdentifier, this._leadingTrivia, this._text, this._trailingTrivia);
return new RealizedToken(this._fullStart, this.kind, this._isKeywordConvertedToIdentifier, this._leadingTrivia, this._text, this._trailingTrivia);
}
// Realized tokens are created from the parser. They are *never* incrementally reusable.
@@ -494,22 +489,22 @@ module TypeScript.Syntax {
public leadingTrivia(): ISyntaxTriviaList { return this._leadingTrivia; }
public trailingTrivia(): ISyntaxTriviaList { return this._trailingTrivia; }
}
RealizedToken.prototype.childCount = 0;
class ConvertedKeywordToken implements ISyntaxToken {
public _primaryExpressionBrand: any; public _memberExpressionBrand: any; public _leftHandSideExpressionBrand: any; public _postfixExpressionBrand: any; public _unaryExpressionBrand: any; public _expressionBrand: any; public _typeBrand: any; public _syntaxNodeOrTokenBrand: any;
public _primaryExpressionBrand: any; public _memberExpressionBrand: any; public _leftHandSideExpressionBrand: any; public _postfixExpressionBrand: any; public _unaryExpressionBrand: any; public _expressionBrand: any; public _typeBrand: any; public _nameBrand: any; public _propertyAssignmentBrand: any; public _propertyNameBrand: any;
public parent: ISyntaxElement;
public kind: SyntaxKind;
public childCount: number;
constructor(private underlyingToken: ISyntaxToken) {
}
public kind() {
return SyntaxKind.IdentifierName;
}
public setFullStart(fullStart: number): void {
this.underlyingToken.setFullStart(fullStart);
}
public childCount() { return 0 }
public childAt(index: number): ISyntaxElement { throw Errors.invalidOperation() }
public accept(visitor: ISyntaxVisitor): any { return visitor.visitToken(this) }
@@ -591,4 +586,6 @@ module TypeScript.Syntax {
return new ConvertedKeywordToken(this.underlyingToken);
}
}
ConvertedKeywordToken.prototype.kind = SyntaxKind.IdentifierName;
ConvertedKeywordToken.prototype.childCount = 0;
}
+64 -51
View File
@@ -231,7 +231,7 @@ module TypeScript {
}
private checkParameterAccessibilityModifier(parameterList: ParameterListSyntax, modifier: ISyntaxToken, modifierIndex: number): boolean {
if (!SyntaxFacts.isAccessibilityModifier(modifier.kind())) {
if (!SyntaxFacts.isAccessibilityModifier(modifier.kind)) {
this.pushDiagnostic(modifier, DiagnosticCode._0_modifier_cannot_appear_on_a_parameter, [modifier.text()]);
return true;
}
@@ -280,7 +280,7 @@ module TypeScript {
public visitHeritageClause(node: HeritageClauseSyntax): void {
if (this.checkForTrailingComma(node.typeNames) ||
this.checkForAtLeastOneElement(node.typeNames, node.extendsOrImplementsKeyword, SyntaxFacts.getText(node.extendsOrImplementsKeyword.kind()))) {
this.checkForAtLeastOneElement(node.typeNames, node.extendsOrImplementsKeyword, SyntaxFacts.getText(node.extendsOrImplementsKeyword.kind))) {
return;
}
@@ -359,8 +359,8 @@ module TypeScript {
this.pushDiagnostic(parameter, DiagnosticCode.Index_signature_parameter_must_have_a_type_annotation);
return true;
}
else if (parameter.typeAnnotation.type.kind() !== SyntaxKind.StringKeyword &&
parameter.typeAnnotation.type.kind() !== SyntaxKind.NumberKeyword) {
else if (parameter.typeAnnotation.type.kind !== SyntaxKind.StringKeyword &&
parameter.typeAnnotation.type.kind !== SyntaxKind.NumberKeyword) {
this.pushDiagnostic(parameter, DiagnosticCode.Index_signature_parameter_type_must_be_string_or_number);
return true;
}
@@ -389,7 +389,7 @@ module TypeScript {
Debug.assert(i <= 2);
var heritageClause = node.heritageClauses[i];
if (heritageClause.extendsOrImplementsKeyword.kind() === SyntaxKind.ExtendsKeyword) {
if (heritageClause.extendsOrImplementsKeyword.kind === SyntaxKind.ExtendsKeyword) {
if (seenExtendsClause) {
this.pushDiagnostic(heritageClause, DiagnosticCode.extends_clause_already_seen);
return true;
@@ -408,7 +408,7 @@ module TypeScript {
seenExtendsClause = true;
}
else {
Debug.assert(heritageClause.extendsOrImplementsKeyword.kind() === SyntaxKind.ImplementsKeyword);
Debug.assert(heritageClause.extendsOrImplementsKeyword.kind === SyntaxKind.ImplementsKeyword);
if (seenImplementsClause) {
this.pushDiagnostic(heritageClause, DiagnosticCode.implements_clause_already_seen);
return true;
@@ -468,7 +468,7 @@ module TypeScript {
Debug.assert(i <= 1);
var heritageClause = node.heritageClauses[i];
if (heritageClause.extendsOrImplementsKeyword.kind() === SyntaxKind.ExtendsKeyword) {
if (heritageClause.extendsOrImplementsKeyword.kind === SyntaxKind.ExtendsKeyword) {
if (seenExtendsClause) {
this.pushDiagnostic(heritageClause, DiagnosticCode.extends_clause_already_seen);
return true;
@@ -477,7 +477,7 @@ module TypeScript {
seenExtendsClause = true;
}
else {
Debug.assert(heritageClause.extendsOrImplementsKeyword.kind() === SyntaxKind.ImplementsKeyword);
Debug.assert(heritageClause.extendsOrImplementsKeyword.kind === SyntaxKind.ImplementsKeyword);
this.pushDiagnostic(heritageClause, DiagnosticCode.Interface_declaration_cannot_have_implements_clause);
return true;
}
@@ -489,7 +489,7 @@ module TypeScript {
private checkInterfaceModifiers(modifiers: ISyntaxToken[]): boolean {
for (var i = 0, n = modifiers.length; i < n; i++) {
var modifier = modifiers[i];
if (modifier.kind() === SyntaxKind.DeclareKeyword) {
if (modifier.kind === SyntaxKind.DeclareKeyword) {
this.pushDiagnostic(modifier,
DiagnosticCode.A_declare_modifier_cannot_be_used_with_an_interface_declaration);
return true;
@@ -516,7 +516,7 @@ module TypeScript {
for (var i = 0, n = list.length; i < n; i++) {
var modifier = list[i];
if (SyntaxFacts.isAccessibilityModifier(modifier.kind())) {
if (SyntaxFacts.isAccessibilityModifier(modifier.kind)) {
if (seenAccessibilityModifier) {
this.pushDiagnostic(modifier, DiagnosticCode.Accessibility_modifier_already_seen);
return true;
@@ -530,7 +530,7 @@ module TypeScript {
seenAccessibilityModifier = true;
}
else if (modifier.kind() === SyntaxKind.StaticKeyword) {
else if (modifier.kind === SyntaxKind.StaticKeyword) {
if (seenStaticModifier) {
this.pushDiagnostic(modifier, DiagnosticCode._0_modifier_already_seen, [modifier.text()]);
return true;
@@ -556,7 +556,8 @@ module TypeScript {
}
public visitMethodSignature(node: MethodSignatureSyntax): void {
if (this.checkForTemplatePropertyName(node.propertyName)) {
if (this.checkForDisallowedTemplatePropertyName(node.propertyName) ||
this.checkForDisallowedComputedPropertyName(node.propertyName)) {
return;
}
@@ -564,7 +565,8 @@ module TypeScript {
}
public visitPropertySignature(node: PropertySignatureSyntax): void {
if (this.checkForTemplatePropertyName(node.propertyName)) {
if (this.checkForDisallowedTemplatePropertyName(node.propertyName) ||
this.checkForDisallowedComputedPropertyName(node.propertyName)) {
return;
}
@@ -573,7 +575,7 @@ module TypeScript {
public visitMemberFunctionDeclaration(node: MemberFunctionDeclarationSyntax): void {
if (this.checkClassElementModifiers(node.modifiers) ||
this.checkForTemplatePropertyName(node.propertyName)) {
this.checkForDisallowedTemplatePropertyName(node.propertyName)) {
return;
}
@@ -624,12 +626,12 @@ module TypeScript {
public visitGetAccessor(node: GetAccessorSyntax): void {
if (this.checkForAccessorDeclarationInAmbientContext(node) ||
this.checkEcmaScriptVersionIsAtLeast(node.propertyName, ts.ScriptTarget.ES5, DiagnosticCode.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher) ||
this.checkEcmaScriptVersionIsAtLeast(node.getKeyword, ts.ScriptTarget.ES5, DiagnosticCode.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher) ||
this.checkForDisallowedModifiers(node.modifiers) ||
this.checkClassElementModifiers(node.modifiers) ||
this.checkForDisallowedAccessorTypeParameters(node.callSignature) ||
this.checkGetAccessorParameter(node) ||
this.checkForTemplatePropertyName(node.propertyName)) {
this.checkForDisallowedTemplatePropertyName(node.propertyName)) {
return;
}
@@ -691,7 +693,7 @@ module TypeScript {
}
public visitSimplePropertyAssignment(node: SimplePropertyAssignmentSyntax): void {
if (this.checkForTemplatePropertyName(node.propertyName)) {
if (this.checkForDisallowedTemplatePropertyName(node.propertyName)) {
return;
}
@@ -700,13 +702,13 @@ module TypeScript {
public visitSetAccessor(node: SetAccessorSyntax): void {
if (this.checkForAccessorDeclarationInAmbientContext(node) ||
this.checkEcmaScriptVersionIsAtLeast(node.propertyName, ts.ScriptTarget.ES5, DiagnosticCode.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher) ||
this.checkEcmaScriptVersionIsAtLeast(node.setKeyword, ts.ScriptTarget.ES5, DiagnosticCode.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher) ||
this.checkForDisallowedModifiers(node.modifiers) ||
this.checkClassElementModifiers(node.modifiers) ||
this.checkForDisallowedAccessorTypeParameters(node.callSignature) ||
this.checkForDisallowedSetAccessorTypeAnnotation(node) ||
this.checkSetAccessorParameter(node) ||
this.checkForTemplatePropertyName(node.propertyName)) {
this.checkForDisallowedTemplatePropertyName(node.propertyName)) {
return;
}
@@ -747,7 +749,8 @@ module TypeScript {
}
public visitEnumElement(node: EnumElementSyntax): void {
if (this.checkForTemplatePropertyName(node.propertyName)) {
if (this.checkForDisallowedTemplatePropertyName(node.propertyName) ||
this.checkForDisallowedComputedPropertyName(node.propertyName)) {
return;
}
@@ -763,7 +766,7 @@ module TypeScript {
}
public visitInvocationExpression(node: InvocationExpressionSyntax): void {
if (node.expression.kind() === SyntaxKind.SuperKeyword &&
if (node.expression.kind === SyntaxKind.SuperKeyword &&
node.argumentList.typeArgumentList) {
this.pushDiagnostic(node, DiagnosticCode.super_invocation_cannot_have_type_arguments);
}
@@ -777,13 +780,13 @@ module TypeScript {
for (var i = 0, n = modifiers.length; i < n; i++) {
var modifier = modifiers[i];
if (SyntaxFacts.isAccessibilityModifier(modifier.kind()) ||
modifier.kind() === SyntaxKind.StaticKeyword) {
if (SyntaxFacts.isAccessibilityModifier(modifier.kind) ||
modifier.kind === SyntaxKind.StaticKeyword) {
this.pushDiagnostic(modifier, DiagnosticCode._0_modifier_cannot_appear_on_a_module_element, [modifier.text()]);
return true;
}
if (modifier.kind() === SyntaxKind.DeclareKeyword) {
if (modifier.kind === SyntaxKind.DeclareKeyword) {
if (seenDeclareModifier) {
this.pushDiagnostic(modifier, DiagnosticCode.Accessibility_modifier_already_seen);
return;
@@ -791,7 +794,7 @@ module TypeScript {
seenDeclareModifier = true;
}
else if (modifier.kind() === SyntaxKind.ExportKeyword) {
else if (modifier.kind === SyntaxKind.ExportKeyword) {
if (seenExportModifier) {
this.pushDiagnostic(modifier, DiagnosticCode._0_modifier_already_seen, [modifier.text()]);
return;
@@ -814,9 +817,9 @@ module TypeScript {
if (!node.stringLiteral) {
for (var i = 0, n = node.moduleElements.length; i < n; i++) {
var child = node.moduleElements[i];
if (child.kind() === SyntaxKind.ImportDeclaration) {
if (child.kind === SyntaxKind.ImportDeclaration) {
var importDeclaration = <ImportDeclarationSyntax>child;
if (importDeclaration.moduleReference.kind() === SyntaxKind.ExternalModuleReference) {
if (importDeclaration.moduleReference.kind === SyntaxKind.ExternalModuleReference) {
this.pushDiagnostic(importDeclaration, DiagnosticCode.Import_declarations_in_an_internal_module_cannot_reference_an_external_module);
}
}
@@ -874,7 +877,7 @@ module TypeScript {
for (var i = 0, n = node.moduleElements.length; i < n; i++) {
var child = node.moduleElements[i];
if (child.kind() === SyntaxKind.ExportAssignment) {
if (child.kind === SyntaxKind.ExportAssignment) {
this.pushDiagnostic(child, DiagnosticCode.Export_assignment_cannot_be_used_in_internal_modules);
return true;
}
@@ -898,7 +901,7 @@ module TypeScript {
if (this.inAmbientDeclaration || this.syntaxTree.isDeclaration()) {
// Provide a specialized message for a block as a statement versus the block as a
// function body.
if (node.parent.kind() === SyntaxKind.List) {
if (node.parent.kind === SyntaxKind.List) {
this.pushDiagnostic(firstToken(node), DiagnosticCode.Statements_are_not_allowed_in_ambient_contexts);
}
else {
@@ -979,7 +982,7 @@ module TypeScript {
private inSwitchStatement(ast: ISyntaxElement): boolean {
while (ast) {
if (ast.kind() === SyntaxKind.SwitchStatement) {
if (ast.kind === SyntaxKind.SwitchStatement) {
return true;
}
@@ -994,7 +997,7 @@ module TypeScript {
}
private isIterationStatement(ast: ISyntaxElement): boolean {
switch (ast.kind()) {
switch (ast.kind) {
case SyntaxKind.ForStatement:
case SyntaxKind.ForInStatement:
case SyntaxKind.WhileStatement:
@@ -1026,7 +1029,7 @@ module TypeScript {
element = element.parent;
while (element) {
if (element.kind() === SyntaxKind.LabeledStatement) {
if (element.kind === SyntaxKind.LabeledStatement) {
var labeledStatement = <LabeledStatementSyntax>element;
if (breakable) {
// Breakable labels can be placed on any construct
@@ -1052,7 +1055,7 @@ module TypeScript {
}
private labelIsOnContinuableConstruct(statement: ISyntaxElement): boolean {
switch (statement.kind()) {
switch (statement.kind) {
case SyntaxKind.LabeledStatement:
// Labels work transitively. i.e. if you have:
// foo:
@@ -1338,7 +1341,7 @@ module TypeScript {
}
public visitFunctionPropertyAssignment(node: FunctionPropertyAssignmentSyntax): void {
if (this.checkForTemplatePropertyName(node.propertyName)) {
if (this.checkForDisallowedTemplatePropertyName(node.propertyName)) {
return;
}
@@ -1363,7 +1366,7 @@ module TypeScript {
private checkListSeparators<T extends ISyntaxNodeOrToken>(list: ISeparatedSyntaxList<T>, kind: SyntaxKind): boolean {
for (var i = 0, n = separatorCount(list); i < n; i++) {
var child = separatorAt(list, i);
if (child.kind() !== kind) {
if (child.kind !== kind) {
this.pushDiagnostic(child, DiagnosticCode._0_expected, [SyntaxFacts.getText(kind)]);
}
}
@@ -1410,16 +1413,25 @@ module TypeScript {
public visitVariableDeclarator(node: VariableDeclaratorSyntax): void {
if (this.checkVariableDeclaratorInitializer(node) ||
this.checkVariableDeclaratorIdentifier(node) ||
this.checkForTemplatePropertyName(node.propertyName)) {
this.checkForDisallowedTemplatePropertyName(node.propertyName)) {
return;
}
super.visitVariableDeclarator(node);
}
private checkForTemplatePropertyName(token: ISyntaxToken): boolean {
if (token.kind() === SyntaxKind.NoSubstitutionTemplateToken) {
this.pushDiagnostic(token, DiagnosticCode.Template_literal_cannot_be_used_as_an_element_name);
private checkForDisallowedTemplatePropertyName(propertyName: IPropertyNameSyntax): boolean {
if (propertyName.kind === SyntaxKind.NoSubstitutionTemplateToken) {
this.pushDiagnostic(propertyName, DiagnosticCode.Template_literal_cannot_be_used_as_an_element_name);
return true;
}
return false;
}
private checkForDisallowedComputedPropertyName(propertyName: IPropertyNameSyntax): boolean {
if (propertyName.kind === SyntaxKind.ComputedPropertyName) {
this.pushDiagnostic(propertyName, DiagnosticCode.Computed_property_names_cannot_be_used_here);
return true;
}
@@ -1427,8 +1439,9 @@ module TypeScript {
}
private checkVariableDeclaratorIdentifier(node: VariableDeclaratorSyntax): boolean {
if (node.parent.kind() !== SyntaxKind.MemberVariableDeclaration) {
if (this.checkForDisallowedEvalOrArguments(node, node.propertyName)) {
if (node.parent.kind !== SyntaxKind.MemberVariableDeclaration) {
Debug.assert(isToken(node.propertyName), "A normal variable declarator must always have a token for a name.");
if (this.checkForDisallowedEvalOrArguments(node, <ISyntaxToken>node.propertyName)) {
return true;
}
}
@@ -1460,8 +1473,8 @@ module TypeScript {
private checkConstructorModifiers(modifiers: ISyntaxToken[]): boolean {
for (var i = 0, n = modifiers.length; i < n; i++) {
var child = modifiers[i];
if (child.kind() !== SyntaxKind.PublicKeyword) {
this.pushDiagnostic(child, DiagnosticCode._0_modifier_cannot_appear_on_a_constructor_declaration, [SyntaxFacts.getText(child.kind())]);
if (child.kind !== SyntaxKind.PublicKeyword) {
this.pushDiagnostic(child, DiagnosticCode._0_modifier_cannot_appear_on_a_constructor_declaration, [SyntaxFacts.getText(child.kind)]);
return true;
}
}
@@ -1531,7 +1544,7 @@ module TypeScript {
}
private isPreIncrementOrDecrementExpression(node: PrefixUnaryExpressionSyntax) {
switch (node.operatorToken.kind()) {
switch (node.operatorToken.kind) {
case SyntaxKind.MinusMinusToken:
case SyntaxKind.PlusPlusToken:
return true;
@@ -1541,7 +1554,7 @@ module TypeScript {
}
public visitDeleteExpression(node: DeleteExpressionSyntax): void {
if (parsedInStrictMode(node) && node.expression.kind() === SyntaxKind.IdentifierName) {
if (parsedInStrictMode(node) && node.expression.kind === SyntaxKind.IdentifierName) {
this.pushDiagnostic(firstToken(node), DiagnosticCode.delete_cannot_be_called_on_an_identifier_in_strict_mode);
return;
}
@@ -1550,7 +1563,7 @@ module TypeScript {
}
private checkIllegalAssignment(node: BinaryExpressionSyntax): boolean {
if (parsedInStrictMode(node) && SyntaxFacts.isAssignmentOperatorToken(node.operatorToken.kind()) && this.isEvalOrArguments(node.left)) {
if (parsedInStrictMode(node) && SyntaxFacts.isAssignmentOperatorToken(node.operatorToken.kind) && this.isEvalOrArguments(node.left)) {
this.pushDiagnostic(node.operatorToken, DiagnosticCode.Invalid_use_of_0_in_strict_mode, [this.getEvalOrArguments(node.left)]);
return true;
}
@@ -1559,7 +1572,7 @@ module TypeScript {
}
private getEvalOrArguments(expr: IExpressionSyntax): string {
if (expr.kind() === SyntaxKind.IdentifierName) {
if (expr.kind === SyntaxKind.IdentifierName) {
var text = tokenValueText(<ISyntaxToken>expr);
if (text === "eval" || text === "arguments") {
return text;
@@ -1582,7 +1595,7 @@ module TypeScript {
}
private checkConstraintType(node: ConstraintSyntax): boolean {
if (!SyntaxFacts.isType(node.typeOrExpression.kind())) {
if (!SyntaxFacts.isType(node.typeOrExpression.kind)) {
this.pushDiagnostic(node.typeOrExpression, DiagnosticCode.Type_expected);
return true;
}
@@ -1639,13 +1652,13 @@ module TypeScript {
var moduleElement = node.moduleElements[i];
var _firstToken = firstToken(moduleElement);
if (_firstToken && _firstToken.kind() === SyntaxKind.ExportKeyword) {
if (_firstToken && _firstToken.kind === SyntaxKind.ExportKeyword) {
return new TextSpan(start(_firstToken), width(_firstToken));
}
if (moduleElement.kind() === SyntaxKind.ImportDeclaration) {
if (moduleElement.kind === SyntaxKind.ImportDeclaration) {
var importDecl = <ImportDeclarationSyntax>moduleElement;
if (importDecl.moduleReference.kind() === SyntaxKind.ExternalModuleReference) {
if (importDecl.moduleReference.kind === SyntaxKind.ExternalModuleReference) {
var literal = (<TypeScript.ExternalModuleReferenceSyntax>importDecl.moduleReference).stringLiteral;
return new TextSpan(start(literal), width(literal));
}
@@ -1,879 +0,0 @@
module TypeScript {
export function childCount(element: ISyntaxElement): number {
if (isList(element)) { return (<ISyntaxNodeOrToken[]>element).length; }
switch (element.kind()) {
case SyntaxKind.SourceUnit: return 2;
case SyntaxKind.QualifiedName: return 3;
case SyntaxKind.ObjectType: return 3;
case SyntaxKind.FunctionType: return 4;
case SyntaxKind.ArrayType: return 3;
case SyntaxKind.ConstructorType: return 5;
case SyntaxKind.GenericType: return 2;
case SyntaxKind.TypeQuery: return 2;
case SyntaxKind.TupleType: return 3;
case SyntaxKind.UnionType: return 3;
case SyntaxKind.ParenthesizedType: return 3;
case SyntaxKind.InterfaceDeclaration: return 6;
case SyntaxKind.FunctionDeclaration: return 6;
case SyntaxKind.ModuleDeclaration: return 7;
case SyntaxKind.ClassDeclaration: return 8;
case SyntaxKind.EnumDeclaration: return 6;
case SyntaxKind.ImportDeclaration: return 6;
case SyntaxKind.ExportAssignment: return 4;
case SyntaxKind.MemberFunctionDeclaration: return 5;
case SyntaxKind.MemberVariableDeclaration: return 3;
case SyntaxKind.ConstructorDeclaration: return 5;
case SyntaxKind.IndexMemberDeclaration: return 3;
case SyntaxKind.GetAccessor: return 5;
case SyntaxKind.SetAccessor: return 5;
case SyntaxKind.PropertySignature: return 3;
case SyntaxKind.CallSignature: return 3;
case SyntaxKind.ConstructSignature: return 2;
case SyntaxKind.IndexSignature: return 4;
case SyntaxKind.MethodSignature: return 3;
case SyntaxKind.Block: return 3;
case SyntaxKind.IfStatement: return 6;
case SyntaxKind.VariableStatement: return 3;
case SyntaxKind.ExpressionStatement: return 2;
case SyntaxKind.ReturnStatement: return 3;
case SyntaxKind.SwitchStatement: return 7;
case SyntaxKind.BreakStatement: return 3;
case SyntaxKind.ContinueStatement: return 3;
case SyntaxKind.ForStatement: return 10;
case SyntaxKind.ForInStatement: return 8;
case SyntaxKind.EmptyStatement: return 1;
case SyntaxKind.ThrowStatement: return 3;
case SyntaxKind.WhileStatement: return 5;
case SyntaxKind.TryStatement: return 4;
case SyntaxKind.LabeledStatement: return 3;
case SyntaxKind.DoStatement: return 7;
case SyntaxKind.DebuggerStatement: return 2;
case SyntaxKind.WithStatement: return 5;
case SyntaxKind.PrefixUnaryExpression: return 2;
case SyntaxKind.DeleteExpression: return 2;
case SyntaxKind.TypeOfExpression: return 2;
case SyntaxKind.VoidExpression: return 2;
case SyntaxKind.ConditionalExpression: return 5;
case SyntaxKind.BinaryExpression: return 3;
case SyntaxKind.PostfixUnaryExpression: return 2;
case SyntaxKind.MemberAccessExpression: return 3;
case SyntaxKind.InvocationExpression: return 2;
case SyntaxKind.ArrayLiteralExpression: return 3;
case SyntaxKind.ObjectLiteralExpression: return 3;
case SyntaxKind.ObjectCreationExpression: return 3;
case SyntaxKind.ParenthesizedExpression: return 3;
case SyntaxKind.ParenthesizedArrowFunctionExpression: return 4;
case SyntaxKind.SimpleArrowFunctionExpression: return 4;
case SyntaxKind.CastExpression: return 4;
case SyntaxKind.ElementAccessExpression: return 4;
case SyntaxKind.FunctionExpression: return 4;
case SyntaxKind.OmittedExpression: return 0;
case SyntaxKind.TemplateExpression: return 2;
case SyntaxKind.TemplateAccessExpression: return 2;
case SyntaxKind.VariableDeclaration: return 2;
case SyntaxKind.VariableDeclarator: return 3;
case SyntaxKind.ArgumentList: return 4;
case SyntaxKind.ParameterList: return 3;
case SyntaxKind.TypeArgumentList: return 3;
case SyntaxKind.TypeParameterList: return 3;
case SyntaxKind.HeritageClause: return 2;
case SyntaxKind.EqualsValueClause: return 2;
case SyntaxKind.CaseSwitchClause: return 4;
case SyntaxKind.DefaultSwitchClause: return 3;
case SyntaxKind.ElseClause: return 2;
case SyntaxKind.CatchClause: return 6;
case SyntaxKind.FinallyClause: return 2;
case SyntaxKind.TemplateClause: return 2;
case SyntaxKind.TypeParameter: return 2;
case SyntaxKind.Constraint: return 2;
case SyntaxKind.SimplePropertyAssignment: return 3;
case SyntaxKind.FunctionPropertyAssignment: return 3;
case SyntaxKind.Parameter: return 6;
case SyntaxKind.EnumElement: return 2;
case SyntaxKind.TypeAnnotation: return 2;
case SyntaxKind.ExternalModuleReference: return 4;
case SyntaxKind.ModuleNameModuleReference: return 1;
default: return 0;
}
}
function sourceUnitChildAt(node: SourceUnitSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.moduleElements;
case 1: return node.endOfFileToken;
}
}
function qualifiedNameChildAt(node: QualifiedNameSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.left;
case 1: return node.dotToken;
case 2: return node.right;
}
}
function objectTypeChildAt(node: ObjectTypeSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.openBraceToken;
case 1: return node.typeMembers;
case 2: return node.closeBraceToken;
}
}
function functionTypeChildAt(node: FunctionTypeSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.typeParameterList;
case 1: return node.parameterList;
case 2: return node.equalsGreaterThanToken;
case 3: return node.type;
}
}
function arrayTypeChildAt(node: ArrayTypeSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.type;
case 1: return node.openBracketToken;
case 2: return node.closeBracketToken;
}
}
function constructorTypeChildAt(node: ConstructorTypeSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.newKeyword;
case 1: return node.typeParameterList;
case 2: return node.parameterList;
case 3: return node.equalsGreaterThanToken;
case 4: return node.type;
}
}
function genericTypeChildAt(node: GenericTypeSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.name;
case 1: return node.typeArgumentList;
}
}
function typeQueryChildAt(node: TypeQuerySyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.typeOfKeyword;
case 1: return node.name;
}
}
function tupleTypeChildAt(node: TupleTypeSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.openBracketToken;
case 1: return node.types;
case 2: return node.closeBracketToken;
}
}
function unionTypeChildAt(node: UnionTypeSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.left;
case 1: return node.barToken;
case 2: return node.right;
}
}
function parenthesizedTypeChildAt(node: ParenthesizedTypeSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.openParenToken;
case 1: return node.type;
case 2: return node.closeParenToken;
}
}
function interfaceDeclarationChildAt(node: InterfaceDeclarationSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.modifiers;
case 1: return node.interfaceKeyword;
case 2: return node.identifier;
case 3: return node.typeParameterList;
case 4: return node.heritageClauses;
case 5: return node.body;
}
}
function functionDeclarationChildAt(node: FunctionDeclarationSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.modifiers;
case 1: return node.functionKeyword;
case 2: return node.identifier;
case 3: return node.callSignature;
case 4: return node.block;
case 5: return node.semicolonToken;
}
}
function moduleDeclarationChildAt(node: ModuleDeclarationSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.modifiers;
case 1: return node.moduleKeyword;
case 2: return node.name;
case 3: return node.stringLiteral;
case 4: return node.openBraceToken;
case 5: return node.moduleElements;
case 6: return node.closeBraceToken;
}
}
function classDeclarationChildAt(node: ClassDeclarationSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.modifiers;
case 1: return node.classKeyword;
case 2: return node.identifier;
case 3: return node.typeParameterList;
case 4: return node.heritageClauses;
case 5: return node.openBraceToken;
case 6: return node.classElements;
case 7: return node.closeBraceToken;
}
}
function enumDeclarationChildAt(node: EnumDeclarationSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.modifiers;
case 1: return node.enumKeyword;
case 2: return node.identifier;
case 3: return node.openBraceToken;
case 4: return node.enumElements;
case 5: return node.closeBraceToken;
}
}
function importDeclarationChildAt(node: ImportDeclarationSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.modifiers;
case 1: return node.importKeyword;
case 2: return node.identifier;
case 3: return node.equalsToken;
case 4: return node.moduleReference;
case 5: return node.semicolonToken;
}
}
function exportAssignmentChildAt(node: ExportAssignmentSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.exportKeyword;
case 1: return node.equalsToken;
case 2: return node.identifier;
case 3: return node.semicolonToken;
}
}
function memberFunctionDeclarationChildAt(node: MemberFunctionDeclarationSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.modifiers;
case 1: return node.propertyName;
case 2: return node.callSignature;
case 3: return node.block;
case 4: return node.semicolonToken;
}
}
function memberVariableDeclarationChildAt(node: MemberVariableDeclarationSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.modifiers;
case 1: return node.variableDeclarator;
case 2: return node.semicolonToken;
}
}
function constructorDeclarationChildAt(node: ConstructorDeclarationSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.modifiers;
case 1: return node.constructorKeyword;
case 2: return node.callSignature;
case 3: return node.block;
case 4: return node.semicolonToken;
}
}
function indexMemberDeclarationChildAt(node: IndexMemberDeclarationSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.modifiers;
case 1: return node.indexSignature;
case 2: return node.semicolonToken;
}
}
function getAccessorChildAt(node: GetAccessorSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.modifiers;
case 1: return node.getKeyword;
case 2: return node.propertyName;
case 3: return node.callSignature;
case 4: return node.block;
}
}
function setAccessorChildAt(node: SetAccessorSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.modifiers;
case 1: return node.setKeyword;
case 2: return node.propertyName;
case 3: return node.callSignature;
case 4: return node.block;
}
}
function propertySignatureChildAt(node: PropertySignatureSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.propertyName;
case 1: return node.questionToken;
case 2: return node.typeAnnotation;
}
}
function callSignatureChildAt(node: CallSignatureSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.typeParameterList;
case 1: return node.parameterList;
case 2: return node.typeAnnotation;
}
}
function constructSignatureChildAt(node: ConstructSignatureSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.newKeyword;
case 1: return node.callSignature;
}
}
function indexSignatureChildAt(node: IndexSignatureSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.openBracketToken;
case 1: return node.parameters;
case 2: return node.closeBracketToken;
case 3: return node.typeAnnotation;
}
}
function methodSignatureChildAt(node: MethodSignatureSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.propertyName;
case 1: return node.questionToken;
case 2: return node.callSignature;
}
}
function blockChildAt(node: BlockSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.openBraceToken;
case 1: return node.statements;
case 2: return node.closeBraceToken;
}
}
function ifStatementChildAt(node: IfStatementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.ifKeyword;
case 1: return node.openParenToken;
case 2: return node.condition;
case 3: return node.closeParenToken;
case 4: return node.statement;
case 5: return node.elseClause;
}
}
function variableStatementChildAt(node: VariableStatementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.modifiers;
case 1: return node.variableDeclaration;
case 2: return node.semicolonToken;
}
}
function expressionStatementChildAt(node: ExpressionStatementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.expression;
case 1: return node.semicolonToken;
}
}
function returnStatementChildAt(node: ReturnStatementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.returnKeyword;
case 1: return node.expression;
case 2: return node.semicolonToken;
}
}
function switchStatementChildAt(node: SwitchStatementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.switchKeyword;
case 1: return node.openParenToken;
case 2: return node.expression;
case 3: return node.closeParenToken;
case 4: return node.openBraceToken;
case 5: return node.switchClauses;
case 6: return node.closeBraceToken;
}
}
function breakStatementChildAt(node: BreakStatementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.breakKeyword;
case 1: return node.identifier;
case 2: return node.semicolonToken;
}
}
function continueStatementChildAt(node: ContinueStatementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.continueKeyword;
case 1: return node.identifier;
case 2: return node.semicolonToken;
}
}
function forStatementChildAt(node: ForStatementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.forKeyword;
case 1: return node.openParenToken;
case 2: return node.variableDeclaration;
case 3: return node.initializer;
case 4: return node.firstSemicolonToken;
case 5: return node.condition;
case 6: return node.secondSemicolonToken;
case 7: return node.incrementor;
case 8: return node.closeParenToken;
case 9: return node.statement;
}
}
function forInStatementChildAt(node: ForInStatementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.forKeyword;
case 1: return node.openParenToken;
case 2: return node.variableDeclaration;
case 3: return node.left;
case 4: return node.inKeyword;
case 5: return node.expression;
case 6: return node.closeParenToken;
case 7: return node.statement;
}
}
function emptyStatementChildAt(node: EmptyStatementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.semicolonToken;
}
}
function throwStatementChildAt(node: ThrowStatementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.throwKeyword;
case 1: return node.expression;
case 2: return node.semicolonToken;
}
}
function whileStatementChildAt(node: WhileStatementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.whileKeyword;
case 1: return node.openParenToken;
case 2: return node.condition;
case 3: return node.closeParenToken;
case 4: return node.statement;
}
}
function tryStatementChildAt(node: TryStatementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.tryKeyword;
case 1: return node.block;
case 2: return node.catchClause;
case 3: return node.finallyClause;
}
}
function labeledStatementChildAt(node: LabeledStatementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.identifier;
case 1: return node.colonToken;
case 2: return node.statement;
}
}
function doStatementChildAt(node: DoStatementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.doKeyword;
case 1: return node.statement;
case 2: return node.whileKeyword;
case 3: return node.openParenToken;
case 4: return node.condition;
case 5: return node.closeParenToken;
case 6: return node.semicolonToken;
}
}
function debuggerStatementChildAt(node: DebuggerStatementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.debuggerKeyword;
case 1: return node.semicolonToken;
}
}
function withStatementChildAt(node: WithStatementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.withKeyword;
case 1: return node.openParenToken;
case 2: return node.condition;
case 3: return node.closeParenToken;
case 4: return node.statement;
}
}
function prefixUnaryExpressionChildAt(node: PrefixUnaryExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.operatorToken;
case 1: return node.operand;
}
}
function deleteExpressionChildAt(node: DeleteExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.deleteKeyword;
case 1: return node.expression;
}
}
function typeOfExpressionChildAt(node: TypeOfExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.typeOfKeyword;
case 1: return node.expression;
}
}
function voidExpressionChildAt(node: VoidExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.voidKeyword;
case 1: return node.expression;
}
}
function conditionalExpressionChildAt(node: ConditionalExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.condition;
case 1: return node.questionToken;
case 2: return node.whenTrue;
case 3: return node.colonToken;
case 4: return node.whenFalse;
}
}
function binaryExpressionChildAt(node: BinaryExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.left;
case 1: return node.operatorToken;
case 2: return node.right;
}
}
function postfixUnaryExpressionChildAt(node: PostfixUnaryExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.operand;
case 1: return node.operatorToken;
}
}
function memberAccessExpressionChildAt(node: MemberAccessExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.expression;
case 1: return node.dotToken;
case 2: return node.name;
}
}
function invocationExpressionChildAt(node: InvocationExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.expression;
case 1: return node.argumentList;
}
}
function arrayLiteralExpressionChildAt(node: ArrayLiteralExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.openBracketToken;
case 1: return node.expressions;
case 2: return node.closeBracketToken;
}
}
function objectLiteralExpressionChildAt(node: ObjectLiteralExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.openBraceToken;
case 1: return node.propertyAssignments;
case 2: return node.closeBraceToken;
}
}
function objectCreationExpressionChildAt(node: ObjectCreationExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.newKeyword;
case 1: return node.expression;
case 2: return node.argumentList;
}
}
function parenthesizedExpressionChildAt(node: ParenthesizedExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.openParenToken;
case 1: return node.expression;
case 2: return node.closeParenToken;
}
}
function parenthesizedArrowFunctionExpressionChildAt(node: ParenthesizedArrowFunctionExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.callSignature;
case 1: return node.equalsGreaterThanToken;
case 2: return node.block;
case 3: return node.expression;
}
}
function simpleArrowFunctionExpressionChildAt(node: SimpleArrowFunctionExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.parameter;
case 1: return node.equalsGreaterThanToken;
case 2: return node.block;
case 3: return node.expression;
}
}
function castExpressionChildAt(node: CastExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.lessThanToken;
case 1: return node.type;
case 2: return node.greaterThanToken;
case 3: return node.expression;
}
}
function elementAccessExpressionChildAt(node: ElementAccessExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.expression;
case 1: return node.openBracketToken;
case 2: return node.argumentExpression;
case 3: return node.closeBracketToken;
}
}
function functionExpressionChildAt(node: FunctionExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.functionKeyword;
case 1: return node.identifier;
case 2: return node.callSignature;
case 3: return node.block;
}
}
function omittedExpressionChildAt(node: OmittedExpressionSyntax, index: number): ISyntaxElement {
throw Errors.invalidOperation();
}
function templateExpressionChildAt(node: TemplateExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.templateStartToken;
case 1: return node.templateClauses;
}
}
function templateAccessExpressionChildAt(node: TemplateAccessExpressionSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.expression;
case 1: return node.templateExpression;
}
}
function variableDeclarationChildAt(node: VariableDeclarationSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.varKeyword;
case 1: return node.variableDeclarators;
}
}
function variableDeclaratorChildAt(node: VariableDeclaratorSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.propertyName;
case 1: return node.typeAnnotation;
case 2: return node.equalsValueClause;
}
}
function argumentListChildAt(node: ArgumentListSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.typeArgumentList;
case 1: return node.openParenToken;
case 2: return node.arguments;
case 3: return node.closeParenToken;
}
}
function parameterListChildAt(node: ParameterListSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.openParenToken;
case 1: return node.parameters;
case 2: return node.closeParenToken;
}
}
function typeArgumentListChildAt(node: TypeArgumentListSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.lessThanToken;
case 1: return node.typeArguments;
case 2: return node.greaterThanToken;
}
}
function typeParameterListChildAt(node: TypeParameterListSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.lessThanToken;
case 1: return node.typeParameters;
case 2: return node.greaterThanToken;
}
}
function heritageClauseChildAt(node: HeritageClauseSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.extendsOrImplementsKeyword;
case 1: return node.typeNames;
}
}
function equalsValueClauseChildAt(node: EqualsValueClauseSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.equalsToken;
case 1: return node.value;
}
}
function caseSwitchClauseChildAt(node: CaseSwitchClauseSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.caseKeyword;
case 1: return node.expression;
case 2: return node.colonToken;
case 3: return node.statements;
}
}
function defaultSwitchClauseChildAt(node: DefaultSwitchClauseSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.defaultKeyword;
case 1: return node.colonToken;
case 2: return node.statements;
}
}
function elseClauseChildAt(node: ElseClauseSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.elseKeyword;
case 1: return node.statement;
}
}
function catchClauseChildAt(node: CatchClauseSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.catchKeyword;
case 1: return node.openParenToken;
case 2: return node.identifier;
case 3: return node.typeAnnotation;
case 4: return node.closeParenToken;
case 5: return node.block;
}
}
function finallyClauseChildAt(node: FinallyClauseSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.finallyKeyword;
case 1: return node.block;
}
}
function templateClauseChildAt(node: TemplateClauseSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.expression;
case 1: return node.templateMiddleOrEndToken;
}
}
function typeParameterChildAt(node: TypeParameterSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.identifier;
case 1: return node.constraint;
}
}
function constraintChildAt(node: ConstraintSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.extendsKeyword;
case 1: return node.typeOrExpression;
}
}
function simplePropertyAssignmentChildAt(node: SimplePropertyAssignmentSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.propertyName;
case 1: return node.colonToken;
case 2: return node.expression;
}
}
function functionPropertyAssignmentChildAt(node: FunctionPropertyAssignmentSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.propertyName;
case 1: return node.callSignature;
case 2: return node.block;
}
}
function parameterChildAt(node: ParameterSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.dotDotDotToken;
case 1: return node.modifiers;
case 2: return node.identifier;
case 3: return node.questionToken;
case 4: return node.typeAnnotation;
case 5: return node.equalsValueClause;
}
}
function enumElementChildAt(node: EnumElementSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.propertyName;
case 1: return node.equalsValueClause;
}
}
function typeAnnotationChildAt(node: TypeAnnotationSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.colonToken;
case 1: return node.type;
}
}
function externalModuleReferenceChildAt(node: ExternalModuleReferenceSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.requireKeyword;
case 1: return node.openParenToken;
case 2: return node.stringLiteral;
case 3: return node.closeParenToken;
}
}
function moduleNameModuleReferenceChildAt(node: ModuleNameModuleReferenceSyntax, index: number): ISyntaxElement {
switch (index) {
case 0: return node.moduleName;
}
}
export function childAt(element: ISyntaxElement, index: number): ISyntaxElement {
if (isList(element)) { return (<ISyntaxNodeOrToken[]>element)[index]; }
switch (element.kind()) {
case SyntaxKind.SourceUnit: return sourceUnitChildAt(<SourceUnitSyntax>element, index);
case SyntaxKind.QualifiedName: return qualifiedNameChildAt(<QualifiedNameSyntax>element, index);
case SyntaxKind.ObjectType: return objectTypeChildAt(<ObjectTypeSyntax>element, index);
case SyntaxKind.FunctionType: return functionTypeChildAt(<FunctionTypeSyntax>element, index);
case SyntaxKind.ArrayType: return arrayTypeChildAt(<ArrayTypeSyntax>element, index);
case SyntaxKind.ConstructorType: return constructorTypeChildAt(<ConstructorTypeSyntax>element, index);
case SyntaxKind.GenericType: return genericTypeChildAt(<GenericTypeSyntax>element, index);
case SyntaxKind.TypeQuery: return typeQueryChildAt(<TypeQuerySyntax>element, index);
case SyntaxKind.TupleType: return tupleTypeChildAt(<TupleTypeSyntax>element, index);
case SyntaxKind.UnionType: return unionTypeChildAt(<UnionTypeSyntax>element, index);
case SyntaxKind.ParenthesizedType: return parenthesizedTypeChildAt(<ParenthesizedTypeSyntax>element, index);
case SyntaxKind.InterfaceDeclaration: return interfaceDeclarationChildAt(<InterfaceDeclarationSyntax>element, index);
case SyntaxKind.FunctionDeclaration: return functionDeclarationChildAt(<FunctionDeclarationSyntax>element, index);
case SyntaxKind.ModuleDeclaration: return moduleDeclarationChildAt(<ModuleDeclarationSyntax>element, index);
case SyntaxKind.ClassDeclaration: return classDeclarationChildAt(<ClassDeclarationSyntax>element, index);
case SyntaxKind.EnumDeclaration: return enumDeclarationChildAt(<EnumDeclarationSyntax>element, index);
case SyntaxKind.ImportDeclaration: return importDeclarationChildAt(<ImportDeclarationSyntax>element, index);
case SyntaxKind.ExportAssignment: return exportAssignmentChildAt(<ExportAssignmentSyntax>element, index);
case SyntaxKind.MemberFunctionDeclaration: return memberFunctionDeclarationChildAt(<MemberFunctionDeclarationSyntax>element, index);
case SyntaxKind.MemberVariableDeclaration: return memberVariableDeclarationChildAt(<MemberVariableDeclarationSyntax>element, index);
case SyntaxKind.ConstructorDeclaration: return constructorDeclarationChildAt(<ConstructorDeclarationSyntax>element, index);
case SyntaxKind.IndexMemberDeclaration: return indexMemberDeclarationChildAt(<IndexMemberDeclarationSyntax>element, index);
case SyntaxKind.GetAccessor: return getAccessorChildAt(<GetAccessorSyntax>element, index);
case SyntaxKind.SetAccessor: return setAccessorChildAt(<SetAccessorSyntax>element, index);
case SyntaxKind.PropertySignature: return propertySignatureChildAt(<PropertySignatureSyntax>element, index);
case SyntaxKind.CallSignature: return callSignatureChildAt(<CallSignatureSyntax>element, index);
case SyntaxKind.ConstructSignature: return constructSignatureChildAt(<ConstructSignatureSyntax>element, index);
case SyntaxKind.IndexSignature: return indexSignatureChildAt(<IndexSignatureSyntax>element, index);
case SyntaxKind.MethodSignature: return methodSignatureChildAt(<MethodSignatureSyntax>element, index);
case SyntaxKind.Block: return blockChildAt(<BlockSyntax>element, index);
case SyntaxKind.IfStatement: return ifStatementChildAt(<IfStatementSyntax>element, index);
case SyntaxKind.VariableStatement: return variableStatementChildAt(<VariableStatementSyntax>element, index);
case SyntaxKind.ExpressionStatement: return expressionStatementChildAt(<ExpressionStatementSyntax>element, index);
case SyntaxKind.ReturnStatement: return returnStatementChildAt(<ReturnStatementSyntax>element, index);
case SyntaxKind.SwitchStatement: return switchStatementChildAt(<SwitchStatementSyntax>element, index);
case SyntaxKind.BreakStatement: return breakStatementChildAt(<BreakStatementSyntax>element, index);
case SyntaxKind.ContinueStatement: return continueStatementChildAt(<ContinueStatementSyntax>element, index);
case SyntaxKind.ForStatement: return forStatementChildAt(<ForStatementSyntax>element, index);
case SyntaxKind.ForInStatement: return forInStatementChildAt(<ForInStatementSyntax>element, index);
case SyntaxKind.EmptyStatement: return emptyStatementChildAt(<EmptyStatementSyntax>element, index);
case SyntaxKind.ThrowStatement: return throwStatementChildAt(<ThrowStatementSyntax>element, index);
case SyntaxKind.WhileStatement: return whileStatementChildAt(<WhileStatementSyntax>element, index);
case SyntaxKind.TryStatement: return tryStatementChildAt(<TryStatementSyntax>element, index);
case SyntaxKind.LabeledStatement: return labeledStatementChildAt(<LabeledStatementSyntax>element, index);
case SyntaxKind.DoStatement: return doStatementChildAt(<DoStatementSyntax>element, index);
case SyntaxKind.DebuggerStatement: return debuggerStatementChildAt(<DebuggerStatementSyntax>element, index);
case SyntaxKind.WithStatement: return withStatementChildAt(<WithStatementSyntax>element, index);
case SyntaxKind.PrefixUnaryExpression: return prefixUnaryExpressionChildAt(<PrefixUnaryExpressionSyntax>element, index);
case SyntaxKind.DeleteExpression: return deleteExpressionChildAt(<DeleteExpressionSyntax>element, index);
case SyntaxKind.TypeOfExpression: return typeOfExpressionChildAt(<TypeOfExpressionSyntax>element, index);
case SyntaxKind.VoidExpression: return voidExpressionChildAt(<VoidExpressionSyntax>element, index);
case SyntaxKind.ConditionalExpression: return conditionalExpressionChildAt(<ConditionalExpressionSyntax>element, index);
case SyntaxKind.BinaryExpression: return binaryExpressionChildAt(<BinaryExpressionSyntax>element, index);
case SyntaxKind.PostfixUnaryExpression: return postfixUnaryExpressionChildAt(<PostfixUnaryExpressionSyntax>element, index);
case SyntaxKind.MemberAccessExpression: return memberAccessExpressionChildAt(<MemberAccessExpressionSyntax>element, index);
case SyntaxKind.InvocationExpression: return invocationExpressionChildAt(<InvocationExpressionSyntax>element, index);
case SyntaxKind.ArrayLiteralExpression: return arrayLiteralExpressionChildAt(<ArrayLiteralExpressionSyntax>element, index);
case SyntaxKind.ObjectLiteralExpression: return objectLiteralExpressionChildAt(<ObjectLiteralExpressionSyntax>element, index);
case SyntaxKind.ObjectCreationExpression: return objectCreationExpressionChildAt(<ObjectCreationExpressionSyntax>element, index);
case SyntaxKind.ParenthesizedExpression: return parenthesizedExpressionChildAt(<ParenthesizedExpressionSyntax>element, index);
case SyntaxKind.ParenthesizedArrowFunctionExpression: return parenthesizedArrowFunctionExpressionChildAt(<ParenthesizedArrowFunctionExpressionSyntax>element, index);
case SyntaxKind.SimpleArrowFunctionExpression: return simpleArrowFunctionExpressionChildAt(<SimpleArrowFunctionExpressionSyntax>element, index);
case SyntaxKind.CastExpression: return castExpressionChildAt(<CastExpressionSyntax>element, index);
case SyntaxKind.ElementAccessExpression: return elementAccessExpressionChildAt(<ElementAccessExpressionSyntax>element, index);
case SyntaxKind.FunctionExpression: return functionExpressionChildAt(<FunctionExpressionSyntax>element, index);
case SyntaxKind.OmittedExpression: return omittedExpressionChildAt(<OmittedExpressionSyntax>element, index);
case SyntaxKind.TemplateExpression: return templateExpressionChildAt(<TemplateExpressionSyntax>element, index);
case SyntaxKind.TemplateAccessExpression: return templateAccessExpressionChildAt(<TemplateAccessExpressionSyntax>element, index);
case SyntaxKind.VariableDeclaration: return variableDeclarationChildAt(<VariableDeclarationSyntax>element, index);
case SyntaxKind.VariableDeclarator: return variableDeclaratorChildAt(<VariableDeclaratorSyntax>element, index);
case SyntaxKind.ArgumentList: return argumentListChildAt(<ArgumentListSyntax>element, index);
case SyntaxKind.ParameterList: return parameterListChildAt(<ParameterListSyntax>element, index);
case SyntaxKind.TypeArgumentList: return typeArgumentListChildAt(<TypeArgumentListSyntax>element, index);
case SyntaxKind.TypeParameterList: return typeParameterListChildAt(<TypeParameterListSyntax>element, index);
case SyntaxKind.HeritageClause: return heritageClauseChildAt(<HeritageClauseSyntax>element, index);
case SyntaxKind.EqualsValueClause: return equalsValueClauseChildAt(<EqualsValueClauseSyntax>element, index);
case SyntaxKind.CaseSwitchClause: return caseSwitchClauseChildAt(<CaseSwitchClauseSyntax>element, index);
case SyntaxKind.DefaultSwitchClause: return defaultSwitchClauseChildAt(<DefaultSwitchClauseSyntax>element, index);
case SyntaxKind.ElseClause: return elseClauseChildAt(<ElseClauseSyntax>element, index);
case SyntaxKind.CatchClause: return catchClauseChildAt(<CatchClauseSyntax>element, index);
case SyntaxKind.FinallyClause: return finallyClauseChildAt(<FinallyClauseSyntax>element, index);
case SyntaxKind.TemplateClause: return templateClauseChildAt(<TemplateClauseSyntax>element, index);
case SyntaxKind.TypeParameter: return typeParameterChildAt(<TypeParameterSyntax>element, index);
case SyntaxKind.Constraint: return constraintChildAt(<ConstraintSyntax>element, index);
case SyntaxKind.SimplePropertyAssignment: return simplePropertyAssignmentChildAt(<SimplePropertyAssignmentSyntax>element, index);
case SyntaxKind.FunctionPropertyAssignment: return functionPropertyAssignmentChildAt(<FunctionPropertyAssignmentSyntax>element, index);
case SyntaxKind.Parameter: return parameterChildAt(<ParameterSyntax>element, index);
case SyntaxKind.EnumElement: return enumElementChildAt(<EnumElementSyntax>element, index);
case SyntaxKind.TypeAnnotation: return typeAnnotationChildAt(<TypeAnnotationSyntax>element, index);
case SyntaxKind.ExternalModuleReference: return externalModuleReferenceChildAt(<ExternalModuleReferenceSyntax>element, index);
case SyntaxKind.ModuleNameModuleReference: return moduleNameModuleReferenceChildAt(<ModuleNameModuleReferenceSyntax>element, index);
}
}
}
+37 -27
View File
@@ -1,9 +1,19 @@
///<reference path='references.ts' />
module TypeScript {
export class SyntaxUtilities {
public static isAnyFunctionExpressionOrDeclaration(ast: ISyntaxElement): boolean {
switch (ast.kind()) {
export function childCount(element: ISyntaxElement): number {
if (isList(element)) { return (<ISyntaxNodeOrToken[]>element).length; }
return (<ISyntaxNodeOrToken>element).childCount;
}
export function childAt(element: ISyntaxElement, index: number): ISyntaxElement {
if (isList(element)) { return (<ISyntaxNodeOrToken[]>element)[index]; }
return (<ISyntaxNodeOrToken>element).childAt(index);
}
export module SyntaxUtilities {
export function isAnyFunctionExpressionOrDeclaration(ast: ISyntaxElement): boolean {
switch (ast.kind) {
case SyntaxKind.SimpleArrowFunctionExpression:
case SyntaxKind.ParenthesizedArrowFunctionExpression:
case SyntaxKind.FunctionExpression:
@@ -19,7 +29,7 @@ module TypeScript {
return false;
}
public static isLastTokenOnLine(token: ISyntaxToken, text: ISimpleText): boolean {
export function isLastTokenOnLine(token: ISyntaxToken, text: ISimpleText): boolean {
var _nextToken = nextToken(token, text);
if (_nextToken === undefined) {
return true;
@@ -32,9 +42,9 @@ module TypeScript {
return tokenLine !== nextTokenLine;
}
public static isLeftHandSizeExpression(element: ISyntaxElement) {
export function isLeftHandSizeExpression(element: ISyntaxElement) {
if (element) {
switch (element.kind()) {
switch (element.kind) {
case SyntaxKind.MemberAccessExpression:
case SyntaxKind.ElementAccessExpression:
case SyntaxKind.TemplateAccessExpression:
@@ -60,9 +70,9 @@ module TypeScript {
return false;
}
public static isSwitchClause(element: ISyntaxElement) {
export function isSwitchClause(element: ISyntaxElement) {
if (element) {
switch (element.kind()) {
switch (element.kind) {
case SyntaxKind.CaseSwitchClause:
case SyntaxKind.DefaultSwitchClause:
return true;
@@ -72,9 +82,9 @@ module TypeScript {
return false;
}
public static isTypeMember(element: ISyntaxElement) {
export function isTypeMember(element: ISyntaxElement) {
if (element) {
switch (element.kind()) {
switch (element.kind) {
case SyntaxKind.ConstructSignature:
case SyntaxKind.MethodSignature:
case SyntaxKind.IndexSignature:
@@ -87,9 +97,9 @@ module TypeScript {
return false;
}
public static isClassElement(element: ISyntaxElement) {
export function isClassElement(element: ISyntaxElement) {
if (element) {
switch (element.kind()) {
switch (element.kind) {
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.IndexMemberDeclaration:
case SyntaxKind.MemberFunctionDeclaration:
@@ -104,9 +114,9 @@ module TypeScript {
return false;
}
public static isModuleElement(element: ISyntaxElement) {
export function isModuleElement(element: ISyntaxElement) {
if (element) {
switch (element.kind()) {
switch (element.kind) {
case SyntaxKind.ImportDeclaration:
case SyntaxKind.ExportAssignment:
case SyntaxKind.ClassDeclaration:
@@ -141,9 +151,9 @@ module TypeScript {
return false;
}
public static isStatement(element: ISyntaxElement) {
export function isStatement(element: ISyntaxElement) {
if (element) {
switch (element.kind()) {
switch (element.kind) {
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.VariableStatement:
case SyntaxKind.Block:
@@ -170,11 +180,11 @@ module TypeScript {
return false;
}
public static isAngleBracket(positionedElement: ISyntaxElement): boolean {
export function isAngleBracket(positionedElement: ISyntaxElement): boolean {
var element = positionedElement;
var parent = positionedElement.parent;
if (parent && (element.kind() === SyntaxKind.LessThanToken || element.kind() === SyntaxKind.GreaterThanToken)) {
switch (parent.kind()) {
if (parent && (element.kind === SyntaxKind.LessThanToken || element.kind === SyntaxKind.GreaterThanToken)) {
switch (parent.kind) {
case SyntaxKind.TypeArgumentList:
case SyntaxKind.TypeParameterList:
case SyntaxKind.CastExpression:
@@ -185,10 +195,10 @@ module TypeScript {
return false;
}
public static getToken(list: ISyntaxToken[], kind: SyntaxKind): ISyntaxToken {
export function getToken(list: ISyntaxToken[], kind: SyntaxKind): ISyntaxToken {
for (var i = 0, n = list.length; i < n; i++) {
var token = list[i];
if (token.kind() === kind) {
if (token.kind === kind) {
return token;
}
}
@@ -196,16 +206,16 @@ module TypeScript {
return undefined;
}
public static containsToken(list: ISyntaxToken[], kind: SyntaxKind): boolean {
export function containsToken(list: ISyntaxToken[], kind: SyntaxKind): boolean {
return !!SyntaxUtilities.getToken(list, kind);
}
public static hasExportKeyword(moduleElement: IModuleElementSyntax): boolean {
export function hasExportKeyword(moduleElement: IModuleElementSyntax): boolean {
return !!SyntaxUtilities.getExportKeyword(moduleElement);
}
public static getExportKeyword(moduleElement: IModuleElementSyntax): ISyntaxToken {
switch (moduleElement.kind()) {
export function getExportKeyword(moduleElement: IModuleElementSyntax): ISyntaxToken {
switch (moduleElement.kind) {
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.FunctionDeclaration:
@@ -219,13 +229,13 @@ module TypeScript {
}
}
public static isAmbientDeclarationSyntax(positionNode: ISyntaxNode): boolean {
export function isAmbientDeclarationSyntax(positionNode: ISyntaxNode): boolean {
if (!positionNode) {
return false;
}
var node = positionNode;
switch (node.kind()) {
switch (node.kind) {
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.FunctionDeclaration:
@@ -3,7 +3,7 @@
module TypeScript {
export function visitNodeOrToken(visitor: ISyntaxVisitor, element: ISyntaxNodeOrToken): any {
if (element === undefined) { return undefined; }
switch (element.kind()) {
switch (element.kind) {
case SyntaxKind.SourceUnit: return visitor.visitSourceUnit(<SourceUnitSyntax>element);
case SyntaxKind.QualifiedName: return visitor.visitQualifiedName(<QualifiedNameSyntax>element);
case SyntaxKind.ObjectType: return visitor.visitObjectType(<ObjectTypeSyntax>element);
@@ -93,6 +93,7 @@ module TypeScript {
case SyntaxKind.Parameter: return visitor.visitParameter(<ParameterSyntax>element);
case SyntaxKind.EnumElement: return visitor.visitEnumElement(<EnumElementSyntax>element);
case SyntaxKind.TypeAnnotation: return visitor.visitTypeAnnotation(<TypeAnnotationSyntax>element);
case SyntaxKind.ComputedPropertyName: return visitor.visitComputedPropertyName(<ComputedPropertyNameSyntax>element);
case SyntaxKind.ExternalModuleReference: return visitor.visitExternalModuleReference(<ExternalModuleReferenceSyntax>element);
case SyntaxKind.ModuleNameModuleReference: return visitor.visitModuleNameModuleReference(<ModuleNameModuleReferenceSyntax>element);
default: return visitor.visitToken(<ISyntaxToken>element);
@@ -190,6 +191,7 @@ module TypeScript {
visitParameter(node: ParameterSyntax): any;
visitEnumElement(node: EnumElementSyntax): any;
visitTypeAnnotation(node: TypeAnnotationSyntax): any;
visitComputedPropertyName(node: ComputedPropertyNameSyntax): any;
visitExternalModuleReference(node: ExternalModuleReferenceSyntax): any;
visitModuleNameModuleReference(node: ModuleNameModuleReferenceSyntax): any;
}
+15 -9
View File
@@ -151,7 +151,7 @@ module TypeScript {
public visitMemberFunctionDeclaration(node: MemberFunctionDeclarationSyntax): void {
this.visitList(node.modifiers);
this.visitToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
visitNodeOrToken(this, node.callSignature);
visitNodeOrToken(this, node.block);
this.visitOptionalToken(node.semicolonToken);
@@ -180,7 +180,7 @@ module TypeScript {
public visitGetAccessor(node: GetAccessorSyntax): void {
this.visitList(node.modifiers);
this.visitToken(node.getKeyword);
this.visitToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
visitNodeOrToken(this, node.callSignature);
visitNodeOrToken(this, node.block);
}
@@ -188,13 +188,13 @@ module TypeScript {
public visitSetAccessor(node: SetAccessorSyntax): void {
this.visitList(node.modifiers);
this.visitToken(node.setKeyword);
this.visitToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
visitNodeOrToken(this, node.callSignature);
visitNodeOrToken(this, node.block);
}
public visitPropertySignature(node: PropertySignatureSyntax): void {
this.visitToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
this.visitOptionalToken(node.questionToken);
visitNodeOrToken(this, node.typeAnnotation);
}
@@ -218,7 +218,7 @@ module TypeScript {
}
public visitMethodSignature(node: MethodSignatureSyntax): void {
this.visitToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
this.visitOptionalToken(node.questionToken);
visitNodeOrToken(this, node.callSignature);
}
@@ -483,7 +483,7 @@ module TypeScript {
}
public visitVariableDeclarator(node: VariableDeclaratorSyntax): void {
this.visitToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
visitNodeOrToken(this, node.typeAnnotation);
visitNodeOrToken(this, node.equalsValueClause);
}
@@ -571,13 +571,13 @@ module TypeScript {
}
public visitSimplePropertyAssignment(node: SimplePropertyAssignmentSyntax): void {
this.visitToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
this.visitToken(node.colonToken);
visitNodeOrToken(this, node.expression);
}
public visitFunctionPropertyAssignment(node: FunctionPropertyAssignmentSyntax): void {
this.visitToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
visitNodeOrToken(this, node.callSignature);
visitNodeOrToken(this, node.block);
}
@@ -592,7 +592,7 @@ module TypeScript {
}
public visitEnumElement(node: EnumElementSyntax): void {
this.visitToken(node.propertyName);
visitNodeOrToken(this, node.propertyName);
visitNodeOrToken(this, node.equalsValueClause);
}
@@ -601,6 +601,12 @@ module TypeScript {
visitNodeOrToken(this, node.type);
}
public visitComputedPropertyName(node: ComputedPropertyNameSyntax): void {
this.visitToken(node.openBracketToken);
visitNodeOrToken(this, node.expression);
this.visitToken(node.closeBracketToken);
}
public visitExternalModuleReference(node: ExternalModuleReferenceSyntax): void {
this.visitToken(node.requireKeyword);
this.visitToken(node.openParenToken);
+9 -9
View File
@@ -9,10 +9,10 @@ module TypeScript {
if (node1 === node2) { return true; }
if (!node1 || !node2) { return false; }
Debug.assert(node1.kind() === TypeScript.SyntaxKind.SourceUnit || node1.parent);
Debug.assert(node2.kind() === TypeScript.SyntaxKind.SourceUnit || node2.parent);
Debug.assert(node1.kind === TypeScript.SyntaxKind.SourceUnit || node1.parent);
Debug.assert(node2.kind === TypeScript.SyntaxKind.SourceUnit || node2.parent);
if (node1.kind() !== node2.kind()) { return false; }
if (node1.kind !== node2.kind) { return false; }
if (childCount(node1) !== childCount(node2)) { return false; }
for (var i = 0, n = childCount(node1); i < n; i++) {
@@ -41,8 +41,8 @@ module TypeScript {
return false;
}
Debug.assert(node1.kind() === TypeScript.SyntaxKind.SourceUnit || node1.parent);
Debug.assert(node2.kind() === TypeScript.SyntaxKind.SourceUnit || node2.parent);
Debug.assert(node1.kind === TypeScript.SyntaxKind.SourceUnit || node1.parent);
Debug.assert(node2.kind === TypeScript.SyntaxKind.SourceUnit || node2.parent);
if (TypeScript.isToken(node1)) {
return TypeScript.isToken(node2) ? tokenStructuralEquals(<TypeScript.ISyntaxToken>node1, <TypeScript.ISyntaxToken>node2, text1, text2) : false;
@@ -63,7 +63,7 @@ module TypeScript {
Debug.assert(token1.parent);
Debug.assert(token2.parent);
return token1.kind() === token2.kind() &&
return token1.kind === token2.kind &&
TypeScript.width(token1) === TypeScript.width(token2) &&
token1.fullWidth() === token2.fullWidth() &&
token1.fullStart() === token2.fullStart() &&
@@ -135,10 +135,10 @@ module TypeScript {
return false;
}
Debug.assert(element1.kind() === SyntaxKind.SourceUnit || element1.parent);
Debug.assert(element2.kind() === SyntaxKind.SourceUnit || element2.parent);
Debug.assert(element1.kind === SyntaxKind.SourceUnit || element1.parent);
Debug.assert(element2.kind === SyntaxKind.SourceUnit || element2.parent);
if (element2.kind() !== element2.kind()) {
if (element2.kind !== element2.kind) {
return false;
}
@@ -0,0 +1,4 @@
var fixedWidthArray = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 4, 5, 8, 8, 7, 6, 2, 4, 5, 7, 3, 8, 2, 2, 10, 3, 4, 6, 6, 4, 5, 4, 3, 6, 3, 4, 5, 4, 5, 5, 4, 6, 7, 6, 5, 10, 9, 3, 7, 7, 9, 6, 6, 5, 3, 7, 11, 7, 3, 6, 7, 6, 3, 6, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 1, 1, 1, 1, 2, 2, 2, 2, 3, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 2, 2, 2, 1, 2];
function fixedWidthTokenLength(kind: SyntaxKind) {
return fixedWidthArray[kind];
}
+1 -1
View File
@@ -238,7 +238,7 @@ module ts {
}
if (isAnyFunction(node) || node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.InterfaceDeclaration) {
return (<FunctionDeclaration>node).typeParameters;
return (<FunctionLikeDeclaration>node).typeParameters;
}
return undefined;