diff --git a/bin/tsc.js b/bin/tsc.js index 070f5356189..ab5386e2b40 100644 --- a/bin/tsc.js +++ b/bin/tsc.js @@ -182,6 +182,19 @@ var ts; return result; } ts.clone = clone; + function extend(first, second) { + var result = {}; + for (var id in first) { + result[id] = first[id]; + } + for (var id in second) { + if (!hasProperty(result, id)) { + result[id] = second[id]; + } + } + return result; + } + ts.extend = extend; function forEachValue(map, callback) { var result; for (var id in map) { @@ -503,7 +516,7 @@ var ts; return path2; if (!(path2 && path2.length)) return path1; - if (path2.charAt(0) === ts.directorySeparator) + if (getRootLength(path2) !== 0) return path2; if (path1.charAt(path1.length - 1) === ts.directorySeparator) return path1 + path2; @@ -666,6 +679,32 @@ var ts; fileStream.Close(); } } + function getNames(collection) { + var result = []; + for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { + result.push(e.item().Name); + } + return result.sort(); + } + function readDirectory(path, extension) { + var result = []; + visitDirectory(path); + return result; + function visitDirectory(path) { + var folder = fso.GetFolder(path || "."); + var files = getNames(folder.files); + for (var i = 0; i < files.length; i++) { + var name = files[i]; + if (!extension || ts.fileExtensionIs(name, extension)) { + result.push(ts.combinePaths(path, name)); + } + } + var subfolders = getNames(folder.subfolders); + for (var i = 0; i < subfolders.length; i++) { + visitDirectory(ts.combinePaths(path, subfolders[i])); + } + } + } return { args: args, newLine: "\r\n", @@ -695,6 +734,7 @@ var ts; getCurrentDirectory: function () { return new ActiveXObject("WScript.Shell").CurrentDirectory; }, + readDirectory: readDirectory, exit: function (exitCode) { try { WScript.Quit(exitCode); @@ -739,6 +779,30 @@ var ts; } _fs.writeFileSync(fileName, data, "utf8"); } + function readDirectory(path, extension) { + var result = []; + visitDirectory(path); + return result; + function visitDirectory(path) { + var files = _fs.readdirSync(path || ".").sort(); + var directories = []; + for (var i = 0; i < files.length; i++) { + var name = ts.combinePaths(path, files[i]); + var stat = _fs.lstatSync(name); + if (stat.isFile()) { + if (!extension || ts.fileExtensionIs(name, extension)) { + result.push(name); + } + } + else if (stat.isDirectory()) { + directories.push(name); + } + } + for (var i = 0; i < directories.length; i++) { + visitDirectory(directories[i]); + } + } + } return { args: process.argv.slice(2), newLine: _os.EOL, @@ -783,6 +847,7 @@ var ts; getCurrentDirectory: function () { return process.cwd(); }, + readDirectory: readDirectory, getMemoryUsage: function () { if (global.gc) { global.gc(); @@ -952,6 +1017,7 @@ var ts; Modifiers_cannot_appear_here: { code: 1184, category: 1 /* Error */, key: "Modifiers cannot appear here." }, Merge_conflict_marker_encountered: { code: 1185, category: 1 /* Error */, key: "Merge conflict marker encountered." }, A_rest_element_cannot_have_an_initializer: { code: 1186, category: 1 /* Error */, key: "A rest element cannot have an initializer." }, + A_parameter_property_may_not_be_a_binding_pattern: { code: 1187, category: 1 /* Error */, key: "A parameter property may not be a binding pattern." }, Duplicate_identifier_0: { code: 2300, category: 1 /* Error */, key: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: 1 /* Error */, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: 1 /* Error */, key: "Static members cannot reference class type parameters." }, @@ -1103,6 +1169,11 @@ var ts; Type_0_has_no_property_1: { code: 2460, category: 1 /* Error */, key: "Type '{0}' has no property '{1}'." }, Type_0_is_not_an_array_type: { code: 2461, category: 1 /* Error */, key: "Type '{0}' is not an array type." }, A_rest_element_must_be_last_in_an_array_destructuring_pattern: { code: 2462, category: 1 /* Error */, key: "A rest element must be last in an array destructuring pattern" }, + A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: { code: 2463, category: 1 /* Error */, key: "A binding pattern parameter cannot be optional in an implementation signature." }, + A_computed_property_name_must_be_of_type_string_number_or_any: { code: 2464, category: 1 /* Error */, key: "A computed property name must be of type 'string', 'number', or 'any'." }, + this_cannot_be_referenced_in_a_computed_property_name: { code: 2465, category: 1 /* Error */, key: "'this' cannot be referenced in a computed property name." }, + super_cannot_be_referenced_in_a_computed_property_name: { code: 2466, category: 1 /* Error */, key: "'super' cannot be referenced in a computed property name." }, + A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: { code: 2466, category: 1 /* Error */, key: "A computed property name cannot reference a type parameter from its containing type." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: 1 /* Error */, key: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: 1 /* Error */, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: 1 /* Error */, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -1175,19 +1246,22 @@ var ts; Enum_declarations_must_all_be_const_or_non_const: { code: 4082, category: 1 /* Error */, key: "Enum declarations must all be const or non-const." }, In_const_enum_declarations_member_initializer_must_be_constant_expression: { code: 4083, category: 1 /* 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: 1 /* 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: 1 /* Error */, key: "Index expression arguments in 'const' enums must be of type 'string'." }, + A_const_enum_member_can_only_be_accessed_using_a_string_literal: { code: 4085, category: 1 /* Error */, key: "A const enum member can only be accessed using a string literal.", isEarly: true }, const_enum_member_initializer_was_evaluated_to_a_non_finite_value: { code: 4086, category: 1 /* 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: 1 /* Error */, key: "'const' enum member initializer was evaluated to disallowed value 'NaN'." }, + Property_0_does_not_exist_on_const_enum_1: { code: 4088, category: 1 /* Error */, key: "Property '{0}' does not exist on 'const' enum '{1}'.", isEarly: true }, The_current_host_does_not_support_the_0_option: { code: 5001, category: 1 /* Error */, key: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: 1 /* Error */, key: "Cannot find the common subdirectory path for the input files." }, Cannot_read_file_0_Colon_1: { code: 5012, category: 1 /* Error */, key: "Cannot read file '{0}': {1}" }, Unsupported_file_encoding: { code: 5013, category: 1 /* Error */, key: "Unsupported file encoding." }, Unknown_compiler_option_0: { code: 5023, category: 1 /* Error */, key: "Unknown compiler option '{0}'." }, + Compiler_option_0_requires_a_value_of_type_1: { code: 5024, category: 1 /* Error */, key: "Compiler option '{0}' requires a value of type {1}." }, Could_not_write_file_0_Colon_1: { code: 5033, category: 1 /* Error */, key: "Could not write file '{0}': {1}" }, - Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5038, category: 1 /* Error */, key: "Option mapRoot cannot be specified without specifying sourcemap option." }, - Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5039, category: 1 /* Error */, key: "Option sourceRoot cannot be specified without specifying sourcemap option." }, - Option_noEmit_cannot_be_specified_with_option_out_or_outDir: { code: 5040, category: 1 /* Error */, key: "Option noEmit cannot be specified with option out or outDir." }, - Option_noEmit_cannot_be_specified_with_option_declaration: { code: 5041, category: 1 /* Error */, key: "Option noEmit cannot be specified with option declaration." }, + Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5038, category: 1 /* Error */, key: "Option 'mapRoot' cannot be specified without specifying 'sourcemap' option." }, + Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5039, category: 1 /* Error */, key: "Option 'sourceRoot' cannot be specified without specifying 'sourcemap' option." }, + Option_noEmit_cannot_be_specified_with_option_out_or_outDir: { code: 5040, category: 1 /* Error */, key: "Option 'noEmit' cannot be specified with option 'out' or 'outDir'." }, + Option_noEmit_cannot_be_specified_with_option_declaration: { code: 5041, category: 1 /* Error */, key: "Option 'noEmit' cannot be specified with option 'declaration'." }, + Option_project_cannot_be_mixed_with_source_files_on_a_command_line: { code: 5042, category: 1 /* Error */, key: "Option 'project' cannot be mixed with source files on a command line." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: 2 /* Message */, key: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: 2 /* Message */, key: "Generates corresponding '.d.ts' file." }, Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: 2 /* Message */, key: "Specifies the location where debugger should locate map files instead of generated locations." }, @@ -1202,6 +1276,7 @@ var ts; Specify_module_code_generation_Colon_commonjs_or_amd: { code: 6016, category: 2 /* Message */, key: "Specify module code generation: 'commonjs' or 'amd'" }, Print_this_message: { code: 6017, category: 2 /* Message */, key: "Print this message." }, Print_the_compiler_s_version: { code: 6019, category: 2 /* Message */, key: "Print the compiler's version." }, + Compile_the_project_in_the_given_directory: { code: 6020, category: 2 /* Message */, key: "Compile the project in the given directory." }, Syntax_Colon_0: { code: 6023, category: 2 /* Message */, key: "Syntax: {0}" }, options: { code: 6024, category: 2 /* Message */, key: "options" }, file: { code: 6025, category: 2 /* Message */, key: "file" }, @@ -1209,7 +1284,7 @@ var ts; Options_Colon: { code: 6027, category: 2 /* Message */, key: "Options:" }, Version_0: { code: 6029, category: 2 /* Message */, key: "Version {0}" }, Insert_command_line_options_and_files_from_a_file: { code: 6030, category: 2 /* Message */, key: "Insert command line options and files from a file." }, - File_change_detected_Compiling: { code: 6032, category: 2 /* Message */, key: "File change detected. Compiling..." }, + File_change_detected_Starting_incremental_compilation: { code: 6032, category: 2 /* Message */, key: "File change detected. Starting incremental compilation..." }, KIND: { code: 6034, category: 2 /* Message */, key: "KIND" }, FILE: { code: 6035, category: 2 /* Message */, key: "FILE" }, VERSION: { code: 6036, category: 2 /* Message */, key: "VERSION" }, @@ -1225,7 +1300,7 @@ var ts; Unsupported_locale_0: { code: 6049, category: 1 /* Error */, key: "Unsupported locale '{0}'." }, Unable_to_open_file_0: { code: 6050, category: 1 /* Error */, key: "Unable to open file '{0}'." }, Corrupted_locale_file_0: { code: 6051, category: 1 /* Error */, key: "Corrupted locale file {0}." }, - Raise_error_on_expressions_and_declarations_with_an_implied_any_type: { code: 6052, category: 2 /* Message */, key: "Warn on expressions and declarations with an implied 'any' type." }, + Raise_error_on_expressions_and_declarations_with_an_implied_any_type: { code: 6052, category: 2 /* Message */, key: "Raise error on expressions and declarations with an implied 'any' type." }, File_0_not_found: { code: 6053, category: 1 /* Error */, key: "File '{0}' not found." }, File_0_must_have_extension_ts_or_d_ts: { code: 6054, category: 1 /* Error */, key: "File '{0}' must have extension '.ts' or '.d.ts'." }, Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: { code: 6055, category: 2 /* Message */, key: "Suppress noImplicitAny errors for indexing objects lacking index signatures." }, @@ -1247,8 +1322,7 @@ var ts; 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: { code: 7024, category: 1 /* Error */, key: "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." }, You_cannot_rename_this_element: { code: 8000, category: 1 /* Error */, key: "You cannot rename this element." }, yield_expressions_are_not_currently_supported: { code: 9000, category: 1 /* Error */, key: "'yield' expressions are not currently supported.", isEarly: true }, - Generators_are_not_currently_supported: { code: 9001, category: 1 /* Error */, key: "Generators are not currently supported.", isEarly: true }, - Computed_property_names_are_not_currently_supported: { code: 9002, category: 1 /* Error */, key: "Computed property names are not currently supported.", isEarly: true } + Generators_are_not_currently_supported: { code: 9001, category: 1 /* Error */, key: "Generators are not currently supported.", isEarly: true } }; })(ts || (ts = {})); var ts; @@ -1388,10 +1462,10 @@ var ts; return false; } function isUnicodeIdentifierStart(code, languageVersion) { - return languageVersion === 0 /* ES3 */ ? lookupInUnicodeMap(code, unicodeES3IdentifierStart) : lookupInUnicodeMap(code, unicodeES5IdentifierStart); + return languageVersion >= 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) : lookupInUnicodeMap(code, unicodeES3IdentifierStart); } function isUnicodeIdentifierPart(code, languageVersion) { - return languageVersion === 0 /* ES3 */ ? lookupInUnicodeMap(code, unicodeES3IdentifierPart) : lookupInUnicodeMap(code, unicodeES5IdentifierPart); + return languageVersion >= 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) : lookupInUnicodeMap(code, unicodeES3IdentifierPart); } function makeReverseMap(source) { var result = []; @@ -1435,7 +1509,7 @@ var ts; } ts.computeLineStarts = computeLineStarts; function getPositionFromLineAndCharacter(lineStarts, line, character) { - ts.Debug.assert(line > 0); + ts.Debug.assert(line > 0 && line <= lineStarts.length); return lineStarts[line - 1] + character - 1; } ts.getPositionFromLineAndCharacter = getPositionFromLineAndCharacter; @@ -2099,7 +2173,7 @@ var ts; value = 0; } tokenValue = "" + value; - return 7 /* NumericLiteral */; + return token = 7 /* NumericLiteral */; } else if (pos + 2 < len && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { pos += 2; @@ -2109,7 +2183,7 @@ var ts; value = 0; } tokenValue = "" + value; - return 7 /* NumericLiteral */; + return token = 7 /* NumericLiteral */; } if (pos + 1 < len && isOctalDigit(text.charCodeAt(pos + 1))) { tokenValue = "" + scanOctalDigits(); @@ -2667,6 +2741,12 @@ var ts; return undefined; } switch (node.kind) { + case 122 /* ComputedPropertyName */: + if (node.parent.parent.kind === 191 /* ClassDeclaration */) { + return node; + } + node = node.parent; + break; case 157 /* ArrowFunction */: if (!includeArrowFunctions) { continue; @@ -2688,13 +2768,24 @@ var ts; } } ts.getThisContainer = getThisContainer; - function getSuperContainer(node) { + function getSuperContainer(node, includeFunctions) { while (true) { node = node.parent; - if (!node) { - return undefined; - } + if (!node) + return node; switch (node.kind) { + case 122 /* ComputedPropertyName */: + if (node.parent.parent.kind === 191 /* ClassDeclaration */) { + return node; + } + node = node.parent; + break; + case 190 /* FunctionDeclaration */: + case 156 /* FunctionExpression */: + case 157 /* ArrowFunction */: + if (!includeFunctions) { + continue; + } case 126 /* PropertyDeclaration */: case 125 /* PropertySignature */: case 128 /* MethodDeclaration */: @@ -2787,6 +2878,8 @@ var ts; return node === parent.expression; case 169 /* TemplateSpan */: return node === parent.expression; + case 122 /* ComputedPropertyName */: + return node === parent.expression; default: if (isExpression(parent)) { return true; @@ -3971,7 +4064,7 @@ var ts; return canFollowModifier(); } function canFollowModifier() { - return token === 18 /* OpenBracketToken */ || token === 35 /* AsteriskToken */ || isLiteralPropertyName(); + return token === 18 /* OpenBracketToken */ || token === 14 /* OpenBraceToken */ || token === 35 /* AsteriskToken */ || isLiteralPropertyName(); } function isListElement(parsingContext, inErrorRecovery) { var node = currentNode(parsingContext); @@ -6294,7 +6387,7 @@ var ts; var ts; (function (ts) { function getModuleInstanceState(node) { - if (node.kind === 192 /* InterfaceDeclaration */) { + if (node.kind === 192 /* InterfaceDeclaration */ || node.kind === 193 /* TypeAliasDeclaration */) { return 0 /* NonInstantiated */; } else if (ts.isConstEnumDeclaration(node)) { @@ -6327,10 +6420,10 @@ var ts; } } ts.getModuleInstanceState = getModuleInstanceState; - function hasComputedNameButNotSymbol(declaration) { + function hasDynamicName(declaration) { return declaration.name && declaration.name.kind === 122 /* ComputedPropertyName */; } - ts.hasComputedNameButNotSymbol = hasComputedNameButNotSymbol; + ts.hasDynamicName = hasDynamicName; function bindSourceFile(file) { var parent; var container; @@ -6366,7 +6459,7 @@ var ts; if (node.kind === 195 /* ModuleDeclaration */ && node.name.kind === 8 /* StringLiteral */) { return '"' + node.name.text + '"'; } - ts.Debug.assert(!hasComputedNameButNotSymbol(node)); + ts.Debug.assert(!hasDynamicName(node)); return node.name.text; } switch (node.kind) { @@ -6386,9 +6479,7 @@ var ts; return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); } function declareSymbol(symbols, parent, node, includes, excludes) { - if (hasComputedNameButNotSymbol(node)) { - return undefined; - } + ts.Debug.assert(!hasDynamicName(node)); var name = getDeclarationName(node); if (name !== undefined) { var symbol = ts.hasProperty(symbols, name) ? symbols[name] : (symbols[name] = createSymbol(0, name)); @@ -6607,14 +6698,14 @@ var ts; break; case 126 /* PropertyDeclaration */: case 125 /* PropertySignature */: - bindDeclaration(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0), 107455 /* PropertyExcludes */, false); + bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0), 107455 /* PropertyExcludes */, false); break; case 204 /* PropertyAssignment */: case 205 /* ShorthandPropertyAssignment */: - bindDeclaration(node, 4 /* Property */, 107455 /* PropertyExcludes */, false); + bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */, false); break; case 206 /* EnumMember */: - bindDeclaration(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */, false); + bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */, false); break; case 132 /* CallSignature */: case 133 /* ConstructSignature */: @@ -6623,7 +6714,7 @@ var ts; break; case 128 /* MethodDeclaration */: case 127 /* MethodSignature */: - bindDeclaration(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */, true); + bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */, true); break; case 190 /* FunctionDeclaration */: bindDeclaration(node, 16 /* Function */, 106927 /* FunctionExcludes */, true); @@ -6632,10 +6723,10 @@ var ts; bindDeclaration(node, 16384 /* Constructor */, 0, true); break; case 130 /* GetAccessor */: - bindDeclaration(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */, true); + bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */, true); break; case 131 /* SetAccessor */: - bindDeclaration(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */, true); + bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */, true); break; case 136 /* FunctionType */: case 137 /* ConstructorType */: @@ -6708,6 +6799,14 @@ var ts; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); } } + function bindPropertyOrMethodOrAccessor(node, symbolKind, symbolExcludes, isBlockScopeContainer) { + if (hasDynamicName(node)) { + bindAnonymousDeclaration(node, symbolKind, "__computed", isBlockScopeContainer); + } + else { + bindDeclaration(node, symbolKind, symbolExcludes, isBlockScopeContainer); + } + } } ts.bindSourceFile = bindSourceFile; })(ts || (ts = {})); @@ -6724,6 +6823,7 @@ var ts; var emptyArray = []; var emptySymbols = {}; var compilerOptions = host.getCompilerOptions(); + var languageVersion = compilerOptions.target || 0 /* ES3 */; var emitResolver = createResolver(); var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, @@ -6769,8 +6869,8 @@ var ts; var numberType = createIntrinsicType(4 /* Number */, "number"); var booleanType = createIntrinsicType(8 /* Boolean */, "boolean"); var voidType = createIntrinsicType(16 /* Void */, "void"); - var undefinedType = createIntrinsicType(32 /* Undefined */ | 131072 /* Unwidened */, "undefined"); - var nullType = createIntrinsicType(64 /* Null */ | 131072 /* Unwidened */, "null"); + var undefinedType = createIntrinsicType(32 /* Undefined */ | 262144 /* ContainsUndefinedOrNull */, "undefined"); + var nullType = createIntrinsicType(64 /* Null */ | 262144 /* ContainsUndefinedOrNull */, "null"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); var resolvingType = createIntrinsicType(1 /* Any */, "__resolving__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -6800,6 +6900,20 @@ var ts; var potentialThisCollisions = []; var diagnostics = []; var diagnosticsModified = false; + var primitiveTypeInfo = { + "string": { + type: stringType, + flags: 258 /* StringLike */ + }, + "number": { + type: numberType, + flags: 132 /* NumberLike */ + }, + "boolean": { + type: booleanType, + flags: 8 /* Boolean */ + } + }; function addDiagnostic(diagnostic) { diagnostics.push(diagnostic); diagnosticsModified = true; @@ -7016,6 +7130,15 @@ var ts; break loop; } break; + case 122 /* ComputedPropertyName */: + var grandparent = location.parent.parent; + if (grandparent.kind === 191 /* ClassDeclaration */ || grandparent.kind === 192 /* InterfaceDeclaration */) { + if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056 /* Type */)) { + error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); + return undefined; + } + } + break; case 128 /* MethodDeclaration */: case 127 /* MethodSignature */: case 129 /* Constructor */: @@ -8050,7 +8173,7 @@ var ts; } if (pattern.kind === 144 /* ObjectBindingPattern */) { var name = declaration.propertyName || declaration.name; - var type = getTypeOfPropertyOfType(parentType, name.text) || isNumericName(name.text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); + var type = getTypeOfPropertyOfType(parentType, name.text) || isNumericLiteralName(name.text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); if (!type) { error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); return unknownType; @@ -8087,7 +8210,7 @@ var ts; } if (declaration.kind === 124 /* Parameter */) { var func = declaration.parent; - if (func.kind === 131 /* SetAccessor */ && !ts.hasComputedNameButNotSymbol(func)) { + if (func.kind === 131 /* SetAccessor */ && !ts.hasDynamicName(func)) { var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 130 /* GetAccessor */); if (getter) { return getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); @@ -8868,7 +8991,7 @@ var ts; returnType = getTypeFromTypeNode(declaration.type); } else { - if (declaration.kind === 130 /* GetAccessor */ && !ts.hasComputedNameButNotSymbol(declaration)) { + if (declaration.kind === 130 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { var setter = ts.getDeclarationOfKind(declaration.symbol, 131 /* SetAccessor */); returnType = getAnnotatedAccessorType(setter); } @@ -9030,14 +9153,18 @@ var ts; return result; } } - function getUnwidenedFlagOfTypes(types) { - return ts.forEach(types, function (t) { return t.flags & 131072 /* Unwidened */; }) || 0; + function getWideningFlagsOfTypes(types) { + var result = 0; + for (var i = 0; i < types.length; i++) { + result |= types[i].flags; + } + return result & 786432 /* RequiresWidening */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations[id]; if (!type) { - var flags = 4096 /* Reference */ | getUnwidenedFlagOfTypes(typeArguments); + var flags = 4096 /* Reference */ | getWideningFlagsOfTypes(typeArguments); type = target.instantiations[id] = createObjectType(flags, target.symbol); type.target = target; type.typeArguments = typeArguments; @@ -9254,7 +9381,7 @@ var ts; var id = getTypeListId(sortedTypes); var type = unionTypes[id]; if (!type) { - type = unionTypes[id] = createObjectType(16384 /* Union */ | getUnwidenedFlagOfTypes(sortedTypes)); + type = unionTypes[id] = createObjectType(16384 /* Union */ | getWideningFlagsOfTypes(sortedTypes)); type.types = sortedTypes; } return type; @@ -9481,6 +9608,8 @@ var ts; case 128 /* MethodDeclaration */: case 127 /* MethodSignature */: return isContextSensitiveFunctionLikeDeclaration(node); + case 155 /* ParenthesizedExpression */: + return isContextSensitive(node.expression); } return false; } @@ -9541,6 +9670,10 @@ var ts; error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); } else if (errorInfo) { + if (errorInfo.next === undefined) { + errorInfo = undefined; + isRelatedTo(source, target, errorNode !== undefined, headMessage, true); + } if (containingMessageChain) { errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); } @@ -9550,7 +9683,8 @@ var ts; function reportError(message, arg0, arg1, arg2) { errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); } - function isRelatedTo(source, target, reportErrors, headMessage) { + function isRelatedTo(source, target, reportErrors, headMessage, elaborateErrors) { + if (elaborateErrors === void 0) { elaborateErrors = false; } var result; if (source === target) return -1 /* True */; @@ -9619,7 +9753,7 @@ var ts; } var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo; var sourceOrApparentType = relation === identityRelation ? source : getApparentType(source); - if (sourceOrApparentType.flags & 48128 /* ObjectType */ && target.flags & 48128 /* ObjectType */ && (result = objectTypeRelatedTo(sourceOrApparentType, target, reportStructuralErrors))) { + if (sourceOrApparentType.flags & 48128 /* ObjectType */ && target.flags & 48128 /* ObjectType */ && (result = objectTypeRelatedTo(sourceOrApparentType, target, reportStructuralErrors, elaborateErrors))) { errorInfo = saveErrorInfo; return result; } @@ -9700,14 +9834,17 @@ var ts; return 0 /* False */; } } - function objectTypeRelatedTo(source, target, reportErrors) { + function objectTypeRelatedTo(source, target, reportErrors, elaborateErrors) { + if (elaborateErrors === void 0) { elaborateErrors = false; } if (overflow) { return 0 /* False */; } var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; var related = relation[id]; if (related !== undefined) { - return related ? -1 /* True */ : 0 /* False */; + if (!elaborateErrors || (related === 3 /* FailedAndReported */)) { + return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; + } } if (depth > 0) { for (var i = 0; i < depth; i++) { @@ -9729,7 +9866,7 @@ var ts; sourceStack[depth] = source; targetStack[depth] = target; maybeStack[depth] = {}; - maybeStack[depth][id] = true; + maybeStack[depth][id] = 1 /* Succeeded */; depth++; var saveExpandingFlags = expandingFlags; if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack)) @@ -9758,11 +9895,11 @@ var ts; depth--; if (result) { var maybeCache = maybeStack[depth]; - var destinationCache = result === -1 /* True */ || depth === 0 ? relation : maybeStack[depth - 1]; + var destinationCache = (result === -1 /* True */ || depth === 0) ? relation : maybeStack[depth - 1]; ts.copyMap(maybeCache, destinationCache); } else { - relation[id] = false; + relation[id] = reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */; } return result; } @@ -9787,12 +9924,13 @@ var ts; } var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 131072 /* ObjectLiteral */); for (var i = 0; i < properties.length; i++) { var targetProp = properties[i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { - if (relation === subtypeRelation || !(targetProp.flags & 536870912 /* Optional */)) { + if (!(targetProp.flags & 536870912 /* Optional */) || requireOptionalProperties) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); } @@ -10137,9 +10275,6 @@ var ts; } checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); } - function isTypeOfObjectLiteral(type) { - return (type.flags & 32768 /* Anonymous */) && type.symbol && (type.symbol.flags & 4096 /* ObjectLiteral */) ? true : false; - } function isArrayType(type) { return type.flags & 4096 /* Reference */ && type.target === globalArrayType; } @@ -10150,14 +10285,19 @@ var ts; var properties = getPropertiesOfObjectType(type); var members = {}; ts.forEach(properties, function (p) { - var symbol = createSymbol(p.flags | 67108864 /* Transient */, p.name); - symbol.declarations = p.declarations; - symbol.parent = p.parent; - symbol.type = getWidenedType(getTypeOfSymbol(p)); - symbol.target = p; - if (p.valueDeclaration) - symbol.valueDeclaration = p.valueDeclaration; - members[symbol.name] = symbol; + var propType = getTypeOfSymbol(p); + var widenedType = getWidenedType(propType); + if (propType !== widenedType) { + var symbol = createSymbol(p.flags | 67108864 /* Transient */, p.name); + symbol.declarations = p.declarations; + symbol.parent = p.parent; + symbol.type = widenedType; + symbol.target = p; + if (p.valueDeclaration) + symbol.valueDeclaration = p.valueDeclaration; + p = symbol; + } + members[p.name] = p; }); var stringIndexType = getIndexTypeOfType(type, 0 /* String */); var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); @@ -10168,16 +10308,16 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); } function getWidenedType(type) { - if (type.flags & 131072 /* Unwidened */) { + if (type.flags & 786432 /* RequiresWidening */) { if (type.flags & (32 /* Undefined */ | 64 /* Null */)) { return anyType; } + if (type.flags & 131072 /* ObjectLiteral */) { + return getWidenedTypeOfObjectLiteral(type); + } if (type.flags & 16384 /* Union */) { return getUnionType(ts.map(type.types, getWidenedType)); } - if (isTypeOfObjectLiteral(type)) { - return getWidenedTypeOfObjectLiteral(type); - } if (isArrayType(type)) { return createArrayType(getWidenedType(type.typeArguments[0])); } @@ -10197,11 +10337,11 @@ var ts; if (isArrayType(type)) { return reportWideningErrorsInType(type.typeArguments[0]); } - if (isTypeOfObjectLiteral(type)) { + if (type.flags & 131072 /* ObjectLiteral */) { var errorReported = false; ts.forEach(getPropertiesOfObjectType(type), function (p) { var t = getTypeOfSymbol(p); - if (t.flags & 131072 /* Unwidened */) { + if (t.flags & 262144 /* ContainsUndefinedOrNull */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -10241,7 +10381,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 131072 /* Unwidened */) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 262144 /* ContainsUndefinedOrNull */) { if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -10465,11 +10605,14 @@ var ts; } ts.Debug.fail("should not get here"); } - function subtractPrimitiveTypes(type, subtractMask) { + function removeTypesFromUnionType(type, typeKind, isOfTypeKind) { if (type.flags & 16384 /* Union */) { var types = type.types; - if (ts.forEach(types, function (t) { return t.flags & subtractMask; })) { - return getUnionType(ts.filter(types, function (t) { return !(t.flags & subtractMask); })); + if (ts.forEach(types, function (t) { return !!(t.flags & typeKind) === isOfTypeKind; })) { + var narrowedType = getUnionType(ts.filter(types, function (t) { return !(t.flags & typeKind) === isOfTypeKind; })); + if (narrowedType !== emptyObjectType) { + return narrowedType; + } } } return type; @@ -10614,7 +10757,7 @@ var ts; case 129 /* Constructor */: break loop; } - if (narrowedType !== type && isTypeSubtypeOf(narrowedType, type)) { + if (narrowedType !== type) { if (isVariableAssignedWithin(symbol, node)) { break; } @@ -10632,16 +10775,24 @@ var ts; if (left.expression.kind !== 64 /* Identifier */ || getResolvedSymbol(left.expression) !== symbol) { return type; } - var t = right.text; - var checkType = t === "string" ? stringType : t === "number" ? numberType : t === "boolean" ? booleanType : emptyObjectType; + var typeInfo = primitiveTypeInfo[right.text]; if (expr.operator === 31 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } if (assumeTrue) { - return checkType === emptyObjectType ? subtractPrimitiveTypes(type, 2 /* String */ | 4 /* Number */ | 8 /* Boolean */) : checkType; + if (!typeInfo) { + return removeTypesFromUnionType(type, 258 /* StringLike */ | 132 /* NumberLike */ | 8 /* Boolean */, true); + } + if (isTypeSubtypeOf(typeInfo.type, type)) { + return typeInfo.type; + } + return removeTypesFromUnionType(type, typeInfo.flags, false); } else { - return checkType === emptyObjectType ? type : subtractPrimitiveTypes(type, checkType.flags); + if (typeInfo) { + return removeTypesFromUnionType(type, typeInfo.flags, true); + } + return type; } } function narrowTypeByAnd(type, expr, assumeTrue) { @@ -10678,8 +10829,14 @@ var ts; if (!prototypeProperty) { return type; } - var prototypeType = getTypeOfSymbol(prototypeProperty); - return isTypeSubtypeOf(prototypeType, type) ? prototypeType : type; + var targetType = getTypeOfSymbol(prototypeProperty); + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + if (type.flags & 16384 /* Union */) { + return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, targetType); })); + } + return type; } function narrowType(type, expr, assumeTrue) { switch (expr.kind) { @@ -10777,6 +10934,9 @@ var ts; error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; + case 122 /* ComputedPropertyName */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); + break; } if (needToCaptureLexicalThis) { captureLexicalThis(node, container); @@ -10788,26 +10948,6 @@ var ts; } return anyType; } - function getSuperContainer(node) { - while (true) { - node = node.parent; - if (!node) - return node; - switch (node.kind) { - case 190 /* FunctionDeclaration */: - case 156 /* FunctionExpression */: - case 157 /* ArrowFunction */: - case 126 /* PropertyDeclaration */: - case 125 /* PropertySignature */: - case 128 /* MethodDeclaration */: - case 127 /* MethodSignature */: - case 129 /* Constructor */: - case 130 /* GetAccessor */: - case 131 /* SetAccessor */: - return node; - } - } - } function isInConstructorArgumentInitializer(node, constructorDecl) { for (var n = node; n && n !== constructorDecl; n = n.parent) { if (n.kind === 124 /* Parameter */) { @@ -10828,7 +10968,7 @@ var ts; error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); return unknownType; } - var container = getSuperContainer(node); + var container = ts.getSuperContainer(node, true); if (container) { var canUseSuperExpression = false; if (isCallExpression) { @@ -10837,7 +10977,7 @@ var ts; else { var needToCaptureLexicalThis = false; while (container && container.kind === 157 /* ArrowFunction */) { - container = getSuperContainer(container); + container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = true; } if (container && container.parent && container.parent.kind === 191 /* ClassDeclaration */) { @@ -10869,7 +11009,10 @@ var ts; return returnType; } } - if (isCallExpression) { + if (container.kind === 122 /* ComputedPropertyName */) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); + } + else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } else { @@ -11008,9 +11151,15 @@ var ts; function getContextualTypeForObjectLiteralElement(element) { var objectLiteral = element.parent; var type = getContextualType(objectLiteral); - var name = element.name.text; - if (type && name) { - return getTypeOfPropertyOfContextualType(type, name) || isNumericName(name) && getIndexTypeOfContextualType(type, 1 /* Number */) || getIndexTypeOfContextualType(type, 0 /* String */); + if (type) { + if (!ts.hasDynamicName(element)) { + var symbolName = getSymbolOfNode(element).name; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); + if (propertyType) { + return propertyType; + } + } + return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) || getIndexTypeOfContextualType(type, 0 /* String */); } return undefined; } @@ -11061,6 +11210,8 @@ var ts; case 169 /* TemplateSpan */: ts.Debug.assert(parent.parent.kind === 165 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); + case 155 /* ParenthesizedExpression */: + return getContextualType(parent); } return undefined; } @@ -11165,72 +11316,84 @@ var ts; return createArrayType(getUnionType(elementTypes)); } function isNumericName(name) { + return name.kind === 122 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); + } + function isNumericComputedName(name) { + return isTypeOfKind(checkComputedPropertyName(name), 1 /* Any */ | 132 /* NumberLike */); + } + function isNumericLiteralName(name) { return (+name).toString() === name; } + function checkComputedPropertyName(node) { + var links = getNodeLinks(node.expression); + if (!links.resolvedType) { + links.resolvedType = checkExpression(node.expression); + if (!isTypeOfKind(links.resolvedType, 1 /* Any */ | 132 /* NumberLike */ | 258 /* StringLike */)) { + error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_or_any); + } + } + return links.resolvedType; + } function checkObjectLiteral(node, contextualMapper) { checkGrammarObjectLiteralExpression(node); - var members = node.symbol.members; - var properties = {}; + var propertiesTable = {}; + var propertiesArray = []; var contextualType = getContextualType(node); var typeFlags; - for (var id in members) { - if (ts.hasProperty(members, id)) { - var member = members[id]; - if (member.flags & 4 /* Property */ || ts.isObjectLiteralMethod(member.declarations[0])) { - var memberDecl = member.declarations[0]; - if (memberDecl.kind === 204 /* PropertyAssignment */) { - var type = checkExpression(memberDecl.initializer, contextualMapper); - } - else if (memberDecl.kind === 128 /* MethodDeclaration */) { - var type = checkObjectLiteralMethod(memberDecl, contextualMapper); - } - else { - ts.Debug.assert(memberDecl.kind === 205 /* ShorthandPropertyAssignment */); - var type = memberDecl.name.kind === 122 /* ComputedPropertyName */ ? unknownType : checkExpression(memberDecl.name, contextualMapper); - } - typeFlags |= type.flags; - var prop = createSymbol(4 /* Property */ | 67108864 /* Transient */ | member.flags, member.name); - prop.declarations = member.declarations; - prop.parent = member.parent; - if (member.valueDeclaration) { - prop.valueDeclaration = member.valueDeclaration; - } - prop.type = type; - prop.target = member; - member = prop; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; + var member = memberDecl.symbol; + if (memberDecl.kind === 204 /* PropertyAssignment */ || memberDecl.kind === 205 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { + if (memberDecl.kind === 204 /* PropertyAssignment */) { + var type = checkPropertyAssignment(memberDecl, contextualMapper); + } + else if (memberDecl.kind === 128 /* MethodDeclaration */) { + var type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - var getAccessor = ts.getDeclarationOfKind(member, 130 /* GetAccessor */); - if (getAccessor) { - checkAccessorDeclaration(getAccessor); - } - var setAccessor = ts.getDeclarationOfKind(member, 131 /* SetAccessor */); - if (setAccessor) { - checkAccessorDeclaration(setAccessor); - } + ts.Debug.assert(memberDecl.kind === 205 /* ShorthandPropertyAssignment */); + var type = memberDecl.name.kind === 122 /* ComputedPropertyName */ ? unknownType : checkExpression(memberDecl.name, contextualMapper); } - properties[member.name] = member; + typeFlags |= type.flags; + var prop = createSymbol(4 /* Property */ | 67108864 /* Transient */ | member.flags, member.name); + prop.declarations = member.declarations; + prop.parent = member.parent; + if (member.valueDeclaration) { + prop.valueDeclaration = member.valueDeclaration; + } + prop.type = type; + prop.target = member; + member = prop; } + else { + ts.Debug.assert(memberDecl.kind === 130 /* GetAccessor */ || memberDecl.kind === 131 /* SetAccessor */); + checkAccessorDeclaration(memberDecl); + } + if (!ts.hasDynamicName(memberDecl)) { + propertiesTable[member.name] = member; + } + propertiesArray.push(member); } var stringIndexType = getIndexType(0 /* String */); var numberIndexType = getIndexType(1 /* Number */); - var result = createAnonymousType(node.symbol, properties, emptyArray, emptyArray, stringIndexType, numberIndexType); - result.flags |= (typeFlags & 131072 /* Unwidened */); + var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); + result.flags |= 131072 /* ObjectLiteral */ | 524288 /* ContainsObjectLiteral */ | (typeFlags & 262144 /* ContainsUndefinedOrNull */); return result; function getIndexType(kind) { if (contextualType && contextualTypeHasIndexSignature(contextualType, kind)) { var propTypes = []; - for (var id in properties) { - if (ts.hasProperty(properties, id)) { - if (kind === 0 /* String */ || isNumericName(id)) { - var type = getTypeOfSymbol(properties[id]); - if (!ts.contains(propTypes, type)) { - propTypes.push(type); - } + for (var i = 0; i < propertiesArray.length; i++) { + var propertyDecl = node.properties[i]; + if (kind === 0 /* String */ || isNumericName(propertyDecl.name)) { + var type = getTypeOfSymbol(propertiesArray[i]); + if (!ts.contains(propTypes, type)) { + propTypes.push(type); } } } - return propTypes.length ? getUnionType(propTypes) : undefinedType; + var result = propTypes.length ? getUnionType(propTypes) : undefinedType; + typeFlags |= result.flags; + return result; } return undefined; } @@ -11341,8 +11504,10 @@ var ts; if (objectType === unknownType) { return unknownType; } - if (isConstEnumObjectType(objectType) && node.argumentExpression && node.argumentExpression.kind !== 8 /* StringLiteral */) { - error(node.argumentExpression, ts.Diagnostics.Index_expression_arguments_in_const_enums_must_be_of_type_string); + var isConstEnum = isConstEnumObjectType(objectType); + if (isConstEnum && (!node.argumentExpression || node.argumentExpression.kind !== 8 /* StringLiteral */)) { + error(node.argumentExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + return unknownType; } if (node.argumentExpression) { if (node.argumentExpression.kind === 8 /* StringLiteral */ || node.argumentExpression.kind === 7 /* NumericLiteral */) { @@ -11352,10 +11517,14 @@ var ts; getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } + else if (isConstEnum) { + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name, symbolToString(objectType.symbol)); + return unknownType; + } } } - if (indexType.flags & (1 /* Any */ | 258 /* StringLike */ | 132 /* NumberLike */)) { - if (indexType.flags & (1 /* Any */ | 132 /* NumberLike */)) { + if (isTypeOfKind(indexType, 1 /* Any */ | 258 /* StringLike */ | 132 /* NumberLike */)) { + if (isTypeOfKind(indexType, 1 /* Any */ | 132 /* NumberLike */)) { var numberIndexType = getIndexTypeOfType(objectType, 1 /* Number */); if (numberIndexType) { return numberIndexType; @@ -11539,10 +11708,25 @@ var ts; } return args; } + function getEffectiveTypeArguments(callExpression) { + if (callExpression.expression.kind === 90 /* SuperKeyword */) { + var containingClass = ts.getAncestor(callExpression, 191 /* ClassDeclaration */); + var baseClassTypeNode = containingClass && ts.getClassBaseTypeNode(containingClass); + return baseClassTypeNode && baseClassTypeNode.typeArguments; + } + else { + return callExpression.typeArguments; + } + } function resolveCall(node, signatures, candidatesOutArray) { var isTaggedTemplate = node.kind === 153 /* TaggedTemplateExpression */; - var typeArguments = isTaggedTemplate ? undefined : node.typeArguments; - ts.forEach(typeArguments, checkSourceElement); + var typeArguments; + if (!isTaggedTemplate) { + typeArguments = getEffectiveTypeArguments(node); + if (node.expression.kind !== 90 /* SuperKeyword */) { + ts.forEach(typeArguments, checkSourceElement); + } + } var candidates = candidatesOutArray || []; collectCandidates(); if (!candidates.length) { @@ -11659,8 +11843,10 @@ var ts; var result = candidates; var lastParent; var lastSymbol; - var cutoffPos = 0; - var pos; + var cutoffIndex = 0; + var index; + var specializedIndex = -1; + var spliceIndex; ts.Debug.assert(!result.length); for (var i = 0; i < signatures.length; i++) { var signature = signatures[i]; @@ -11668,22 +11854,27 @@ var ts; var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { if (lastParent && parent === lastParent) { - pos++; + index++; } else { lastParent = parent; - pos = cutoffPos; + index = cutoffIndex; } } else { - pos = cutoffPos = result.length; + index = cutoffIndex = result.length; lastParent = parent; } lastSymbol = symbol; - for (var j = result.length; j > pos; j--) { - result[j] = result[j - 1]; + if (signature.hasStringLiterals) { + specializedIndex++; + spliceIndex = specializedIndex; + cutoffIndex++; } - result[pos] = signature; + else { + spliceIndex = index; + } + result.splice(spliceIndex, 0, signature); } } } @@ -11799,7 +11990,7 @@ var ts; return getReturnTypeOfSignature(signature); } function checkTaggedTemplateExpression(node) { - if (compilerOptions.target < 2 /* ES6 */) { + if (languageVersion < 2 /* ES6 */) { grammarErrorOnFirstToken(node.template, ts.Diagnostics.Tagged_templates_are_only_available_when_targeting_ECMAScript_6_and_higher); } return getReturnTypeOfSignature(getResolvedSignature(node)); @@ -11948,7 +12139,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!(type.flags & (1 /* Any */ | 132 /* NumberLike */))) { + if (!isTypeOfKind(type, 1 /* Any */ | 132 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -12052,11 +12243,20 @@ var ts; } return numberType; } - function isStructuredType(type) { - if (type.flags & 16384 /* Union */) { - return !ts.forEach(type.types, function (t) { return !isStructuredType(t); }); + function isTypeOfKind(type, kind) { + if (type.flags & kind) { + return true; } - return (type.flags & (48128 /* ObjectType */ | 512 /* TypeParameter */)) !== 0; + if (type.flags & 16384 /* Union */) { + var types = type.types; + for (var i = 0; i < types.length; i++) { + if (!(types[i].flags & kind)) { + return false; + } + } + return true; + } + return false; } function isConstEnumObjectType(type) { return type.flags & (48128 /* ObjectType */ | 32768 /* Anonymous */) && type.symbol && isConstEnumSymbol(type.symbol); @@ -12065,7 +12265,7 @@ var ts; return (symbol.flags & 128 /* ConstEnum */) !== 0; } function checkInstanceOfExpression(node, leftType, rightType) { - if (!(leftType.flags & 1 /* Any */ || isStructuredType(leftType))) { + if (isTypeOfKind(leftType, 510 /* Primitive */)) { error(node.left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } if (!(rightType.flags & 1 /* Any */ || isTypeSubtypeOf(rightType, globalFunctionType))) { @@ -12074,10 +12274,10 @@ var ts; return booleanType; } function checkInExpression(node, leftType, rightType) { - if (leftType !== anyType && leftType !== stringType && leftType !== numberType) { + if (!isTypeOfKind(leftType, 1 /* Any */ | 258 /* StringLike */ | 132 /* NumberLike */)) { error(node.left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number); } - if (!(rightType.flags & 1 /* Any */ || isStructuredType(rightType))) { + if (!isTypeOfKind(rightType, 1 /* Any */ | 48128 /* ObjectType */ | 512 /* TypeParameter */)) { error(node.right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -12088,7 +12288,7 @@ var ts; var p = properties[i]; if (p.kind === 204 /* PropertyAssignment */ || p.kind === 205 /* ShorthandPropertyAssignment */) { var name = p.name; - var type = sourceType.flags & 1 /* Any */ ? sourceType : getTypeOfPropertyOfType(sourceType, name.text) || isNumericName(name.text) && getIndexTypeOfType(sourceType, 1 /* Number */) || getIndexTypeOfType(sourceType, 0 /* String */); + var type = sourceType.flags & 1 /* Any */ ? sourceType : getTypeOfPropertyOfType(sourceType, name.text) || isNumericLiteralName(name.text) && getIndexTypeOfType(sourceType, 1 /* Number */) || getIndexTypeOfType(sourceType, 0 /* String */); if (type) { checkDestructuringAssignment(p.initializer || name, type); } @@ -12207,13 +12407,13 @@ var ts; if (rightType.flags & (32 /* Undefined */ | 64 /* Null */)) rightType = leftType; var resultType; - if (leftType.flags & 132 /* NumberLike */ && rightType.flags & 132 /* NumberLike */) { + if (isTypeOfKind(leftType, 132 /* NumberLike */) && isTypeOfKind(rightType, 132 /* NumberLike */)) { resultType = numberType; } - else if (leftType.flags & 258 /* StringLike */ || rightType.flags & 258 /* StringLike */) { + else if (isTypeOfKind(leftType, 258 /* StringLike */) || isTypeOfKind(rightType, 258 /* StringLike */)) { resultType = stringType; } - else if (leftType.flags & 1 /* Any */ || leftType === unknownType || rightType.flags & 1 /* Any */ || rightType === unknownType) { + else if (leftType.flags & 1 /* Any */ || rightType.flags & 1 /* Any */) { resultType = anyType; } if (!resultType) { @@ -12311,8 +12511,17 @@ var ts; } return links.resolvedType; } + function checkPropertyAssignment(node, contextualMapper) { + if (ts.hasDynamicName(node)) { + checkComputedPropertyName(node.name); + } + return checkExpression(node.initializer, contextualMapper); + } function checkObjectLiteralMethod(node, contextualMapper) { checkGrammarMethod(node); + if (ts.hasDynamicName(node)) { + checkComputedPropertyName(node.name); + } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); } @@ -12435,12 +12644,15 @@ var ts; checkGrammarModifiers(node) || checkGrammarEvalOrArgumentsInStrictMode(node, node.name); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (node.flags & (16 /* Public */ | 32 /* Private */ | 64 /* Protected */)) { + if (node.flags & 112 /* AccessibilityModifier */) { func = ts.getContainingFunction(node); if (!(func.kind === 129 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } + if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); + } if (node.dotDotDotToken) { if (!isArrayType(getTypeOfSymbol(node.symbol))) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); @@ -12585,7 +12797,7 @@ var ts; error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement); } } - if (!ts.hasComputedNameButNotSymbol(node)) { + if (!ts.hasDynamicName(node)) { var otherKind = node.kind === 130 /* GetAccessor */ ? 131 /* SetAccessor */ : 130 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { @@ -12600,8 +12812,8 @@ var ts; } } } - checkAndStoreTypeOfAccessors(getSymbolOfNode(node)); } + checkAndStoreTypeOfAccessors(getSymbolOfNode(node)); } checkFunctionLikeDeclaration(node); } @@ -12909,7 +13121,10 @@ var ts; } function checkFunctionLikeDeclaration(node) { checkSignatureDeclaration(node); - if (!ts.hasComputedNameButNotSymbol(node)) { + if (ts.hasDynamicName(node)) { + checkComputedPropertyName(node.name); + } + else { var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; var firstDeclaration = ts.getDeclarationOfKind(localSymbol, node.kind); @@ -13063,7 +13278,8 @@ var ts; } function checkVariableLikeDeclaration(node) { checkSourceElement(node.type); - if (ts.hasComputedNameButNotSymbol(node)) { + if (ts.hasDynamicName(node)) { + checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } @@ -13207,7 +13423,7 @@ var ts; } } var exprType = checkExpression(node.expression); - if (!(exprType.flags & 1 /* Any */ || isStructuredType(exprType))) { + if (!isTypeOfKind(exprType, 1 /* Any */ | 48128 /* ObjectType */ | 512 /* TypeParameter */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -13327,29 +13543,6 @@ var ts; checkBlock(node.finallyBlock); } function checkIndexConstraints(type) { - function checkIndexConstraintForProperty(prop, propertyType, indexDeclaration, indexType, indexKind) { - if (!indexType) { - return; - } - if (indexKind === 1 /* Number */ && !isNumericName(prop.name)) { - return; - } - var errorNode; - if (prop.parent === type.symbol) { - errorNode = prop.valueDeclaration; - } - else if (indexDeclaration) { - errorNode = indexDeclaration; - } - else if (type.flags & 2048 /* Interface */) { - var someBaseClassHasBothPropertyAndIndexer = ts.forEach(type.baseTypes, function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); - errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : type.symbol.declarations[0]; - } - if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { - var errorMessage = indexKind === 0 /* String */ ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; - error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); - } - } var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); var stringIndexType = getIndexTypeOfType(type, 0 /* String */); @@ -13357,9 +13550,20 @@ var ts; if (stringIndexType || numberIndexType) { ts.forEach(getPropertiesOfObjectType(type), function (prop) { var propType = getTypeOfSymbol(prop); - checkIndexConstraintForProperty(prop, propType, declaredStringIndexer, stringIndexType, 0 /* String */); - checkIndexConstraintForProperty(prop, propType, declaredNumberIndexer, numberIndexType, 1 /* Number */); + checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); + if (type.flags & 1024 /* Class */ && type.symbol.valueDeclaration.kind === 191 /* ClassDeclaration */) { + var classDeclaration = type.symbol.valueDeclaration; + for (var i = 0; i < classDeclaration.members.length; i++) { + var member = classDeclaration.members[i]; + if (!(member.flags & 128 /* Static */) && ts.hasDynamicName(member)) { + var propType = getTypeOfSymbol(member.symbol); + checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + } + } + } } var errorNode; if (stringIndexType && numberIndexType) { @@ -13372,6 +13576,29 @@ var ts; if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); } + function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { + if (!indexType) { + return; + } + if (indexKind === 1 /* Number */ && !isNumericName(prop.valueDeclaration.name)) { + return; + } + var errorNode; + if (prop.valueDeclaration.name.kind === 122 /* ComputedPropertyName */ || prop.parent === containingType.symbol) { + errorNode = prop.valueDeclaration; + } + else if (indexDeclaration) { + errorNode = indexDeclaration; + } + else if (containingType.flags & 2048 /* Interface */) { + var someBaseClassHasBothPropertyAndIndexer = ts.forEach(containingType.baseTypes, function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); + errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + } + if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { + var errorMessage = indexKind === 0 /* String */ ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; + error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); + } + } } function checkTypeNameIsReserved(name, message) { switch (name.text) { @@ -13600,7 +13827,7 @@ var ts; var ambient = ts.isInAmbientContext(node); var enumIsConst = ts.isConst(node); ts.forEach(node.members, function (member) { - if (isNumericName(member.name.text)) { + if (member.name.kind !== 122 /* ComputedPropertyName */ && isNumericLiteralName(member.name.text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } var initializer = member.initializer; @@ -14564,8 +14791,8 @@ var ts; if (symbol && (symbol.flags & 8 /* EnumMember */)) { var declaration = symbol.valueDeclaration; var constantValue; - if (declaration.kind === 206 /* EnumMember */ && (constantValue = getNodeLinks(declaration).enumMemberValue) !== undefined) { - return constantValue; + if (declaration.kind === 206 /* EnumMember */) { + return getEnumMemberValue(declaration); } } return undefined; @@ -14624,7 +14851,7 @@ var ts; globalNumberType = getGlobalType("Number"); globalBooleanType = getGlobalType("Boolean"); globalRegExpType = getGlobalType("RegExp"); - globalTemplateStringsArrayType = compilerOptions.target >= 2 /* ES6 */ ? getGlobalType("TemplateStringsArray") : unknownType; + globalTemplateStringsArrayType = languageVersion >= 2 /* ES6 */ ? getGlobalType("TemplateStringsArray") : unknownType; anyArrayType = createArrayType(anyType); } function checkGrammarModifiers(node) { @@ -14748,6 +14975,9 @@ var ts; else if (node.kind === 192 /* InterfaceDeclaration */ && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_declare_modifier_cannot_be_used_with_an_interface_declaration, "declare"); } + else if (node.kind === 124 /* Parameter */ && (flags & 112 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); + } } function checkGrammarForDisallowedTrailingComma(list) { if (list && list.hasTrailingComma) { @@ -14932,16 +15162,14 @@ var ts; } function checkGrammarComputedPropertyName(node) { if (node.kind !== 122 /* ComputedPropertyName */) { - return; + return false; } - grammarErrorOnNode(node, ts.Diagnostics.Computed_property_names_are_not_currently_supported); - return; var computedPropertyName = node; - if (compilerOptions.target < 2 /* ES6 */) { - grammarErrorOnNode(node, ts.Diagnostics.Computed_property_names_are_only_available_when_targeting_ECMAScript_6_and_higher); + if (languageVersion < 2 /* ES6 */) { + return grammarErrorOnNode(node, ts.Diagnostics.Computed_property_names_are_only_available_when_targeting_ECMAScript_6_and_higher); } else if (computedPropertyName.expression.kind === 163 /* BinaryExpression */ && computedPropertyName.expression.operator === 23 /* CommaToken */) { - grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); + return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { @@ -15017,7 +15245,7 @@ var ts; } function checkGrammarAccessor(accessor) { var kind = accessor.kind; - if (compilerOptions.target < 1 /* ES5 */) { + if (languageVersion < 1 /* ES5 */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } else if (ts.isInAmbientContext(accessor)) { @@ -15182,7 +15410,7 @@ var ts; if (!declarationList.declarations.length) { return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); } - if (compilerOptions.target < 2 /* ES6 */) { + if (languageVersion < 2 /* ES6 */) { if (ts.isLet(declarationList)) { return grammarErrorOnFirstToken(declarationList, ts.Diagnostics.let_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher); } @@ -15265,7 +15493,7 @@ var ts; function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var scanner = ts.createScanner(compilerOptions.target, true, sourceFile.text); + var scanner = ts.createScanner(languageVersion, true, sourceFile.text); var start = scanToken(scanner, node.pos); diagnostics.push(ts.createFileDiagnostic(sourceFile, start, scanner.getTextPos() - start, message, arg0, arg1, arg2)); return true; @@ -15365,7 +15593,7 @@ var ts; if (node.parserContextFlags & 1 /* StrictMode */) { return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode); } - else if (compilerOptions.target >= 1 /* ES5 */) { + else if (languageVersion >= 1 /* ES5 */) { return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); } } @@ -15373,7 +15601,7 @@ var ts; function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var scanner = ts.createScanner(compilerOptions.target, true, sourceFile.text); + var scanner = ts.createScanner(languageVersion, true, sourceFile.text); scanToken(scanner, node.pos); diagnostics.push(ts.createFileDiagnostic(sourceFile, scanner.getTextPos(), 0, message, arg0, arg1, arg2)); return true; @@ -15500,9 +15728,10 @@ var ts; function writeCommentRange(currentSourceFile, writer, comment, newLine) { if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { var firstCommentLineAndCharacter = currentSourceFile.getLineAndCharacterFromPosition(comment.pos); + var lastLine = currentSourceFile.getLineStarts().length; var firstCommentLineIndent; for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { - var nextLineStart = currentSourceFile.getPositionFromLineAndCharacter(currentLine + 1, 1); + var nextLineStart = currentLine === lastLine ? (comment.end + 1) : currentSourceFile.getPositionFromLineAndCharacter(currentLine + 1, 1); if (pos !== comment.pos) { if (firstCommentLineIndent === undefined) { firstCommentLineIndent = calculateIndent(currentSourceFile.getPositionFromLineAndCharacter(firstCommentLineAndCharacter.line, 1), comment.pos); @@ -15622,6 +15851,7 @@ var ts; function emitDeclarations(host, resolver, diagnostics, jsFilePath, root) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); + var languageVersion = compilerOptions.target || 0 /* ES3 */; var write; var writeLine; var increaseIndent; @@ -16114,6 +16344,9 @@ var ts; } } function emitPropertyDeclaration(node) { + if (ts.hasDynamicName(node)) { + return; + } emitJsDocComments(node); emitClassMemberDeclarationFlags(node); emitVariableDeclaration(node); @@ -16182,6 +16415,9 @@ var ts; } } function emitAccessorDeclaration(node) { + if (ts.hasDynamicName(node)) { + return; + } var accessors = getAllAccessorDeclarations(node.parent, node); if (node === accessors.firstAccessor) { emitJsDocComments(accessors.getAccessor); @@ -16239,6 +16475,9 @@ var ts; } } function emitFunctionDeclaration(node) { + if (ts.hasDynamicName(node)) { + return; + } if ((node.kind !== 190 /* FunctionDeclaration */ || resolver.isDeclarationVisible(node)) && !resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); if (node.kind === 190 /* FunctionDeclaration */) { @@ -16490,6 +16729,7 @@ var ts; ts.getDeclarationDiagnostics = getDeclarationDiagnostics; function emitFiles(resolver, host, targetSourceFile) { var compilerOptions = host.getCompilerOptions(); + var languageVersion = compilerOptions.target || 0 /* ES3 */; var sourceMapDataList = compilerOptions.sourceMap ? [] : undefined; var diagnostics = []; var newLine = host.getNewLine(); @@ -16646,7 +16886,11 @@ var ts; if (scopeName) { var parentIndex = getSourceMapNameIndex(); if (parentIndex !== -1) { - scopeName = sourceMapData.sourceMapNames[parentIndex] + "." + scopeName; + var name = node.name; + if (!name || name.kind !== 122 /* ComputedPropertyName */) { + scopeName = "." + scopeName; + } + scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName; } scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName); if (scopeNameIndex === undefined) { @@ -16662,7 +16906,8 @@ var ts; } else if (node.kind === 190 /* FunctionDeclaration */ || node.kind === 156 /* FunctionExpression */ || node.kind === 128 /* MethodDeclaration */ || node.kind === 127 /* MethodSignature */ || node.kind === 130 /* GetAccessor */ || node.kind === 131 /* SetAccessor */ || node.kind === 195 /* ModuleDeclaration */ || node.kind === 191 /* ClassDeclaration */ || node.kind === 194 /* EnumDeclaration */) { if (node.name) { - scopeName = node.name.text; + var name = node.name; + scopeName = name.kind === 122 /* ComputedPropertyName */ ? ts.getTextOfNode(name) : node.name.text; } recordScopeNameStart(scopeName); } @@ -16882,11 +17127,11 @@ var ts; return false; } function emitLiteral(node) { - var text = compilerOptions.target < 2 /* ES6 */ && ts.isTemplateLiteralKind(node.kind) ? getTemplateLiteralAsStringLiteral(node) : node.parent ? ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node) : node.text; + var text = languageVersion < 2 /* ES6 */ && ts.isTemplateLiteralKind(node.kind) ? getTemplateLiteralAsStringLiteral(node) : node.parent ? ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node) : node.text; if (compilerOptions.sourceMap && (node.kind === 8 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writer.writeLiteral(text); } - else if (compilerOptions.target < 2 /* ES6 */ && node.kind === 7 /* NumericLiteral */ && isBinaryOrOctalIntegerLiteral(text)) { + else if (languageVersion < 2 /* ES6 */ && node.kind === 7 /* NumericLiteral */ && isBinaryOrOctalIntegerLiteral(text)) { write(node.text); } else { @@ -16897,7 +17142,7 @@ var ts; return '"' + ts.escapeString(node.text) + '"'; } function emitTemplateExpression(node) { - if (compilerOptions.target >= 2 /* ES6 */) { + if (languageVersion >= 2 /* ES6 */) { ts.forEachChild(node, emit); return; } @@ -16944,7 +17189,7 @@ var ts; } } function comparePrecedenceToBinaryPlus(expression) { - ts.Debug.assert(compilerOptions.target <= 1 /* ES5 */); + ts.Debug.assert(languageVersion < 2 /* ES6 */); switch (expression.kind) { case 163 /* BinaryExpression */: switch (expression.operator) { @@ -17110,7 +17355,7 @@ var ts; write("[]"); return; } - if (compilerOptions.target >= 2 /* ES6 */) { + if (languageVersion >= 2 /* ES6 */) { write("["); emitList(elements, 0, elements.length, (node.flags & 256 /* MultiLine */) !== 0, elements.hasTrailingComma); write("]"); @@ -17155,7 +17400,7 @@ var ts; if (!multiLine) { write(" "); } - emitList(properties, 0, properties.length, multiLine, properties.hasTrailingComma && compilerOptions.target >= 1 /* ES5 */); + emitList(properties, 0, properties.length, multiLine, properties.hasTrailingComma && languageVersion >= 1 /* ES5 */); if (!multiLine) { write(" "); } @@ -17168,32 +17413,23 @@ var ts; write("]"); } function emitMethod(node) { - if (!ts.isObjectLiteralMethod(node)) { - return; - } - emitLeadingComments(node); emit(node.name); - if (compilerOptions.target < 2 /* ES6 */) { + if (languageVersion < 2 /* ES6 */) { write(": function "); } emitSignatureAndBody(node); - emitTrailingComments(node); } function emitPropertyAssignment(node) { - emitLeadingComments(node); emit(node.name); write(": "); emit(node.initializer); - emitTrailingComments(node); } function emitShorthandPropertyAssignment(node) { - emitLeadingComments(node); emit(node.name); - if (compilerOptions.target < 2 /* ES6 */ || resolver.getExpressionNamePrefix(node.name)) { + if (languageVersion < 2 /* ES6 */ || resolver.getExpressionNamePrefix(node.name)) { write(": "); emitExpressionIdentifier(node.name); } - emitTrailingComments(node); } function tryEmitConstantValue(node) { var constantValue = resolver.getConstantValue(node); @@ -17261,7 +17497,7 @@ var ts; } } function emitTaggedTemplateExpression(node) { - ts.Debug.assert(compilerOptions.target >= 2 /* ES6 */, "Trying to emit a tagged template in pre-ES6 mode."); + ts.Debug.assert(languageVersion >= 2 /* ES6 */, "Trying to emit a tagged template in pre-ES6 mode."); emit(node.tag); write(" "); emit(node.template); @@ -17314,7 +17550,7 @@ var ts; write(ts.tokenToString(node.operator)); } function emitBinaryExpression(node) { - if (compilerOptions.target < 2 /* ES6 */ && node.operator === 52 /* EqualsToken */ && (node.left.kind === 148 /* ObjectLiteralExpression */ || node.left.kind === 147 /* ArrayLiteralExpression */)) { + if (languageVersion < 2 /* ES6 */ && node.operator === 52 /* EqualsToken */ && (node.left.kind === 148 /* ObjectLiteralExpression */ || node.left.kind === 147 /* ArrayLiteralExpression */)) { emitDestructuring(node); } else { @@ -17363,13 +17599,10 @@ var ts; } } function emitExpressionStatement(node) { - emitLeadingComments(node); emitParenthesized(node.expression, node.expression.kind === 157 /* ArrowFunction */); write(";"); - emitTrailingComments(node); } function emitIfStatement(node) { - emitLeadingComments(node); var endPos = emitToken(83 /* IfKeyword */, node.pos); write(" "); endPos = emitToken(16 /* OpenParenToken */, endPos); @@ -17387,7 +17620,6 @@ var ts; emitEmbeddedStatement(node.elseStatement); } } - emitTrailingComments(node); } function emitDoStatement(node) { write("do"); @@ -17469,11 +17701,9 @@ var ts; write(";"); } function emitReturnStatement(node) { - emitLeadingComments(node); emitToken(89 /* ReturnKeyword */, node.pos); emitOptional(" ", node.expression); write(";"); - emitTrailingComments(node); } function emitWithStatement(node) { write("with ("); @@ -17754,9 +17984,8 @@ var ts; } } function emitVariableDeclaration(node) { - emitLeadingComments(node); if (ts.isBindingPattern(node.name)) { - if (compilerOptions.target < 2 /* ES6 */) { + if (languageVersion < 2 /* ES6 */) { emitDestructuring(node); } else { @@ -17768,10 +17997,8 @@ var ts; emitModuleMemberName(node); emitOptional(" = ", node.initializer); } - emitTrailingComments(node); } function emitVariableStatement(node) { - emitLeadingComments(node); if (!(node.flags & 1 /* Export */)) { if (ts.isLet(node.declarationList)) { write("let "); @@ -17785,11 +18012,9 @@ var ts; } emitCommaList(node.declarationList.declarations); write(";"); - emitTrailingComments(node); } function emitParameter(node) { - emitLeadingComments(node); - if (compilerOptions.target < 2 /* ES6 */) { + if (languageVersion < 2 /* ES6 */) { if (ts.isBindingPattern(node.name)) { var name = createTempVariable(node); if (!tempParameters) { @@ -17809,10 +18034,9 @@ var ts; emit(node.name); emitOptional(" = ", node.initializer); } - emitTrailingComments(node); } function emitDefaultValueAssignments(node) { - if (compilerOptions.target < 2 /* ES6 */) { + if (languageVersion < 2 /* ES6 */) { var tempIndex = 0; ts.forEach(node.parameters, function (p) { if (ts.isBindingPattern(p.name)) { @@ -17841,7 +18065,7 @@ var ts; } } function emitRestParameter(node) { - if (compilerOptions.target < 2 /* ES6 */ && ts.hasRestParameters(node)) { + if (languageVersion < 2 /* ES6 */ && ts.hasRestParameters(node)) { var restIndex = node.parameters.length - 1; var restParam = node.parameters[restIndex]; var tempName = createTempVariable(node, true).text; @@ -17879,11 +18103,9 @@ var ts; } } function emitAccessor(node) { - emitLeadingComments(node); write(node.kind === 130 /* GetAccessor */ ? "get " : "set "); emit(node.name); emitSignatureAndBody(node); - emitTrailingComments(node); } function emitFunctionDeclaration(node) { if (ts.nodeIsMissing(node.body)) { @@ -17914,7 +18136,7 @@ var ts; write("("); if (node) { var parameters = node.parameters; - var omitCount = compilerOptions.target < 2 /* ES6 */ && ts.hasRestParameters(node) ? 1 : 0; + var omitCount = languageVersion < 2 /* ES6 */ && ts.hasRestParameters(node) ? 1 : 0; emitList(parameters, 0, parameters.length - omitCount, false, false); } write(")"); @@ -17945,7 +18167,7 @@ var ts; write(" "); emitStart(node.body); write("return "); - emitNode(node.body); + emitNode(node.body, true); emitEnd(node.body); write(";"); emitTempDeclarations(false); @@ -17962,7 +18184,7 @@ var ts; writeLine(); emitLeadingComments(node.body); write("return "); - emit(node.body); + emit(node.body, true); write(";"); emitTrailingComments(node.body); } @@ -18136,7 +18358,6 @@ var ts; }); } function emitClassDeclaration(node) { - emitLeadingComments(node); write("var "); emit(node.name); write(" = (function ("); @@ -18186,7 +18407,6 @@ var ts; emitEnd(node); write(";"); } - emitTrailingComments(node); function emitConstructorOfClass() { var saveTempCount = tempCount; var saveTempVariables = tempVariables; @@ -18261,12 +18481,14 @@ var ts; function emitInterfaceDeclaration(node) { emitPinnedOrTripleSlashComments(node); } - function emitEnumDeclaration(node) { + function shouldEmitEnumDeclaration(node) { var isConstEnum = ts.isConst(node); - if (isConstEnum && !compilerOptions.preserveConstEnums) { + return !isConstEnum || compilerOptions.preserveConstEnums; + } + function emitEnumDeclaration(node) { + if (!shouldEmitEnumDeclaration(node)) { return; } - emitLeadingComments(node); if (!(node.flags & 1 /* Export */)) { emitStart(node); write("var "); @@ -18283,7 +18505,7 @@ var ts; write(") {"); increaseIndent(); scopeEmitStart(node); - emitEnumMemberDeclarations(isConstEnum); + emitLines(node.members); decreaseIndent(); writeLine(); emitToken(15 /* CloseBraceToken */, node.members.end); @@ -18304,31 +18526,26 @@ var ts; emitEnd(node); write(";"); } - emitTrailingComments(node); - function emitEnumMemberDeclarations(isConstEnum) { - ts.forEach(node.members, function (member) { - writeLine(); - emitLeadingComments(member); - emitStart(member); - write(resolver.getLocalNameOfContainer(node)); - write("["); - write(resolver.getLocalNameOfContainer(node)); - write("["); - emitExpressionForPropertyName(member.name); - write("] = "); - if (member.initializer && !isConstEnum) { - emit(member.initializer); - } - else { - write(resolver.getEnumMemberValue(member).toString()); - } - write("] = "); - emitExpressionForPropertyName(member.name); - emitEnd(member); - write(";"); - emitTrailingComments(member); - }); + } + function emitEnumMember(node) { + var enumParent = node.parent; + emitStart(node); + write(resolver.getLocalNameOfContainer(enumParent)); + write("["); + write(resolver.getLocalNameOfContainer(enumParent)); + write("["); + emitExpressionForPropertyName(node.name); + write("] = "); + if (node.initializer && !ts.isConst(enumParent)) { + emit(node.initializer); } + else { + write(resolver.getEnumMemberValue(node).toString()); + } + write("] = "); + emitExpressionForPropertyName(node.name); + emitEnd(node); + write(";"); } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { if (moduleDeclaration.body.kind === 195 /* ModuleDeclaration */) { @@ -18336,12 +18553,14 @@ var ts; return recursiveInnerModule || moduleDeclaration.body; } } + function shouldEmitModuleDeclaration(node) { + return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums); + } function emitModuleDeclaration(node) { - var shouldEmit = ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums); + var shouldEmit = shouldEmitModuleDeclaration(node); if (!shouldEmit) { return emitPinnedOrTripleSlashComments(node); } - emitLeadingComments(node); emitStart(node); write("var "); emit(node.name); @@ -18386,7 +18605,6 @@ var ts; emitModuleMemberName(node); write(" = {}));"); emitEnd(node); - emitTrailingComments(node); } function emitImportDeclaration(node) { var emitImportDeclaration = resolver.isReferencedImportDeclaration(node); @@ -18559,13 +18777,38 @@ var ts; } emitLeadingComments(node.endOfFileToken); } - function emitNode(node) { + function emitNode(node, disableComments) { if (!node) { return; } if (node.flags & 2 /* Ambient */) { return emitPinnedOrTripleSlashComments(node); } + var emitComments = !disableComments && shouldEmitLeadingAndTrailingComments(node); + if (emitComments) { + emitLeadingComments(node); + } + emitJavaScriptWorker(node); + if (emitComments) { + emitTrailingComments(node); + } + } + function shouldEmitLeadingAndTrailingComments(node) { + switch (node.kind) { + case 192 /* InterfaceDeclaration */: + case 190 /* FunctionDeclaration */: + case 197 /* ImportDeclaration */: + case 193 /* TypeAliasDeclaration */: + case 198 /* ExportAssignment */: + return false; + case 195 /* ModuleDeclaration */: + return shouldEmitModuleDeclaration(node); + case 194 /* EnumDeclaration */: + return shouldEmitEnumDeclaration(node); + } + return true; + } + function emitJavaScriptWorker(node) { switch (node.kind) { case 64 /* Identifier */: return emitIdentifier(node); @@ -18702,6 +18945,8 @@ var ts; return emitInterfaceDeclaration(node); case 194 /* EnumDeclaration */: return emitEnumDeclaration(node); + case 206 /* EnumMember */: + return emitEnumMember(node); case 195 /* ModuleDeclaration */: return emitModuleDeclaration(node); case 197 /* ImportDeclaration */: @@ -18724,15 +18969,17 @@ var ts; return leadingComments; } function getLeadingCommentsToEmit(node) { - if (node.parent.kind === 207 /* SourceFile */ || node.pos !== node.parent.pos) { - var leadingComments; - if (hasDetachedComments(node.pos)) { - leadingComments = getLeadingCommentsWithoutDetachedComments(); + if (node.parent) { + if (node.parent.kind === 207 /* SourceFile */ || node.pos !== node.parent.pos) { + var leadingComments; + if (hasDetachedComments(node.pos)) { + leadingComments = getLeadingCommentsWithoutDetachedComments(); + } + else { + leadingComments = ts.getLeadingCommentRangesOfNode(node, currentSourceFile); + } + return leadingComments; } - else { - leadingComments = ts.getLeadingCommentRangesOfNode(node, currentSourceFile); - } - return leadingComments; } } function emitLeadingDeclarationComments(node) { @@ -18741,9 +18988,11 @@ var ts; emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); } function emitTrailingDeclarationComments(node) { - if (node.parent.kind === 207 /* SourceFile */ || node.end !== node.parent.end) { - var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, node.end); - emitComments(currentSourceFile, writer, trailingComments, false, newLine, writeComment); + if (node.parent) { + if (node.parent.kind === 207 /* SourceFile */ || node.end !== node.parent.end) { + var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, node.end); + emitComments(currentSourceFile, writer, trailingComments, false, newLine, writeComment); + } } } function emitLeadingCommentsOfLocalPosition(pos) { @@ -19181,7 +19430,7 @@ var ts; return; } var firstExternalModule = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); - if (firstExternalModule && options.module === 0 /* None */) { + if (firstExternalModule && !options.module) { var externalModuleErrorSpan = ts.getErrorSpanForNode(firstExternalModule.externalModuleIndicator); var errorStart = ts.skipTrivia(firstExternalModule.text, externalModuleErrorSpan.pos); var errorLength = externalModuleErrorSpan.end - errorStart; @@ -19261,6 +19510,10 @@ var ts; type: "boolean", description: ts.Diagnostics.Print_this_message }, + { + name: "listFiles", + type: "boolean" + }, { name: "locale", type: "string" @@ -19268,6 +19521,7 @@ var ts; { name: "mapRoot", type: "string", + isFilePath: true, description: ts.Diagnostics.Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, paramType: ts.Diagnostics.LOCATION }, @@ -19318,6 +19572,7 @@ var ts; { name: "outDir", type: "string", + isFilePath: true, description: ts.Diagnostics.Redirect_output_structure_to_the_directory, paramType: ts.Diagnostics.DIRECTORY }, @@ -19326,6 +19581,14 @@ var ts; type: "boolean", description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code }, + { + name: "project", + shortName: "p", + type: "string", + isFilePath: true, + description: ts.Diagnostics.Compile_the_project_in_the_given_directory, + paramType: ts.Diagnostics.DIRECTORY + }, { name: "removeComments", type: "boolean", @@ -19339,6 +19602,7 @@ var ts; { name: "sourceRoot", type: "string", + isFilePath: true, description: ts.Diagnostics.Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, paramType: ts.Diagnostics.LOCATION }, @@ -19368,21 +19632,18 @@ var ts; description: ts.Diagnostics.Watch_input_files } ]; - var shortOptionNames = {}; - var optionNameMap = {}; - ts.forEach(ts.optionDeclarations, function (option) { - optionNameMap[option.name.toLowerCase()] = option; - if (option.shortName) { - shortOptionNames[option.shortName] = option.name; - } - }); function parseCommandLine(commandLine) { - var options = { - target: 0 /* ES3 */, - module: 0 /* None */ - }; + var options = {}; var filenames = []; var errors = []; + var shortOptionNames = {}; + var optionNameMap = {}; + ts.forEach(ts.optionDeclarations, function (option) { + optionNameMap[option.name.toLowerCase()] = option; + if (option.shortName) { + shortOptionNames[option.shortName] = option.name; + } + }); parseStrings(commandLine); return { options: options, @@ -19472,10 +19733,87 @@ var ts; } } ts.parseCommandLine = parseCommandLine; + function readConfigFile(filename) { + try { + var text = ts.sys.readFile(filename); + return /\S/.test(text) ? JSON.parse(text) : {}; + } + catch (e) { + } + } + ts.readConfigFile = readConfigFile; + function parseConfigFile(json, basePath) { + var errors = []; + return { + options: getCompilerOptions(), + filenames: getFiles(), + errors: errors + }; + function getCompilerOptions() { + var options = {}; + var optionNameMap = {}; + ts.forEach(ts.optionDeclarations, function (option) { + optionNameMap[option.name] = option; + }); + var jsonOptions = json["compilerOptions"]; + if (jsonOptions) { + for (var id in jsonOptions) { + if (ts.hasProperty(optionNameMap, id)) { + var opt = optionNameMap[id]; + var optType = opt.type; + var value = jsonOptions[id]; + var expectedType = typeof optType === "string" ? optType : "string"; + if (typeof value === expectedType) { + if (typeof optType !== "string") { + var key = value.toLowerCase(); + if (ts.hasProperty(optType, key)) { + value = optType[key]; + } + else { + errors.push(ts.createCompilerDiagnostic(opt.error)); + value = 0; + } + } + if (opt.isFilePath) { + value = ts.normalizePath(ts.combinePaths(basePath, value)); + } + options[opt.name] = value; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, id, expectedType)); + } + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, id)); + } + } + } + return options; + } + function getFiles() { + var files = []; + if (ts.hasProperty(json, "files")) { + if (json["files"] instanceof Array) { + var files = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); + } + } + else { + var sysFiles = ts.sys.readDirectory(basePath, ".ts"); + for (var i = 0; i < sysFiles.length; i++) { + var name = sysFiles[i]; + if (!ts.fileExtensionIs(name, ".d.ts") || !ts.contains(sysFiles, name.substr(0, name.length - 5) + ".ts")) { + files.push(name); + } + } + } + return files; + } + } + ts.parseConfigFile = parseConfigFile; })(ts || (ts = {})); var ts; (function (ts) { - var version = "1.4.0.0"; + var version = "1.5.0.0"; function validateLocaleAndSetLanguage(locale, errors) { var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase()); if (!matchResult) { @@ -19568,13 +19906,39 @@ var ts; function reportTimeStatistic(name, time) { reportStatisticalValue(name, (time / 1000).toFixed(2) + "s"); } + function isJSONSupported() { + return typeof JSON === "object" && typeof JSON.parse === "function"; + } + function findConfigFile() { + var searchPath = ts.normalizePath(ts.sys.getCurrentDirectory()); + var filename = "tsconfig.json"; + while (true) { + if (ts.sys.fileExists(filename)) { + return filename; + } + var parentPath = ts.getDirectoryPath(searchPath); + if (parentPath === searchPath) { + break; + } + searchPath = parentPath; + filename = "../" + filename; + } + return undefined; + } function executeCommandLine(args) { var commandLine = ts.parseCommandLine(args); - var compilerOptions = commandLine.options; - if (compilerOptions.locale) { - if (typeof JSON === "undefined") { + var configFilename; + var configFileWatcher; + var cachedProgram; + var rootFilenames; + var compilerOptions; + var compilerHost; + var hostGetSourceFile; + var timerHandle; + if (commandLine.options.locale) { + if (!isJSONSupported()) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--locale")); - return ts.sys.exit(1); + return ts.sys.exit(5 /* CompilerOptionsErrors */); } validateLocaleAndSetLanguage(commandLine.options.locale, commandLine.errors); } @@ -19582,92 +19946,126 @@ var ts; reportDiagnostics(commandLine.errors); return ts.sys.exit(5 /* CompilerOptionsErrors */); } - if (compilerOptions.version) { + if (commandLine.options.version) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Version_0, version)); return ts.sys.exit(0 /* Succeeded */); } - if (compilerOptions.help) { + if (commandLine.options.help) { printVersion(); printHelp(); return ts.sys.exit(0 /* Succeeded */); } - if (commandLine.filenames.length === 0) { + if (commandLine.options.project) { + if (!isJSONSupported()) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--project")); + return ts.sys.exit(5 /* CompilerOptionsErrors */); + } + configFilename = ts.normalizePath(ts.combinePaths(commandLine.options.project, "tsconfig.json")); + if (commandLine.filenames.length !== 0) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line)); + return ts.sys.exit(5 /* CompilerOptionsErrors */); + } + } + else if (commandLine.filenames.length === 0 && isJSONSupported()) { + configFilename = findConfigFile(); + } + if (commandLine.filenames.length === 0 && !configFilename) { printVersion(); printHelp(); return ts.sys.exit(5 /* CompilerOptionsErrors */); } - var defaultCompilerHost = ts.createCompilerHost(compilerOptions); - if (compilerOptions.watch) { + if (commandLine.options.watch) { if (!ts.sys.watchFile) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--watch")); return ts.sys.exit(5 /* CompilerOptionsErrors */); } - watchProgram(commandLine, defaultCompilerHost); + if (configFilename) { + configFileWatcher = ts.sys.watchFile(configFilename, configFileChanged); + } } - else { - var result = compile(commandLine, defaultCompilerHost).exitStatus; - return ts.sys.exit(result); + performCompilation(); + function performCompilation() { + if (!cachedProgram) { + if (configFilename) { + var configObject = ts.readConfigFile(configFilename); + if (!configObject) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, configFilename)); + return ts.sys.exit(5 /* CompilerOptionsErrors */); + } + var configParseResult = ts.parseConfigFile(configObject, ts.getDirectoryPath(configFilename)); + if (configParseResult.errors.length > 0) { + reportDiagnostics(configParseResult.errors); + return ts.sys.exit(5 /* CompilerOptionsErrors */); + } + rootFilenames = configParseResult.filenames; + compilerOptions = ts.extend(commandLine.options, configParseResult.options); + } + else { + rootFilenames = commandLine.filenames; + compilerOptions = commandLine.options; + } + compilerHost = ts.createCompilerHost(compilerOptions); + hostGetSourceFile = compilerHost.getSourceFile; + compilerHost.getSourceFile = getSourceFile; + } + var compileResult = compile(rootFilenames, compilerOptions, compilerHost); + if (!commandLine.options.watch) { + return ts.sys.exit(compileResult.exitStatus); + } + setCachedProgram(compileResult.program); + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes)); + } + function getSourceFile(filename, languageVersion, onError) { + if (cachedProgram) { + var sourceFile = cachedProgram.getSourceFile(filename); + if (sourceFile && sourceFile.fileWatcher) { + return sourceFile; + } + } + var sourceFile = hostGetSourceFile(filename, languageVersion, onError); + if (sourceFile && commandLine.options.watch) { + sourceFile.fileWatcher = ts.sys.watchFile(sourceFile.filename, function () { return sourceFileChanged(sourceFile); }); + } + return sourceFile; + } + function setCachedProgram(program) { + if (cachedProgram) { + var newSourceFiles = program ? program.getSourceFiles() : undefined; + ts.forEach(cachedProgram.getSourceFiles(), function (sourceFile) { + if (!(newSourceFiles && ts.contains(newSourceFiles, sourceFile))) { + if (sourceFile.fileWatcher) { + sourceFile.fileWatcher.close(); + sourceFile.fileWatcher = undefined; + } + } + }); + } + cachedProgram = program; + } + function sourceFileChanged(sourceFile) { + sourceFile.fileWatcher = undefined; + startTimer(); + } + function configFileChanged() { + setCachedProgram(undefined); + startTimer(); + } + function startTimer() { + if (timerHandle) { + clearTimeout(timerHandle); + } + timerHandle = setTimeout(recompile, 250); + } + function recompile() { + timerHandle = undefined; + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation)); + performCompilation(); } } ts.executeCommandLine = executeCommandLine; - function watchProgram(commandLine, compilerHost) { - var watchers = {}; - var updatedFiles = {}; - var program = compile(commandLine, compilerHost).program; - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes)); - addWatchers(program); - return; - function addWatchers(program) { - ts.forEach(program.getSourceFiles(), function (f) { - var filename = getCanonicalName(f.filename); - watchers[filename] = ts.sys.watchFile(filename, fileUpdated); - }); - } - function removeWatchers(program) { - ts.forEach(program.getSourceFiles(), function (f) { - var filename = getCanonicalName(f.filename); - if (ts.hasProperty(watchers, filename)) { - watchers[filename].close(); - } - }); - watchers = {}; - } - function fileUpdated(filename) { - var firstNotification = ts.isEmpty(updatedFiles); - updatedFiles[getCanonicalName(filename)] = true; - if (firstNotification) { - setTimeout(function () { - var changedFiles = updatedFiles; - updatedFiles = {}; - recompile(changedFiles); - }, 250); - } - } - function recompile(changedFiles) { - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.File_change_detected_Compiling)); - removeWatchers(program); - var oldSourceFiles = ts.arrayToMap(ts.filter(program.getSourceFiles(), function (file) { return !ts.hasProperty(changedFiles, getCanonicalName(file.filename)); }), function (file) { return getCanonicalName(file.filename); }); - var newCompilerHost = ts.clone(compilerHost); - newCompilerHost.getSourceFile = function (fileName, languageVersion, onError) { - fileName = getCanonicalName(fileName); - var sourceFile = ts.lookUp(oldSourceFiles, fileName); - if (sourceFile) { - return sourceFile; - } - return compilerHost.getSourceFile(fileName, languageVersion, onError); - }; - program = compile(commandLine, newCompilerHost).program; - reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes)); - addWatchers(program); - } - function getCanonicalName(fileName) { - return compilerHost.getCanonicalFileName(fileName); - } - } - function compile(commandLine, compilerHost) { + function compile(filenames, compilerOptions, compilerHost) { var parseStart = new Date().getTime(); - var compilerOptions = commandLine.options; - var program = ts.createProgram(commandLine.filenames, compilerOptions, compilerHost); + var program = ts.createProgram(filenames, compilerOptions, compilerHost); var bindStart = new Date().getTime(); var errors = program.getDiagnostics(); var exitStatus; @@ -19697,7 +20095,12 @@ var ts; } } reportDiagnostics(errors); - if (commandLine.options.diagnostics) { + if (compilerOptions.listFiles) { + ts.forEach(program.getSourceFiles(), function (file) { + ts.sys.write(file.filename + ts.sys.newLine); + }); + } + if (compilerOptions.diagnostics) { var memoryUsed = ts.sys.getMemoryUsage ? ts.sys.getMemoryUsage() : -1; reportCountStatistic("Files", program.getSourceFiles().length); reportCountStatistic("Lines", countLines(program)); diff --git a/bin/typescript.d.ts b/bin/typescript.d.ts index 592b73ba8d9..11f29d7624e 100644 --- a/bin/typescript.d.ts +++ b/bin/typescript.d.ts @@ -283,6 +283,11 @@ declare module "typescript" { ThisNodeOrAnySubNodesHasError = 32, HasAggregatedChildData = 64, } + const enum RelationComparisonResult { + Succeeded = 1, + Failed = 2, + FailedAndReported = 3, + } interface Node extends TextRange { kind: SyntaxKind; flags: NodeFlags; @@ -994,11 +999,15 @@ declare module "typescript" { Union = 16384, Anonymous = 32768, FromSignature = 65536, - Unwidened = 131072, + ObjectLiteral = 131072, + ContainsUndefinedOrNull = 262144, + ContainsObjectLiteral = 524288, Intrinsic = 127, + Primitive = 510, StringLike = 258, NumberLike = 132, ObjectType = 48128, + RequiresWidening = 786432, } interface Type { flags: TypeFlags; @@ -1123,6 +1132,7 @@ declare module "typescript" { diagnostics?: boolean; emitBOM?: boolean; help?: boolean; + listFiles?: boolean; locale?: string; mapRoot?: string; module?: ModuleKind; @@ -1136,6 +1146,7 @@ declare module "typescript" { out?: string; outDir?: string; preserveConstEnums?: boolean; + project?: string; removeComments?: boolean; sourceMap?: boolean; sourceRoot?: string; @@ -1168,6 +1179,7 @@ declare module "typescript" { interface CommandLineOption { name: string; type: string | Map; + isFilePath?: boolean; shortName?: string; description?: DiagnosticMessage; paramType?: DiagnosticMessage; @@ -1428,6 +1440,7 @@ declare module "typescript" { isOpen: boolean; version: string; scriptSnapshot: IScriptSnapshot; + nameTable: Map; getNamedDeclarations(): Declaration[]; } /** @@ -1470,6 +1483,7 @@ declare module "typescript" { } interface LanguageServiceHost extends Logger { getCompilationSettings(): CompilerOptions; + getNewLine?(): string; getScriptFileNames(): string[]; getScriptVersion(fileName: string): string; getScriptIsOpen(fileName: string): boolean; diff --git a/bin/typescriptServices.d.ts b/bin/typescriptServices.d.ts index 6fd1cda359a..d4fa86da1b5 100644 --- a/bin/typescriptServices.d.ts +++ b/bin/typescriptServices.d.ts @@ -283,6 +283,11 @@ declare module ts { ThisNodeOrAnySubNodesHasError = 32, HasAggregatedChildData = 64, } + const enum RelationComparisonResult { + Succeeded = 1, + Failed = 2, + FailedAndReported = 3, + } interface Node extends TextRange { kind: SyntaxKind; flags: NodeFlags; @@ -994,11 +999,15 @@ declare module ts { Union = 16384, Anonymous = 32768, FromSignature = 65536, - Unwidened = 131072, + ObjectLiteral = 131072, + ContainsUndefinedOrNull = 262144, + ContainsObjectLiteral = 524288, Intrinsic = 127, + Primitive = 510, StringLike = 258, NumberLike = 132, ObjectType = 48128, + RequiresWidening = 786432, } interface Type { flags: TypeFlags; @@ -1123,6 +1132,7 @@ declare module ts { diagnostics?: boolean; emitBOM?: boolean; help?: boolean; + listFiles?: boolean; locale?: string; mapRoot?: string; module?: ModuleKind; @@ -1136,6 +1146,7 @@ declare module ts { out?: string; outDir?: string; preserveConstEnums?: boolean; + project?: string; removeComments?: boolean; sourceMap?: boolean; sourceRoot?: string; @@ -1168,6 +1179,7 @@ declare module ts { interface CommandLineOption { name: string; type: string | Map; + isFilePath?: boolean; shortName?: string; description?: DiagnosticMessage; paramType?: DiagnosticMessage; @@ -1428,6 +1440,7 @@ declare module ts { isOpen: boolean; version: string; scriptSnapshot: IScriptSnapshot; + nameTable: Map; getNamedDeclarations(): Declaration[]; } /** @@ -1470,6 +1483,7 @@ declare module ts { } interface LanguageServiceHost extends Logger { getCompilationSettings(): CompilerOptions; + getNewLine?(): string; getScriptFileNames(): string[]; getScriptVersion(fileName: string): string; getScriptIsOpen(fileName: string): boolean; diff --git a/bin/typescriptServices.js b/bin/typescriptServices.js index c3725bdc367..0ea95acc9f6 100644 --- a/bin/typescriptServices.js +++ b/bin/typescriptServices.js @@ -280,6 +280,12 @@ var ts; ParserContextFlags[ParserContextFlags["HasAggregatedChildData"] = 64] = "HasAggregatedChildData"; })(ts.ParserContextFlags || (ts.ParserContextFlags = {})); var ParserContextFlags = ts.ParserContextFlags; + (function (RelationComparisonResult) { + RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded"; + RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; + RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; + })(ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); + var RelationComparisonResult = ts.RelationComparisonResult; (function (EmitReturnStatus) { EmitReturnStatus[EmitReturnStatus["Succeeded"] = 0] = "Succeeded"; EmitReturnStatus[EmitReturnStatus["AllOutputGenerationSkipped"] = 1] = "AllOutputGenerationSkipped"; @@ -407,11 +413,15 @@ var ts; TypeFlags[TypeFlags["Union"] = 16384] = "Union"; TypeFlags[TypeFlags["Anonymous"] = 32768] = "Anonymous"; TypeFlags[TypeFlags["FromSignature"] = 65536] = "FromSignature"; - TypeFlags[TypeFlags["Unwidened"] = 131072] = "Unwidened"; + TypeFlags[TypeFlags["ObjectLiteral"] = 131072] = "ObjectLiteral"; + TypeFlags[TypeFlags["ContainsUndefinedOrNull"] = 262144] = "ContainsUndefinedOrNull"; + TypeFlags[TypeFlags["ContainsObjectLiteral"] = 524288] = "ContainsObjectLiteral"; TypeFlags[TypeFlags["Intrinsic"] = 127] = "Intrinsic"; + TypeFlags[TypeFlags["Primitive"] = 510] = "Primitive"; TypeFlags[TypeFlags["StringLike"] = 258] = "StringLike"; TypeFlags[TypeFlags["NumberLike"] = 132] = "NumberLike"; TypeFlags[TypeFlags["ObjectType"] = 48128] = "ObjectType"; + TypeFlags[TypeFlags["RequiresWidening"] = 786432] = "RequiresWidening"; })(ts.TypeFlags || (ts.TypeFlags = {})); var TypeFlags = ts.TypeFlags; (function (SignatureKind) { @@ -733,6 +743,19 @@ var ts; return result; } ts.clone = clone; + function extend(first, second) { + var result = {}; + for (var id in first) { + result[id] = first[id]; + } + for (var id in second) { + if (!hasProperty(result, id)) { + result[id] = second[id]; + } + } + return result; + } + ts.extend = extend; function forEachValue(map, callback) { var result; for (var id in map) { @@ -1054,7 +1077,7 @@ var ts; return path2; if (!(path2 && path2.length)) return path1; - if (path2.charAt(0) === ts.directorySeparator) + if (getRootLength(path2) !== 0) return path2; if (path1.charAt(path1.length - 1) === ts.directorySeparator) return path1 + path2; @@ -1224,6 +1247,32 @@ var ts; fileStream.Close(); } } + function getNames(collection) { + var result = []; + for (var e = new Enumerator(collection); !e.atEnd(); e.moveNext()) { + result.push(e.item().Name); + } + return result.sort(); + } + function readDirectory(path, extension) { + var result = []; + visitDirectory(path); + return result; + function visitDirectory(path) { + var folder = fso.GetFolder(path || "."); + var files = getNames(folder.files); + for (var i = 0; i < files.length; i++) { + var name = files[i]; + if (!extension || ts.fileExtensionIs(name, extension)) { + result.push(ts.combinePaths(path, name)); + } + } + var subfolders = getNames(folder.subfolders); + for (var i = 0; i < subfolders.length; i++) { + visitDirectory(ts.combinePaths(path, subfolders[i])); + } + } + } return { args: args, newLine: "\r\n", @@ -1253,6 +1302,7 @@ var ts; getCurrentDirectory: function () { return new ActiveXObject("WScript.Shell").CurrentDirectory; }, + readDirectory: readDirectory, exit: function (exitCode) { try { WScript.Quit(exitCode); @@ -1297,6 +1347,30 @@ var ts; } _fs.writeFileSync(fileName, data, "utf8"); } + function readDirectory(path, extension) { + var result = []; + visitDirectory(path); + return result; + function visitDirectory(path) { + var files = _fs.readdirSync(path || ".").sort(); + var directories = []; + for (var i = 0; i < files.length; i++) { + var name = ts.combinePaths(path, files[i]); + var stat = _fs.lstatSync(name); + if (stat.isFile()) { + if (!extension || ts.fileExtensionIs(name, extension)) { + result.push(name); + } + } + else if (stat.isDirectory()) { + directories.push(name); + } + } + for (var i = 0; i < directories.length; i++) { + visitDirectory(directories[i]); + } + } + } return { args: process.argv.slice(2), newLine: _os.EOL, @@ -1341,6 +1415,7 @@ var ts; getCurrentDirectory: function () { return process.cwd(); }, + readDirectory: readDirectory, getMemoryUsage: function () { if (global.gc) { global.gc(); @@ -1510,6 +1585,7 @@ var ts; Modifiers_cannot_appear_here: { code: 1184, category: 1 /* Error */, key: "Modifiers cannot appear here." }, Merge_conflict_marker_encountered: { code: 1185, category: 1 /* Error */, key: "Merge conflict marker encountered." }, A_rest_element_cannot_have_an_initializer: { code: 1186, category: 1 /* Error */, key: "A rest element cannot have an initializer." }, + A_parameter_property_may_not_be_a_binding_pattern: { code: 1187, category: 1 /* Error */, key: "A parameter property may not be a binding pattern." }, Duplicate_identifier_0: { code: 2300, category: 1 /* Error */, key: "Duplicate identifier '{0}'." }, Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: 1 /* Error */, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." }, Static_members_cannot_reference_class_type_parameters: { code: 2302, category: 1 /* Error */, key: "Static members cannot reference class type parameters." }, @@ -1661,6 +1737,11 @@ var ts; Type_0_has_no_property_1: { code: 2460, category: 1 /* Error */, key: "Type '{0}' has no property '{1}'." }, Type_0_is_not_an_array_type: { code: 2461, category: 1 /* Error */, key: "Type '{0}' is not an array type." }, A_rest_element_must_be_last_in_an_array_destructuring_pattern: { code: 2462, category: 1 /* Error */, key: "A rest element must be last in an array destructuring pattern" }, + A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature: { code: 2463, category: 1 /* Error */, key: "A binding pattern parameter cannot be optional in an implementation signature." }, + A_computed_property_name_must_be_of_type_string_number_or_any: { code: 2464, category: 1 /* Error */, key: "A computed property name must be of type 'string', 'number', or 'any'." }, + this_cannot_be_referenced_in_a_computed_property_name: { code: 2465, category: 1 /* Error */, key: "'this' cannot be referenced in a computed property name." }, + super_cannot_be_referenced_in_a_computed_property_name: { code: 2466, category: 1 /* Error */, key: "'super' cannot be referenced in a computed property name." }, + A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type: { code: 2466, category: 1 /* Error */, key: "A computed property name cannot reference a type parameter from its containing type." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: 1 /* Error */, key: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: 1 /* Error */, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: 1 /* Error */, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -1733,19 +1814,22 @@ var ts; Enum_declarations_must_all_be_const_or_non_const: { code: 4082, category: 1 /* Error */, key: "Enum declarations must all be const or non-const." }, In_const_enum_declarations_member_initializer_must_be_constant_expression: { code: 4083, category: 1 /* 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: 1 /* 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: 1 /* Error */, key: "Index expression arguments in 'const' enums must be of type 'string'." }, + A_const_enum_member_can_only_be_accessed_using_a_string_literal: { code: 4085, category: 1 /* Error */, key: "A const enum member can only be accessed using a string literal.", isEarly: true }, const_enum_member_initializer_was_evaluated_to_a_non_finite_value: { code: 4086, category: 1 /* 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: 1 /* Error */, key: "'const' enum member initializer was evaluated to disallowed value 'NaN'." }, + Property_0_does_not_exist_on_const_enum_1: { code: 4088, category: 1 /* Error */, key: "Property '{0}' does not exist on 'const' enum '{1}'.", isEarly: true }, The_current_host_does_not_support_the_0_option: { code: 5001, category: 1 /* Error */, key: "The current host does not support the '{0}' option." }, Cannot_find_the_common_subdirectory_path_for_the_input_files: { code: 5009, category: 1 /* Error */, key: "Cannot find the common subdirectory path for the input files." }, Cannot_read_file_0_Colon_1: { code: 5012, category: 1 /* Error */, key: "Cannot read file '{0}': {1}" }, Unsupported_file_encoding: { code: 5013, category: 1 /* Error */, key: "Unsupported file encoding." }, Unknown_compiler_option_0: { code: 5023, category: 1 /* Error */, key: "Unknown compiler option '{0}'." }, + Compiler_option_0_requires_a_value_of_type_1: { code: 5024, category: 1 /* Error */, key: "Compiler option '{0}' requires a value of type {1}." }, Could_not_write_file_0_Colon_1: { code: 5033, category: 1 /* Error */, key: "Could not write file '{0}': {1}" }, - Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5038, category: 1 /* Error */, key: "Option mapRoot cannot be specified without specifying sourcemap option." }, - Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5039, category: 1 /* Error */, key: "Option sourceRoot cannot be specified without specifying sourcemap option." }, - Option_noEmit_cannot_be_specified_with_option_out_or_outDir: { code: 5040, category: 1 /* Error */, key: "Option noEmit cannot be specified with option out or outDir." }, - Option_noEmit_cannot_be_specified_with_option_declaration: { code: 5041, category: 1 /* Error */, key: "Option noEmit cannot be specified with option declaration." }, + Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5038, category: 1 /* Error */, key: "Option 'mapRoot' cannot be specified without specifying 'sourcemap' option." }, + Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5039, category: 1 /* Error */, key: "Option 'sourceRoot' cannot be specified without specifying 'sourcemap' option." }, + Option_noEmit_cannot_be_specified_with_option_out_or_outDir: { code: 5040, category: 1 /* Error */, key: "Option 'noEmit' cannot be specified with option 'out' or 'outDir'." }, + Option_noEmit_cannot_be_specified_with_option_declaration: { code: 5041, category: 1 /* Error */, key: "Option 'noEmit' cannot be specified with option 'declaration'." }, + Option_project_cannot_be_mixed_with_source_files_on_a_command_line: { code: 5042, category: 1 /* Error */, key: "Option 'project' cannot be mixed with source files on a command line." }, Concatenate_and_emit_output_to_single_file: { code: 6001, category: 2 /* Message */, key: "Concatenate and emit output to single file." }, Generates_corresponding_d_ts_file: { code: 6002, category: 2 /* Message */, key: "Generates corresponding '.d.ts' file." }, Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: 2 /* Message */, key: "Specifies the location where debugger should locate map files instead of generated locations." }, @@ -1760,6 +1844,7 @@ var ts; Specify_module_code_generation_Colon_commonjs_or_amd: { code: 6016, category: 2 /* Message */, key: "Specify module code generation: 'commonjs' or 'amd'" }, Print_this_message: { code: 6017, category: 2 /* Message */, key: "Print this message." }, Print_the_compiler_s_version: { code: 6019, category: 2 /* Message */, key: "Print the compiler's version." }, + Compile_the_project_in_the_given_directory: { code: 6020, category: 2 /* Message */, key: "Compile the project in the given directory." }, Syntax_Colon_0: { code: 6023, category: 2 /* Message */, key: "Syntax: {0}" }, options: { code: 6024, category: 2 /* Message */, key: "options" }, file: { code: 6025, category: 2 /* Message */, key: "file" }, @@ -1767,7 +1852,7 @@ var ts; Options_Colon: { code: 6027, category: 2 /* Message */, key: "Options:" }, Version_0: { code: 6029, category: 2 /* Message */, key: "Version {0}" }, Insert_command_line_options_and_files_from_a_file: { code: 6030, category: 2 /* Message */, key: "Insert command line options and files from a file." }, - File_change_detected_Compiling: { code: 6032, category: 2 /* Message */, key: "File change detected. Compiling..." }, + File_change_detected_Starting_incremental_compilation: { code: 6032, category: 2 /* Message */, key: "File change detected. Starting incremental compilation..." }, KIND: { code: 6034, category: 2 /* Message */, key: "KIND" }, FILE: { code: 6035, category: 2 /* Message */, key: "FILE" }, VERSION: { code: 6036, category: 2 /* Message */, key: "VERSION" }, @@ -1783,7 +1868,7 @@ var ts; Unsupported_locale_0: { code: 6049, category: 1 /* Error */, key: "Unsupported locale '{0}'." }, Unable_to_open_file_0: { code: 6050, category: 1 /* Error */, key: "Unable to open file '{0}'." }, Corrupted_locale_file_0: { code: 6051, category: 1 /* Error */, key: "Corrupted locale file {0}." }, - Raise_error_on_expressions_and_declarations_with_an_implied_any_type: { code: 6052, category: 2 /* Message */, key: "Warn on expressions and declarations with an implied 'any' type." }, + Raise_error_on_expressions_and_declarations_with_an_implied_any_type: { code: 6052, category: 2 /* Message */, key: "Raise error on expressions and declarations with an implied 'any' type." }, File_0_not_found: { code: 6053, category: 1 /* Error */, key: "File '{0}' not found." }, File_0_must_have_extension_ts_or_d_ts: { code: 6054, category: 1 /* Error */, key: "File '{0}' must have extension '.ts' or '.d.ts'." }, Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: { code: 6055, category: 2 /* Message */, key: "Suppress noImplicitAny errors for indexing objects lacking index signatures." }, @@ -1805,8 +1890,7 @@ var ts; 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: { code: 7024, category: 1 /* Error */, key: "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." }, You_cannot_rename_this_element: { code: 8000, category: 1 /* Error */, key: "You cannot rename this element." }, yield_expressions_are_not_currently_supported: { code: 9000, category: 1 /* Error */, key: "'yield' expressions are not currently supported.", isEarly: true }, - Generators_are_not_currently_supported: { code: 9001, category: 1 /* Error */, key: "Generators are not currently supported.", isEarly: true }, - Computed_property_names_are_not_currently_supported: { code: 9002, category: 1 /* Error */, key: "Computed property names are not currently supported.", isEarly: true } + Generators_are_not_currently_supported: { code: 9001, category: 1 /* Error */, key: "Generators are not currently supported.", isEarly: true } }; })(ts || (ts = {})); var ts; @@ -1946,10 +2030,10 @@ var ts; return false; } function isUnicodeIdentifierStart(code, languageVersion) { - return languageVersion === 0 /* ES3 */ ? lookupInUnicodeMap(code, unicodeES3IdentifierStart) : lookupInUnicodeMap(code, unicodeES5IdentifierStart); + return languageVersion >= 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) : lookupInUnicodeMap(code, unicodeES3IdentifierStart); } function isUnicodeIdentifierPart(code, languageVersion) { - return languageVersion === 0 /* ES3 */ ? lookupInUnicodeMap(code, unicodeES3IdentifierPart) : lookupInUnicodeMap(code, unicodeES5IdentifierPart); + return languageVersion >= 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) : lookupInUnicodeMap(code, unicodeES3IdentifierPart); } function makeReverseMap(source) { var result = []; @@ -1993,7 +2077,7 @@ var ts; } ts.computeLineStarts = computeLineStarts; function getPositionFromLineAndCharacter(lineStarts, line, character) { - ts.Debug.assert(line > 0); + ts.Debug.assert(line > 0 && line <= lineStarts.length); return lineStarts[line - 1] + character - 1; } ts.getPositionFromLineAndCharacter = getPositionFromLineAndCharacter; @@ -2657,7 +2741,7 @@ var ts; value = 0; } tokenValue = "" + value; - return 7 /* NumericLiteral */; + return token = 7 /* NumericLiteral */; } else if (pos + 2 < len && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) { pos += 2; @@ -2667,7 +2751,7 @@ var ts; value = 0; } tokenValue = "" + value; - return 7 /* NumericLiteral */; + return token = 7 /* NumericLiteral */; } if (pos + 1 < len && isOctalDigit(text.charCodeAt(pos + 1))) { tokenValue = "" + scanOctalDigits(); @@ -3225,6 +3309,12 @@ var ts; return undefined; } switch (node.kind) { + case 122 /* ComputedPropertyName */: + if (node.parent.parent.kind === 191 /* ClassDeclaration */) { + return node; + } + node = node.parent; + break; case 157 /* ArrowFunction */: if (!includeArrowFunctions) { continue; @@ -3246,13 +3336,24 @@ var ts; } } ts.getThisContainer = getThisContainer; - function getSuperContainer(node) { + function getSuperContainer(node, includeFunctions) { while (true) { node = node.parent; - if (!node) { - return undefined; - } + if (!node) + return node; switch (node.kind) { + case 122 /* ComputedPropertyName */: + if (node.parent.parent.kind === 191 /* ClassDeclaration */) { + return node; + } + node = node.parent; + break; + case 190 /* FunctionDeclaration */: + case 156 /* FunctionExpression */: + case 157 /* ArrowFunction */: + if (!includeFunctions) { + continue; + } case 126 /* PropertyDeclaration */: case 125 /* PropertySignature */: case 128 /* MethodDeclaration */: @@ -3345,6 +3446,8 @@ var ts; return node === parent.expression; case 169 /* TemplateSpan */: return node === parent.expression; + case 122 /* ComputedPropertyName */: + return node === parent.expression; default: if (isExpression(parent)) { return true; @@ -4563,7 +4666,7 @@ var ts; return canFollowModifier(); } function canFollowModifier() { - return token === 18 /* OpenBracketToken */ || token === 35 /* AsteriskToken */ || isLiteralPropertyName(); + return token === 18 /* OpenBracketToken */ || token === 14 /* OpenBraceToken */ || token === 35 /* AsteriskToken */ || isLiteralPropertyName(); } function isListElement(parsingContext, inErrorRecovery) { var node = currentNode(parsingContext); @@ -6892,7 +6995,7 @@ var ts; })(ts.ModuleInstanceState || (ts.ModuleInstanceState = {})); var ModuleInstanceState = ts.ModuleInstanceState; function getModuleInstanceState(node) { - if (node.kind === 192 /* InterfaceDeclaration */) { + if (node.kind === 192 /* InterfaceDeclaration */ || node.kind === 193 /* TypeAliasDeclaration */) { return 0 /* NonInstantiated */; } else if (ts.isConstEnumDeclaration(node)) { @@ -6925,10 +7028,10 @@ var ts; } } ts.getModuleInstanceState = getModuleInstanceState; - function hasComputedNameButNotSymbol(declaration) { + function hasDynamicName(declaration) { return declaration.name && declaration.name.kind === 122 /* ComputedPropertyName */; } - ts.hasComputedNameButNotSymbol = hasComputedNameButNotSymbol; + ts.hasDynamicName = hasDynamicName; function bindSourceFile(file) { var parent; var container; @@ -6964,7 +7067,7 @@ var ts; if (node.kind === 195 /* ModuleDeclaration */ && node.name.kind === 8 /* StringLiteral */) { return '"' + node.name.text + '"'; } - ts.Debug.assert(!hasComputedNameButNotSymbol(node)); + ts.Debug.assert(!hasDynamicName(node)); return node.name.text; } switch (node.kind) { @@ -6984,9 +7087,7 @@ var ts; return node.name ? ts.declarationNameToString(node.name) : getDeclarationName(node); } function declareSymbol(symbols, parent, node, includes, excludes) { - if (hasComputedNameButNotSymbol(node)) { - return undefined; - } + ts.Debug.assert(!hasDynamicName(node)); var name = getDeclarationName(node); if (name !== undefined) { var symbol = ts.hasProperty(symbols, name) ? symbols[name] : (symbols[name] = createSymbol(0, name)); @@ -7205,14 +7306,14 @@ var ts; break; case 126 /* PropertyDeclaration */: case 125 /* PropertySignature */: - bindDeclaration(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0), 107455 /* PropertyExcludes */, false); + bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 536870912 /* Optional */ : 0), 107455 /* PropertyExcludes */, false); break; case 204 /* PropertyAssignment */: case 205 /* ShorthandPropertyAssignment */: - bindDeclaration(node, 4 /* Property */, 107455 /* PropertyExcludes */, false); + bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 107455 /* PropertyExcludes */, false); break; case 206 /* EnumMember */: - bindDeclaration(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */, false); + bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 107455 /* EnumMemberExcludes */, false); break; case 132 /* CallSignature */: case 133 /* ConstructSignature */: @@ -7221,7 +7322,7 @@ var ts; break; case 128 /* MethodDeclaration */: case 127 /* MethodSignature */: - bindDeclaration(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */, true); + bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 536870912 /* Optional */ : 0), ts.isObjectLiteralMethod(node) ? 107455 /* PropertyExcludes */ : 99263 /* MethodExcludes */, true); break; case 190 /* FunctionDeclaration */: bindDeclaration(node, 16 /* Function */, 106927 /* FunctionExcludes */, true); @@ -7230,10 +7331,10 @@ var ts; bindDeclaration(node, 16384 /* Constructor */, 0, true); break; case 130 /* GetAccessor */: - bindDeclaration(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */, true); + bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 41919 /* GetAccessorExcludes */, true); break; case 131 /* SetAccessor */: - bindDeclaration(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */, true); + bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 74687 /* SetAccessorExcludes */, true); break; case 136 /* FunctionType */: case 137 /* ConstructorType */: @@ -7306,6 +7407,14 @@ var ts; declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */, 107455 /* PropertyExcludes */); } } + function bindPropertyOrMethodOrAccessor(node, symbolKind, symbolExcludes, isBlockScopeContainer) { + if (hasDynamicName(node)) { + bindAnonymousDeclaration(node, symbolKind, "__computed", isBlockScopeContainer); + } + else { + bindDeclaration(node, symbolKind, symbolExcludes, isBlockScopeContainer); + } + } } ts.bindSourceFile = bindSourceFile; })(ts || (ts = {})); @@ -7322,6 +7431,7 @@ var ts; var emptyArray = []; var emptySymbols = {}; var compilerOptions = host.getCompilerOptions(); + var languageVersion = compilerOptions.target || 0 /* ES3 */; var emitResolver = createResolver(); var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, @@ -7367,8 +7477,8 @@ var ts; var numberType = createIntrinsicType(4 /* Number */, "number"); var booleanType = createIntrinsicType(8 /* Boolean */, "boolean"); var voidType = createIntrinsicType(16 /* Void */, "void"); - var undefinedType = createIntrinsicType(32 /* Undefined */ | 131072 /* Unwidened */, "undefined"); - var nullType = createIntrinsicType(64 /* Null */ | 131072 /* Unwidened */, "null"); + var undefinedType = createIntrinsicType(32 /* Undefined */ | 262144 /* ContainsUndefinedOrNull */, "undefined"); + var nullType = createIntrinsicType(64 /* Null */ | 262144 /* ContainsUndefinedOrNull */, "null"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); var resolvingType = createIntrinsicType(1 /* Any */, "__resolving__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -7398,6 +7508,20 @@ var ts; var potentialThisCollisions = []; var diagnostics = []; var diagnosticsModified = false; + var primitiveTypeInfo = { + "string": { + type: stringType, + flags: 258 /* StringLike */ + }, + "number": { + type: numberType, + flags: 132 /* NumberLike */ + }, + "boolean": { + type: booleanType, + flags: 8 /* Boolean */ + } + }; function addDiagnostic(diagnostic) { diagnostics.push(diagnostic); diagnosticsModified = true; @@ -7614,6 +7738,15 @@ var ts; break loop; } break; + case 122 /* ComputedPropertyName */: + var grandparent = location.parent.parent; + if (grandparent.kind === 191 /* ClassDeclaration */ || grandparent.kind === 192 /* InterfaceDeclaration */) { + if (result = getSymbol(getSymbolOfNode(grandparent).members, name, meaning & 793056 /* Type */)) { + error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type); + return undefined; + } + } + break; case 128 /* MethodDeclaration */: case 127 /* MethodSignature */: case 129 /* Constructor */: @@ -8648,7 +8781,7 @@ var ts; } if (pattern.kind === 144 /* ObjectBindingPattern */) { var name = declaration.propertyName || declaration.name; - var type = getTypeOfPropertyOfType(parentType, name.text) || isNumericName(name.text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); + var type = getTypeOfPropertyOfType(parentType, name.text) || isNumericLiteralName(name.text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); if (!type) { error(name, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name)); return unknownType; @@ -8685,7 +8818,7 @@ var ts; } if (declaration.kind === 124 /* Parameter */) { var func = declaration.parent; - if (func.kind === 131 /* SetAccessor */ && !ts.hasComputedNameButNotSymbol(func)) { + if (func.kind === 131 /* SetAccessor */ && !ts.hasDynamicName(func)) { var getter = ts.getDeclarationOfKind(declaration.parent.symbol, 130 /* GetAccessor */); if (getter) { return getReturnTypeOfSignature(getSignatureFromDeclaration(getter)); @@ -9466,7 +9599,7 @@ var ts; returnType = getTypeFromTypeNode(declaration.type); } else { - if (declaration.kind === 130 /* GetAccessor */ && !ts.hasComputedNameButNotSymbol(declaration)) { + if (declaration.kind === 130 /* GetAccessor */ && !ts.hasDynamicName(declaration)) { var setter = ts.getDeclarationOfKind(declaration.symbol, 131 /* SetAccessor */); returnType = getAnnotatedAccessorType(setter); } @@ -9628,14 +9761,18 @@ var ts; return result; } } - function getUnwidenedFlagOfTypes(types) { - return ts.forEach(types, function (t) { return t.flags & 131072 /* Unwidened */; }) || 0; + function getWideningFlagsOfTypes(types) { + var result = 0; + for (var i = 0; i < types.length; i++) { + result |= types[i].flags; + } + return result & 786432 /* RequiresWidening */; } function createTypeReference(target, typeArguments) { var id = getTypeListId(typeArguments); var type = target.instantiations[id]; if (!type) { - var flags = 4096 /* Reference */ | getUnwidenedFlagOfTypes(typeArguments); + var flags = 4096 /* Reference */ | getWideningFlagsOfTypes(typeArguments); type = target.instantiations[id] = createObjectType(flags, target.symbol); type.target = target; type.typeArguments = typeArguments; @@ -9852,7 +9989,7 @@ var ts; var id = getTypeListId(sortedTypes); var type = unionTypes[id]; if (!type) { - type = unionTypes[id] = createObjectType(16384 /* Union */ | getUnwidenedFlagOfTypes(sortedTypes)); + type = unionTypes[id] = createObjectType(16384 /* Union */ | getWideningFlagsOfTypes(sortedTypes)); type.types = sortedTypes; } return type; @@ -10079,6 +10216,8 @@ var ts; case 128 /* MethodDeclaration */: case 127 /* MethodSignature */: return isContextSensitiveFunctionLikeDeclaration(node); + case 155 /* ParenthesizedExpression */: + return isContextSensitive(node.expression); } return false; } @@ -10139,6 +10278,10 @@ var ts; error(errorNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target)); } else if (errorInfo) { + if (errorInfo.next === undefined) { + errorInfo = undefined; + isRelatedTo(source, target, errorNode !== undefined, headMessage, true); + } if (containingMessageChain) { errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); } @@ -10148,7 +10291,8 @@ var ts; function reportError(message, arg0, arg1, arg2) { errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2); } - function isRelatedTo(source, target, reportErrors, headMessage) { + function isRelatedTo(source, target, reportErrors, headMessage, elaborateErrors) { + if (elaborateErrors === void 0) { elaborateErrors = false; } var result; if (source === target) return -1 /* True */; @@ -10217,7 +10361,7 @@ var ts; } var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo; var sourceOrApparentType = relation === identityRelation ? source : getApparentType(source); - if (sourceOrApparentType.flags & 48128 /* ObjectType */ && target.flags & 48128 /* ObjectType */ && (result = objectTypeRelatedTo(sourceOrApparentType, target, reportStructuralErrors))) { + if (sourceOrApparentType.flags & 48128 /* ObjectType */ && target.flags & 48128 /* ObjectType */ && (result = objectTypeRelatedTo(sourceOrApparentType, target, reportStructuralErrors, elaborateErrors))) { errorInfo = saveErrorInfo; return result; } @@ -10298,14 +10442,17 @@ var ts; return 0 /* False */; } } - function objectTypeRelatedTo(source, target, reportErrors) { + function objectTypeRelatedTo(source, target, reportErrors, elaborateErrors) { + if (elaborateErrors === void 0) { elaborateErrors = false; } if (overflow) { return 0 /* False */; } var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id; var related = relation[id]; if (related !== undefined) { - return related ? -1 /* True */ : 0 /* False */; + if (!elaborateErrors || (related === 3 /* FailedAndReported */)) { + return related === 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */; + } } if (depth > 0) { for (var i = 0; i < depth; i++) { @@ -10327,7 +10474,7 @@ var ts; sourceStack[depth] = source; targetStack[depth] = target; maybeStack[depth] = {}; - maybeStack[depth][id] = true; + maybeStack[depth][id] = 1 /* Succeeded */; depth++; var saveExpandingFlags = expandingFlags; if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack)) @@ -10356,11 +10503,11 @@ var ts; depth--; if (result) { var maybeCache = maybeStack[depth]; - var destinationCache = result === -1 /* True */ || depth === 0 ? relation : maybeStack[depth - 1]; + var destinationCache = (result === -1 /* True */ || depth === 0) ? relation : maybeStack[depth - 1]; ts.copyMap(maybeCache, destinationCache); } else { - relation[id] = false; + relation[id] = reportErrors ? 3 /* FailedAndReported */ : 2 /* Failed */; } return result; } @@ -10385,12 +10532,13 @@ var ts; } var result = -1 /* True */; var properties = getPropertiesOfObjectType(target); + var requireOptionalProperties = relation === subtypeRelation && !(source.flags & 131072 /* ObjectLiteral */); for (var i = 0; i < properties.length; i++) { var targetProp = properties[i]; var sourceProp = getPropertyOfType(source, targetProp.name); if (sourceProp !== targetProp) { if (!sourceProp) { - if (relation === subtypeRelation || !(targetProp.flags & 536870912 /* Optional */)) { + if (!(targetProp.flags & 536870912 /* Optional */) || requireOptionalProperties) { if (reportErrors) { reportError(ts.Diagnostics.Property_0_is_missing_in_type_1, symbolToString(targetProp), typeToString(source)); } @@ -10735,9 +10883,6 @@ var ts; } checkTypeSubtypeOf(bestSupertypeDownfallType, bestSupertype, errorLocation, ts.Diagnostics.Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0, errorMessageChainHead); } - function isTypeOfObjectLiteral(type) { - return (type.flags & 32768 /* Anonymous */) && type.symbol && (type.symbol.flags & 4096 /* ObjectLiteral */) ? true : false; - } function isArrayType(type) { return type.flags & 4096 /* Reference */ && type.target === globalArrayType; } @@ -10748,14 +10893,19 @@ var ts; var properties = getPropertiesOfObjectType(type); var members = {}; ts.forEach(properties, function (p) { - var symbol = createSymbol(p.flags | 67108864 /* Transient */, p.name); - symbol.declarations = p.declarations; - symbol.parent = p.parent; - symbol.type = getWidenedType(getTypeOfSymbol(p)); - symbol.target = p; - if (p.valueDeclaration) - symbol.valueDeclaration = p.valueDeclaration; - members[symbol.name] = symbol; + var propType = getTypeOfSymbol(p); + var widenedType = getWidenedType(propType); + if (propType !== widenedType) { + var symbol = createSymbol(p.flags | 67108864 /* Transient */, p.name); + symbol.declarations = p.declarations; + symbol.parent = p.parent; + symbol.type = widenedType; + symbol.target = p; + if (p.valueDeclaration) + symbol.valueDeclaration = p.valueDeclaration; + p = symbol; + } + members[p.name] = p; }); var stringIndexType = getIndexTypeOfType(type, 0 /* String */); var numberIndexType = getIndexTypeOfType(type, 1 /* Number */); @@ -10766,16 +10916,16 @@ var ts; return createAnonymousType(type.symbol, members, emptyArray, emptyArray, stringIndexType, numberIndexType); } function getWidenedType(type) { - if (type.flags & 131072 /* Unwidened */) { + if (type.flags & 786432 /* RequiresWidening */) { if (type.flags & (32 /* Undefined */ | 64 /* Null */)) { return anyType; } + if (type.flags & 131072 /* ObjectLiteral */) { + return getWidenedTypeOfObjectLiteral(type); + } if (type.flags & 16384 /* Union */) { return getUnionType(ts.map(type.types, getWidenedType)); } - if (isTypeOfObjectLiteral(type)) { - return getWidenedTypeOfObjectLiteral(type); - } if (isArrayType(type)) { return createArrayType(getWidenedType(type.typeArguments[0])); } @@ -10795,11 +10945,11 @@ var ts; if (isArrayType(type)) { return reportWideningErrorsInType(type.typeArguments[0]); } - if (isTypeOfObjectLiteral(type)) { + if (type.flags & 131072 /* ObjectLiteral */) { var errorReported = false; ts.forEach(getPropertiesOfObjectType(type), function (p) { var t = getTypeOfSymbol(p); - if (t.flags & 131072 /* Unwidened */) { + if (t.flags & 262144 /* ContainsUndefinedOrNull */) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, p.name, typeToString(getWidenedType(t))); } @@ -10839,7 +10989,7 @@ var ts; error(declaration, diagnostic, ts.declarationNameToString(declaration.name), typeAsString); } function reportErrorsFromWidening(declaration, type) { - if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 131072 /* Unwidened */) { + if (produceDiagnostics && compilerOptions.noImplicitAny && type.flags & 262144 /* ContainsUndefinedOrNull */) { if (!reportWideningErrorsInType(type)) { reportImplicitAnyError(declaration, type); } @@ -11063,11 +11213,14 @@ var ts; } ts.Debug.fail("should not get here"); } - function subtractPrimitiveTypes(type, subtractMask) { + function removeTypesFromUnionType(type, typeKind, isOfTypeKind) { if (type.flags & 16384 /* Union */) { var types = type.types; - if (ts.forEach(types, function (t) { return t.flags & subtractMask; })) { - return getUnionType(ts.filter(types, function (t) { return !(t.flags & subtractMask); })); + if (ts.forEach(types, function (t) { return !!(t.flags & typeKind) === isOfTypeKind; })) { + var narrowedType = getUnionType(ts.filter(types, function (t) { return !(t.flags & typeKind) === isOfTypeKind; })); + if (narrowedType !== emptyObjectType) { + return narrowedType; + } } } return type; @@ -11212,7 +11365,7 @@ var ts; case 129 /* Constructor */: break loop; } - if (narrowedType !== type && isTypeSubtypeOf(narrowedType, type)) { + if (narrowedType !== type) { if (isVariableAssignedWithin(symbol, node)) { break; } @@ -11230,16 +11383,24 @@ var ts; if (left.expression.kind !== 64 /* Identifier */ || getResolvedSymbol(left.expression) !== symbol) { return type; } - var t = right.text; - var checkType = t === "string" ? stringType : t === "number" ? numberType : t === "boolean" ? booleanType : emptyObjectType; + var typeInfo = primitiveTypeInfo[right.text]; if (expr.operator === 31 /* ExclamationEqualsEqualsToken */) { assumeTrue = !assumeTrue; } if (assumeTrue) { - return checkType === emptyObjectType ? subtractPrimitiveTypes(type, 2 /* String */ | 4 /* Number */ | 8 /* Boolean */) : checkType; + if (!typeInfo) { + return removeTypesFromUnionType(type, 258 /* StringLike */ | 132 /* NumberLike */ | 8 /* Boolean */, true); + } + if (isTypeSubtypeOf(typeInfo.type, type)) { + return typeInfo.type; + } + return removeTypesFromUnionType(type, typeInfo.flags, false); } else { - return checkType === emptyObjectType ? type : subtractPrimitiveTypes(type, checkType.flags); + if (typeInfo) { + return removeTypesFromUnionType(type, typeInfo.flags, true); + } + return type; } } function narrowTypeByAnd(type, expr, assumeTrue) { @@ -11276,8 +11437,14 @@ var ts; if (!prototypeProperty) { return type; } - var prototypeType = getTypeOfSymbol(prototypeProperty); - return isTypeSubtypeOf(prototypeType, type) ? prototypeType : type; + var targetType = getTypeOfSymbol(prototypeProperty); + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + if (type.flags & 16384 /* Union */) { + return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, targetType); })); + } + return type; } function narrowType(type, expr, assumeTrue) { switch (expr.kind) { @@ -11375,6 +11542,9 @@ var ts; error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer); } break; + case 122 /* ComputedPropertyName */: + error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name); + break; } if (needToCaptureLexicalThis) { captureLexicalThis(node, container); @@ -11386,26 +11556,6 @@ var ts; } return anyType; } - function getSuperContainer(node) { - while (true) { - node = node.parent; - if (!node) - return node; - switch (node.kind) { - case 190 /* FunctionDeclaration */: - case 156 /* FunctionExpression */: - case 157 /* ArrowFunction */: - case 126 /* PropertyDeclaration */: - case 125 /* PropertySignature */: - case 128 /* MethodDeclaration */: - case 127 /* MethodSignature */: - case 129 /* Constructor */: - case 130 /* GetAccessor */: - case 131 /* SetAccessor */: - return node; - } - } - } function isInConstructorArgumentInitializer(node, constructorDecl) { for (var n = node; n && n !== constructorDecl; n = n.parent) { if (n.kind === 124 /* Parameter */) { @@ -11426,7 +11576,7 @@ var ts; error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class); return unknownType; } - var container = getSuperContainer(node); + var container = ts.getSuperContainer(node, true); if (container) { var canUseSuperExpression = false; if (isCallExpression) { @@ -11435,7 +11585,7 @@ var ts; else { var needToCaptureLexicalThis = false; while (container && container.kind === 157 /* ArrowFunction */) { - container = getSuperContainer(container); + container = ts.getSuperContainer(container, true); needToCaptureLexicalThis = true; } if (container && container.parent && container.parent.kind === 191 /* ClassDeclaration */) { @@ -11467,7 +11617,10 @@ var ts; return returnType; } } - if (isCallExpression) { + if (container.kind === 122 /* ComputedPropertyName */) { + error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name); + } + else if (isCallExpression) { error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors); } else { @@ -11606,9 +11759,15 @@ var ts; function getContextualTypeForObjectLiteralElement(element) { var objectLiteral = element.parent; var type = getContextualType(objectLiteral); - var name = element.name.text; - if (type && name) { - return getTypeOfPropertyOfContextualType(type, name) || isNumericName(name) && getIndexTypeOfContextualType(type, 1 /* Number */) || getIndexTypeOfContextualType(type, 0 /* String */); + if (type) { + if (!ts.hasDynamicName(element)) { + var symbolName = getSymbolOfNode(element).name; + var propertyType = getTypeOfPropertyOfContextualType(type, symbolName); + if (propertyType) { + return propertyType; + } + } + return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) || getIndexTypeOfContextualType(type, 0 /* String */); } return undefined; } @@ -11659,6 +11818,8 @@ var ts; case 169 /* TemplateSpan */: ts.Debug.assert(parent.parent.kind === 165 /* TemplateExpression */); return getContextualTypeForSubstitutionExpression(parent.parent, node); + case 155 /* ParenthesizedExpression */: + return getContextualType(parent); } return undefined; } @@ -11763,72 +11924,84 @@ var ts; return createArrayType(getUnionType(elementTypes)); } function isNumericName(name) { + return name.kind === 122 /* ComputedPropertyName */ ? isNumericComputedName(name) : isNumericLiteralName(name.text); + } + function isNumericComputedName(name) { + return isTypeOfKind(checkComputedPropertyName(name), 1 /* Any */ | 132 /* NumberLike */); + } + function isNumericLiteralName(name) { return (+name).toString() === name; } + function checkComputedPropertyName(node) { + var links = getNodeLinks(node.expression); + if (!links.resolvedType) { + links.resolvedType = checkExpression(node.expression); + if (!isTypeOfKind(links.resolvedType, 1 /* Any */ | 132 /* NumberLike */ | 258 /* StringLike */)) { + error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_or_any); + } + } + return links.resolvedType; + } function checkObjectLiteral(node, contextualMapper) { checkGrammarObjectLiteralExpression(node); - var members = node.symbol.members; - var properties = {}; + var propertiesTable = {}; + var propertiesArray = []; var contextualType = getContextualType(node); var typeFlags; - for (var id in members) { - if (ts.hasProperty(members, id)) { - var member = members[id]; - if (member.flags & 4 /* Property */ || ts.isObjectLiteralMethod(member.declarations[0])) { - var memberDecl = member.declarations[0]; - if (memberDecl.kind === 204 /* PropertyAssignment */) { - var type = checkExpression(memberDecl.initializer, contextualMapper); - } - else if (memberDecl.kind === 128 /* MethodDeclaration */) { - var type = checkObjectLiteralMethod(memberDecl, contextualMapper); - } - else { - ts.Debug.assert(memberDecl.kind === 205 /* ShorthandPropertyAssignment */); - var type = memberDecl.name.kind === 122 /* ComputedPropertyName */ ? unknownType : checkExpression(memberDecl.name, contextualMapper); - } - typeFlags |= type.flags; - var prop = createSymbol(4 /* Property */ | 67108864 /* Transient */ | member.flags, member.name); - prop.declarations = member.declarations; - prop.parent = member.parent; - if (member.valueDeclaration) { - prop.valueDeclaration = member.valueDeclaration; - } - prop.type = type; - prop.target = member; - member = prop; + for (var i = 0; i < node.properties.length; i++) { + var memberDecl = node.properties[i]; + var member = memberDecl.symbol; + if (memberDecl.kind === 204 /* PropertyAssignment */ || memberDecl.kind === 205 /* ShorthandPropertyAssignment */ || ts.isObjectLiteralMethod(memberDecl)) { + if (memberDecl.kind === 204 /* PropertyAssignment */) { + var type = checkPropertyAssignment(memberDecl, contextualMapper); + } + else if (memberDecl.kind === 128 /* MethodDeclaration */) { + var type = checkObjectLiteralMethod(memberDecl, contextualMapper); } else { - var getAccessor = ts.getDeclarationOfKind(member, 130 /* GetAccessor */); - if (getAccessor) { - checkAccessorDeclaration(getAccessor); - } - var setAccessor = ts.getDeclarationOfKind(member, 131 /* SetAccessor */); - if (setAccessor) { - checkAccessorDeclaration(setAccessor); - } + ts.Debug.assert(memberDecl.kind === 205 /* ShorthandPropertyAssignment */); + var type = memberDecl.name.kind === 122 /* ComputedPropertyName */ ? unknownType : checkExpression(memberDecl.name, contextualMapper); } - properties[member.name] = member; + typeFlags |= type.flags; + var prop = createSymbol(4 /* Property */ | 67108864 /* Transient */ | member.flags, member.name); + prop.declarations = member.declarations; + prop.parent = member.parent; + if (member.valueDeclaration) { + prop.valueDeclaration = member.valueDeclaration; + } + prop.type = type; + prop.target = member; + member = prop; } + else { + ts.Debug.assert(memberDecl.kind === 130 /* GetAccessor */ || memberDecl.kind === 131 /* SetAccessor */); + checkAccessorDeclaration(memberDecl); + } + if (!ts.hasDynamicName(memberDecl)) { + propertiesTable[member.name] = member; + } + propertiesArray.push(member); } var stringIndexType = getIndexType(0 /* String */); var numberIndexType = getIndexType(1 /* Number */); - var result = createAnonymousType(node.symbol, properties, emptyArray, emptyArray, stringIndexType, numberIndexType); - result.flags |= (typeFlags & 131072 /* Unwidened */); + var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); + result.flags |= 131072 /* ObjectLiteral */ | 524288 /* ContainsObjectLiteral */ | (typeFlags & 262144 /* ContainsUndefinedOrNull */); return result; function getIndexType(kind) { if (contextualType && contextualTypeHasIndexSignature(contextualType, kind)) { var propTypes = []; - for (var id in properties) { - if (ts.hasProperty(properties, id)) { - if (kind === 0 /* String */ || isNumericName(id)) { - var type = getTypeOfSymbol(properties[id]); - if (!ts.contains(propTypes, type)) { - propTypes.push(type); - } + for (var i = 0; i < propertiesArray.length; i++) { + var propertyDecl = node.properties[i]; + if (kind === 0 /* String */ || isNumericName(propertyDecl.name)) { + var type = getTypeOfSymbol(propertiesArray[i]); + if (!ts.contains(propTypes, type)) { + propTypes.push(type); } } } - return propTypes.length ? getUnionType(propTypes) : undefinedType; + var result = propTypes.length ? getUnionType(propTypes) : undefinedType; + typeFlags |= result.flags; + return result; } return undefined; } @@ -11939,8 +12112,10 @@ var ts; if (objectType === unknownType) { return unknownType; } - if (isConstEnumObjectType(objectType) && node.argumentExpression && node.argumentExpression.kind !== 8 /* StringLiteral */) { - error(node.argumentExpression, ts.Diagnostics.Index_expression_arguments_in_const_enums_must_be_of_type_string); + var isConstEnum = isConstEnumObjectType(objectType); + if (isConstEnum && (!node.argumentExpression || node.argumentExpression.kind !== 8 /* StringLiteral */)) { + error(node.argumentExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal); + return unknownType; } if (node.argumentExpression) { if (node.argumentExpression.kind === 8 /* StringLiteral */ || node.argumentExpression.kind === 7 /* NumericLiteral */) { @@ -11950,10 +12125,14 @@ var ts; getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } + else if (isConstEnum) { + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name, symbolToString(objectType.symbol)); + return unknownType; + } } } - if (indexType.flags & (1 /* Any */ | 258 /* StringLike */ | 132 /* NumberLike */)) { - if (indexType.flags & (1 /* Any */ | 132 /* NumberLike */)) { + if (isTypeOfKind(indexType, 1 /* Any */ | 258 /* StringLike */ | 132 /* NumberLike */)) { + if (isTypeOfKind(indexType, 1 /* Any */ | 132 /* NumberLike */)) { var numberIndexType = getIndexTypeOfType(objectType, 1 /* Number */); if (numberIndexType) { return numberIndexType; @@ -12137,10 +12316,25 @@ var ts; } return args; } + function getEffectiveTypeArguments(callExpression) { + if (callExpression.expression.kind === 90 /* SuperKeyword */) { + var containingClass = ts.getAncestor(callExpression, 191 /* ClassDeclaration */); + var baseClassTypeNode = containingClass && ts.getClassBaseTypeNode(containingClass); + return baseClassTypeNode && baseClassTypeNode.typeArguments; + } + else { + return callExpression.typeArguments; + } + } function resolveCall(node, signatures, candidatesOutArray) { var isTaggedTemplate = node.kind === 153 /* TaggedTemplateExpression */; - var typeArguments = isTaggedTemplate ? undefined : node.typeArguments; - ts.forEach(typeArguments, checkSourceElement); + var typeArguments; + if (!isTaggedTemplate) { + typeArguments = getEffectiveTypeArguments(node); + if (node.expression.kind !== 90 /* SuperKeyword */) { + ts.forEach(typeArguments, checkSourceElement); + } + } var candidates = candidatesOutArray || []; collectCandidates(); if (!candidates.length) { @@ -12257,8 +12451,10 @@ var ts; var result = candidates; var lastParent; var lastSymbol; - var cutoffPos = 0; - var pos; + var cutoffIndex = 0; + var index; + var specializedIndex = -1; + var spliceIndex; ts.Debug.assert(!result.length); for (var i = 0; i < signatures.length; i++) { var signature = signatures[i]; @@ -12266,22 +12462,27 @@ var ts; var parent = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { if (lastParent && parent === lastParent) { - pos++; + index++; } else { lastParent = parent; - pos = cutoffPos; + index = cutoffIndex; } } else { - pos = cutoffPos = result.length; + index = cutoffIndex = result.length; lastParent = parent; } lastSymbol = symbol; - for (var j = result.length; j > pos; j--) { - result[j] = result[j - 1]; + if (signature.hasStringLiterals) { + specializedIndex++; + spliceIndex = specializedIndex; + cutoffIndex++; } - result[pos] = signature; + else { + spliceIndex = index; + } + result.splice(spliceIndex, 0, signature); } } } @@ -12397,7 +12598,7 @@ var ts; return getReturnTypeOfSignature(signature); } function checkTaggedTemplateExpression(node) { - if (compilerOptions.target < 2 /* ES6 */) { + if (languageVersion < 2 /* ES6 */) { grammarErrorOnFirstToken(node.template, ts.Diagnostics.Tagged_templates_are_only_available_when_targeting_ECMAScript_6_and_higher); } return getReturnTypeOfSignature(getResolvedSignature(node)); @@ -12546,7 +12747,7 @@ var ts; } } function checkArithmeticOperandType(operand, type, diagnostic) { - if (!(type.flags & (1 /* Any */ | 132 /* NumberLike */))) { + if (!isTypeOfKind(type, 1 /* Any */ | 132 /* NumberLike */)) { error(operand, diagnostic); return false; } @@ -12650,11 +12851,20 @@ var ts; } return numberType; } - function isStructuredType(type) { - if (type.flags & 16384 /* Union */) { - return !ts.forEach(type.types, function (t) { return !isStructuredType(t); }); + function isTypeOfKind(type, kind) { + if (type.flags & kind) { + return true; } - return (type.flags & (48128 /* ObjectType */ | 512 /* TypeParameter */)) !== 0; + if (type.flags & 16384 /* Union */) { + var types = type.types; + for (var i = 0; i < types.length; i++) { + if (!(types[i].flags & kind)) { + return false; + } + } + return true; + } + return false; } function isConstEnumObjectType(type) { return type.flags & (48128 /* ObjectType */ | 32768 /* Anonymous */) && type.symbol && isConstEnumSymbol(type.symbol); @@ -12663,7 +12873,7 @@ var ts; return (symbol.flags & 128 /* ConstEnum */) !== 0; } function checkInstanceOfExpression(node, leftType, rightType) { - if (!(leftType.flags & 1 /* Any */ || isStructuredType(leftType))) { + if (isTypeOfKind(leftType, 510 /* Primitive */)) { error(node.left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } if (!(rightType.flags & 1 /* Any */ || isTypeSubtypeOf(rightType, globalFunctionType))) { @@ -12672,10 +12882,10 @@ var ts; return booleanType; } function checkInExpression(node, leftType, rightType) { - if (leftType !== anyType && leftType !== stringType && leftType !== numberType) { + if (!isTypeOfKind(leftType, 1 /* Any */ | 258 /* StringLike */ | 132 /* NumberLike */)) { error(node.left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_types_any_string_or_number); } - if (!(rightType.flags & 1 /* Any */ || isStructuredType(rightType))) { + if (!isTypeOfKind(rightType, 1 /* Any */ | 48128 /* ObjectType */ | 512 /* TypeParameter */)) { error(node.right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter); } return booleanType; @@ -12686,7 +12896,7 @@ var ts; var p = properties[i]; if (p.kind === 204 /* PropertyAssignment */ || p.kind === 205 /* ShorthandPropertyAssignment */) { var name = p.name; - var type = sourceType.flags & 1 /* Any */ ? sourceType : getTypeOfPropertyOfType(sourceType, name.text) || isNumericName(name.text) && getIndexTypeOfType(sourceType, 1 /* Number */) || getIndexTypeOfType(sourceType, 0 /* String */); + var type = sourceType.flags & 1 /* Any */ ? sourceType : getTypeOfPropertyOfType(sourceType, name.text) || isNumericLiteralName(name.text) && getIndexTypeOfType(sourceType, 1 /* Number */) || getIndexTypeOfType(sourceType, 0 /* String */); if (type) { checkDestructuringAssignment(p.initializer || name, type); } @@ -12805,13 +13015,13 @@ var ts; if (rightType.flags & (32 /* Undefined */ | 64 /* Null */)) rightType = leftType; var resultType; - if (leftType.flags & 132 /* NumberLike */ && rightType.flags & 132 /* NumberLike */) { + if (isTypeOfKind(leftType, 132 /* NumberLike */) && isTypeOfKind(rightType, 132 /* NumberLike */)) { resultType = numberType; } - else if (leftType.flags & 258 /* StringLike */ || rightType.flags & 258 /* StringLike */) { + else if (isTypeOfKind(leftType, 258 /* StringLike */) || isTypeOfKind(rightType, 258 /* StringLike */)) { resultType = stringType; } - else if (leftType.flags & 1 /* Any */ || leftType === unknownType || rightType.flags & 1 /* Any */ || rightType === unknownType) { + else if (leftType.flags & 1 /* Any */ || rightType.flags & 1 /* Any */) { resultType = anyType; } if (!resultType) { @@ -12909,8 +13119,17 @@ var ts; } return links.resolvedType; } + function checkPropertyAssignment(node, contextualMapper) { + if (ts.hasDynamicName(node)) { + checkComputedPropertyName(node.name); + } + return checkExpression(node.initializer, contextualMapper); + } function checkObjectLiteralMethod(node, contextualMapper) { checkGrammarMethod(node); + if (ts.hasDynamicName(node)) { + checkComputedPropertyName(node.name); + } var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, contextualMapper); } @@ -13033,12 +13252,15 @@ var ts; checkGrammarModifiers(node) || checkGrammarEvalOrArgumentsInStrictMode(node, node.name); checkVariableLikeDeclaration(node); var func = ts.getContainingFunction(node); - if (node.flags & (16 /* Public */ | 32 /* Private */ | 64 /* Protected */)) { + if (node.flags & 112 /* AccessibilityModifier */) { func = ts.getContainingFunction(node); if (!(func.kind === 129 /* Constructor */ && ts.nodeIsPresent(func.body))) { error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation); } } + if (node.questionToken && ts.isBindingPattern(node.name) && func.body) { + error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); + } if (node.dotDotDotToken) { if (!isArrayType(getTypeOfSymbol(node.symbol))) { error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type); @@ -13183,7 +13405,7 @@ var ts; error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value_or_consist_of_a_single_throw_statement); } } - if (!ts.hasComputedNameButNotSymbol(node)) { + if (!ts.hasDynamicName(node)) { var otherKind = node.kind === 130 /* GetAccessor */ ? 131 /* SetAccessor */ : 130 /* GetAccessor */; var otherAccessor = ts.getDeclarationOfKind(node.symbol, otherKind); if (otherAccessor) { @@ -13198,8 +13420,8 @@ var ts; } } } - checkAndStoreTypeOfAccessors(getSymbolOfNode(node)); } + checkAndStoreTypeOfAccessors(getSymbolOfNode(node)); } checkFunctionLikeDeclaration(node); } @@ -13507,7 +13729,10 @@ var ts; } function checkFunctionLikeDeclaration(node) { checkSignatureDeclaration(node); - if (!ts.hasComputedNameButNotSymbol(node)) { + if (ts.hasDynamicName(node)) { + checkComputedPropertyName(node.name); + } + else { var symbol = getSymbolOfNode(node); var localSymbol = node.localSymbol || symbol; var firstDeclaration = ts.getDeclarationOfKind(localSymbol, node.kind); @@ -13661,7 +13886,8 @@ var ts; } function checkVariableLikeDeclaration(node) { checkSourceElement(node.type); - if (ts.hasComputedNameButNotSymbol(node)) { + if (ts.hasDynamicName(node)) { + checkComputedPropertyName(node.name); if (node.initializer) { checkExpressionCached(node.initializer); } @@ -13805,7 +14031,7 @@ var ts; } } var exprType = checkExpression(node.expression); - if (!(exprType.flags & 1 /* Any */ || isStructuredType(exprType))) { + if (!isTypeOfKind(exprType, 1 /* Any */ | 48128 /* ObjectType */ | 512 /* TypeParameter */)) { error(node.expression, ts.Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter); } checkSourceElement(node.statement); @@ -13925,29 +14151,6 @@ var ts; checkBlock(node.finallyBlock); } function checkIndexConstraints(type) { - function checkIndexConstraintForProperty(prop, propertyType, indexDeclaration, indexType, indexKind) { - if (!indexType) { - return; - } - if (indexKind === 1 /* Number */ && !isNumericName(prop.name)) { - return; - } - var errorNode; - if (prop.parent === type.symbol) { - errorNode = prop.valueDeclaration; - } - else if (indexDeclaration) { - errorNode = indexDeclaration; - } - else if (type.flags & 2048 /* Interface */) { - var someBaseClassHasBothPropertyAndIndexer = ts.forEach(type.baseTypes, function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); - errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : type.symbol.declarations[0]; - } - if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { - var errorMessage = indexKind === 0 /* String */ ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; - error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); - } - } var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */); var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */); var stringIndexType = getIndexTypeOfType(type, 0 /* String */); @@ -13955,9 +14158,20 @@ var ts; if (stringIndexType || numberIndexType) { ts.forEach(getPropertiesOfObjectType(type), function (prop) { var propType = getTypeOfSymbol(prop); - checkIndexConstraintForProperty(prop, propType, declaredStringIndexer, stringIndexType, 0 /* String */); - checkIndexConstraintForProperty(prop, propType, declaredNumberIndexer, numberIndexType, 1 /* Number */); + checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); }); + if (type.flags & 1024 /* Class */ && type.symbol.valueDeclaration.kind === 191 /* ClassDeclaration */) { + var classDeclaration = type.symbol.valueDeclaration; + for (var i = 0; i < classDeclaration.members.length; i++) { + var member = classDeclaration.members[i]; + if (!(member.flags & 128 /* Static */) && ts.hasDynamicName(member)) { + var propType = getTypeOfSymbol(member.symbol); + checkIndexConstraintForProperty(member.symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */); + checkIndexConstraintForProperty(member.symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */); + } + } + } } var errorNode; if (stringIndexType && numberIndexType) { @@ -13970,6 +14184,29 @@ var ts; if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); } + function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { + if (!indexType) { + return; + } + if (indexKind === 1 /* Number */ && !isNumericName(prop.valueDeclaration.name)) { + return; + } + var errorNode; + if (prop.valueDeclaration.name.kind === 122 /* ComputedPropertyName */ || prop.parent === containingType.symbol) { + errorNode = prop.valueDeclaration; + } + else if (indexDeclaration) { + errorNode = indexDeclaration; + } + else if (containingType.flags & 2048 /* Interface */) { + var someBaseClassHasBothPropertyAndIndexer = ts.forEach(containingType.baseTypes, function (base) { return getPropertyOfObjectType(base, prop.name) && getIndexTypeOfType(base, indexKind); }); + errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0]; + } + if (errorNode && !isTypeAssignableTo(propertyType, indexType)) { + var errorMessage = indexKind === 0 /* String */ ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2 : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2; + error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType)); + } + } } function checkTypeNameIsReserved(name, message) { switch (name.text) { @@ -14198,7 +14435,7 @@ var ts; var ambient = ts.isInAmbientContext(node); var enumIsConst = ts.isConst(node); ts.forEach(node.members, function (member) { - if (isNumericName(member.name.text)) { + if (member.name.kind !== 122 /* ComputedPropertyName */ && isNumericLiteralName(member.name.text)) { error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name); } var initializer = member.initializer; @@ -15162,8 +15399,8 @@ var ts; if (symbol && (symbol.flags & 8 /* EnumMember */)) { var declaration = symbol.valueDeclaration; var constantValue; - if (declaration.kind === 206 /* EnumMember */ && (constantValue = getNodeLinks(declaration).enumMemberValue) !== undefined) { - return constantValue; + if (declaration.kind === 206 /* EnumMember */) { + return getEnumMemberValue(declaration); } } return undefined; @@ -15222,7 +15459,7 @@ var ts; globalNumberType = getGlobalType("Number"); globalBooleanType = getGlobalType("Boolean"); globalRegExpType = getGlobalType("RegExp"); - globalTemplateStringsArrayType = compilerOptions.target >= 2 /* ES6 */ ? getGlobalType("TemplateStringsArray") : unknownType; + globalTemplateStringsArrayType = languageVersion >= 2 /* ES6 */ ? getGlobalType("TemplateStringsArray") : unknownType; anyArrayType = createArrayType(anyType); } function checkGrammarModifiers(node) { @@ -15346,6 +15583,9 @@ var ts; else if (node.kind === 192 /* InterfaceDeclaration */ && flags & 2 /* Ambient */) { return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_declare_modifier_cannot_be_used_with_an_interface_declaration, "declare"); } + else if (node.kind === 124 /* Parameter */ && (flags & 112 /* AccessibilityModifier */) && ts.isBindingPattern(node.name)) { + return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_a_binding_pattern); + } } function checkGrammarForDisallowedTrailingComma(list) { if (list && list.hasTrailingComma) { @@ -15530,16 +15770,14 @@ var ts; } function checkGrammarComputedPropertyName(node) { if (node.kind !== 122 /* ComputedPropertyName */) { - return; + return false; } - grammarErrorOnNode(node, ts.Diagnostics.Computed_property_names_are_not_currently_supported); - return; var computedPropertyName = node; - if (compilerOptions.target < 2 /* ES6 */) { - grammarErrorOnNode(node, ts.Diagnostics.Computed_property_names_are_only_available_when_targeting_ECMAScript_6_and_higher); + if (languageVersion < 2 /* ES6 */) { + return grammarErrorOnNode(node, ts.Diagnostics.Computed_property_names_are_only_available_when_targeting_ECMAScript_6_and_higher); } else if (computedPropertyName.expression.kind === 163 /* BinaryExpression */ && computedPropertyName.expression.operator === 23 /* CommaToken */) { - grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); + return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name); } } function checkGrammarForGenerator(node) { @@ -15615,7 +15853,7 @@ var ts; } function checkGrammarAccessor(accessor) { var kind = accessor.kind; - if (compilerOptions.target < 1 /* ES5 */) { + if (languageVersion < 1 /* ES5 */) { return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher); } else if (ts.isInAmbientContext(accessor)) { @@ -15780,7 +16018,7 @@ var ts; if (!declarationList.declarations.length) { return grammarErrorAtPos(ts.getSourceFileOfNode(declarationList), declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty); } - if (compilerOptions.target < 2 /* ES6 */) { + if (languageVersion < 2 /* ES6 */) { if (ts.isLet(declarationList)) { return grammarErrorOnFirstToken(declarationList, ts.Diagnostics.let_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher); } @@ -15863,7 +16101,7 @@ var ts; function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var scanner = ts.createScanner(compilerOptions.target, true, sourceFile.text); + var scanner = ts.createScanner(languageVersion, true, sourceFile.text); var start = scanToken(scanner, node.pos); diagnostics.push(ts.createFileDiagnostic(sourceFile, start, scanner.getTextPos() - start, message, arg0, arg1, arg2)); return true; @@ -15963,7 +16201,7 @@ var ts; if (node.parserContextFlags & 1 /* StrictMode */) { return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode); } - else if (compilerOptions.target >= 1 /* ES5 */) { + else if (languageVersion >= 1 /* ES5 */) { return grammarErrorOnNode(node, ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher); } } @@ -15971,7 +16209,7 @@ var ts; function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) { var sourceFile = ts.getSourceFileOfNode(node); if (!hasParseDiagnostics(sourceFile)) { - var scanner = ts.createScanner(compilerOptions.target, true, sourceFile.text); + var scanner = ts.createScanner(languageVersion, true, sourceFile.text); scanToken(scanner, node.pos); diagnostics.push(ts.createFileDiagnostic(sourceFile, scanner.getTextPos(), 0, message, arg0, arg1, arg2)); return true; @@ -16098,9 +16336,10 @@ var ts; function writeCommentRange(currentSourceFile, writer, comment, newLine) { if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { var firstCommentLineAndCharacter = currentSourceFile.getLineAndCharacterFromPosition(comment.pos); + var lastLine = currentSourceFile.getLineStarts().length; var firstCommentLineIndent; for (var pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) { - var nextLineStart = currentSourceFile.getPositionFromLineAndCharacter(currentLine + 1, 1); + var nextLineStart = currentLine === lastLine ? (comment.end + 1) : currentSourceFile.getPositionFromLineAndCharacter(currentLine + 1, 1); if (pos !== comment.pos) { if (firstCommentLineIndent === undefined) { firstCommentLineIndent = calculateIndent(currentSourceFile.getPositionFromLineAndCharacter(firstCommentLineAndCharacter.line, 1), comment.pos); @@ -16220,6 +16459,7 @@ var ts; function emitDeclarations(host, resolver, diagnostics, jsFilePath, root) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); + var languageVersion = compilerOptions.target || 0 /* ES3 */; var write; var writeLine; var increaseIndent; @@ -16712,6 +16952,9 @@ var ts; } } function emitPropertyDeclaration(node) { + if (ts.hasDynamicName(node)) { + return; + } emitJsDocComments(node); emitClassMemberDeclarationFlags(node); emitVariableDeclaration(node); @@ -16780,6 +17023,9 @@ var ts; } } function emitAccessorDeclaration(node) { + if (ts.hasDynamicName(node)) { + return; + } var accessors = getAllAccessorDeclarations(node.parent, node); if (node === accessors.firstAccessor) { emitJsDocComments(accessors.getAccessor); @@ -16837,6 +17083,9 @@ var ts; } } function emitFunctionDeclaration(node) { + if (ts.hasDynamicName(node)) { + return; + } if ((node.kind !== 190 /* FunctionDeclaration */ || resolver.isDeclarationVisible(node)) && !resolver.isImplementationOfOverload(node)) { emitJsDocComments(node); if (node.kind === 190 /* FunctionDeclaration */) { @@ -17088,6 +17337,7 @@ var ts; ts.getDeclarationDiagnostics = getDeclarationDiagnostics; function emitFiles(resolver, host, targetSourceFile) { var compilerOptions = host.getCompilerOptions(); + var languageVersion = compilerOptions.target || 0 /* ES3 */; var sourceMapDataList = compilerOptions.sourceMap ? [] : undefined; var diagnostics = []; var newLine = host.getNewLine(); @@ -17244,7 +17494,11 @@ var ts; if (scopeName) { var parentIndex = getSourceMapNameIndex(); if (parentIndex !== -1) { - scopeName = sourceMapData.sourceMapNames[parentIndex] + "." + scopeName; + var name = node.name; + if (!name || name.kind !== 122 /* ComputedPropertyName */) { + scopeName = "." + scopeName; + } + scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName; } scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName); if (scopeNameIndex === undefined) { @@ -17260,7 +17514,8 @@ var ts; } else if (node.kind === 190 /* FunctionDeclaration */ || node.kind === 156 /* FunctionExpression */ || node.kind === 128 /* MethodDeclaration */ || node.kind === 127 /* MethodSignature */ || node.kind === 130 /* GetAccessor */ || node.kind === 131 /* SetAccessor */ || node.kind === 195 /* ModuleDeclaration */ || node.kind === 191 /* ClassDeclaration */ || node.kind === 194 /* EnumDeclaration */) { if (node.name) { - scopeName = node.name.text; + var name = node.name; + scopeName = name.kind === 122 /* ComputedPropertyName */ ? ts.getTextOfNode(name) : node.name.text; } recordScopeNameStart(scopeName); } @@ -17480,11 +17735,11 @@ var ts; return false; } function emitLiteral(node) { - var text = compilerOptions.target < 2 /* ES6 */ && ts.isTemplateLiteralKind(node.kind) ? getTemplateLiteralAsStringLiteral(node) : node.parent ? ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node) : node.text; + var text = languageVersion < 2 /* ES6 */ && ts.isTemplateLiteralKind(node.kind) ? getTemplateLiteralAsStringLiteral(node) : node.parent ? ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node) : node.text; if (compilerOptions.sourceMap && (node.kind === 8 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { writer.writeLiteral(text); } - else if (compilerOptions.target < 2 /* ES6 */ && node.kind === 7 /* NumericLiteral */ && isBinaryOrOctalIntegerLiteral(text)) { + else if (languageVersion < 2 /* ES6 */ && node.kind === 7 /* NumericLiteral */ && isBinaryOrOctalIntegerLiteral(text)) { write(node.text); } else { @@ -17495,7 +17750,7 @@ var ts; return '"' + ts.escapeString(node.text) + '"'; } function emitTemplateExpression(node) { - if (compilerOptions.target >= 2 /* ES6 */) { + if (languageVersion >= 2 /* ES6 */) { ts.forEachChild(node, emit); return; } @@ -17542,7 +17797,7 @@ var ts; } } function comparePrecedenceToBinaryPlus(expression) { - ts.Debug.assert(compilerOptions.target <= 1 /* ES5 */); + ts.Debug.assert(languageVersion < 2 /* ES6 */); switch (expression.kind) { case 163 /* BinaryExpression */: switch (expression.operator) { @@ -17708,7 +17963,7 @@ var ts; write("[]"); return; } - if (compilerOptions.target >= 2 /* ES6 */) { + if (languageVersion >= 2 /* ES6 */) { write("["); emitList(elements, 0, elements.length, (node.flags & 256 /* MultiLine */) !== 0, elements.hasTrailingComma); write("]"); @@ -17753,7 +18008,7 @@ var ts; if (!multiLine) { write(" "); } - emitList(properties, 0, properties.length, multiLine, properties.hasTrailingComma && compilerOptions.target >= 1 /* ES5 */); + emitList(properties, 0, properties.length, multiLine, properties.hasTrailingComma && languageVersion >= 1 /* ES5 */); if (!multiLine) { write(" "); } @@ -17766,32 +18021,23 @@ var ts; write("]"); } function emitMethod(node) { - if (!ts.isObjectLiteralMethod(node)) { - return; - } - emitLeadingComments(node); emit(node.name); - if (compilerOptions.target < 2 /* ES6 */) { + if (languageVersion < 2 /* ES6 */) { write(": function "); } emitSignatureAndBody(node); - emitTrailingComments(node); } function emitPropertyAssignment(node) { - emitLeadingComments(node); emit(node.name); write(": "); emit(node.initializer); - emitTrailingComments(node); } function emitShorthandPropertyAssignment(node) { - emitLeadingComments(node); emit(node.name); - if (compilerOptions.target < 2 /* ES6 */ || resolver.getExpressionNamePrefix(node.name)) { + if (languageVersion < 2 /* ES6 */ || resolver.getExpressionNamePrefix(node.name)) { write(": "); emitExpressionIdentifier(node.name); } - emitTrailingComments(node); } function tryEmitConstantValue(node) { var constantValue = resolver.getConstantValue(node); @@ -17859,7 +18105,7 @@ var ts; } } function emitTaggedTemplateExpression(node) { - ts.Debug.assert(compilerOptions.target >= 2 /* ES6 */, "Trying to emit a tagged template in pre-ES6 mode."); + ts.Debug.assert(languageVersion >= 2 /* ES6 */, "Trying to emit a tagged template in pre-ES6 mode."); emit(node.tag); write(" "); emit(node.template); @@ -17912,7 +18158,7 @@ var ts; write(ts.tokenToString(node.operator)); } function emitBinaryExpression(node) { - if (compilerOptions.target < 2 /* ES6 */ && node.operator === 52 /* EqualsToken */ && (node.left.kind === 148 /* ObjectLiteralExpression */ || node.left.kind === 147 /* ArrayLiteralExpression */)) { + if (languageVersion < 2 /* ES6 */ && node.operator === 52 /* EqualsToken */ && (node.left.kind === 148 /* ObjectLiteralExpression */ || node.left.kind === 147 /* ArrayLiteralExpression */)) { emitDestructuring(node); } else { @@ -17961,13 +18207,10 @@ var ts; } } function emitExpressionStatement(node) { - emitLeadingComments(node); emitParenthesized(node.expression, node.expression.kind === 157 /* ArrowFunction */); write(";"); - emitTrailingComments(node); } function emitIfStatement(node) { - emitLeadingComments(node); var endPos = emitToken(83 /* IfKeyword */, node.pos); write(" "); endPos = emitToken(16 /* OpenParenToken */, endPos); @@ -17985,7 +18228,6 @@ var ts; emitEmbeddedStatement(node.elseStatement); } } - emitTrailingComments(node); } function emitDoStatement(node) { write("do"); @@ -18067,11 +18309,9 @@ var ts; write(";"); } function emitReturnStatement(node) { - emitLeadingComments(node); emitToken(89 /* ReturnKeyword */, node.pos); emitOptional(" ", node.expression); write(";"); - emitTrailingComments(node); } function emitWithStatement(node) { write("with ("); @@ -18352,9 +18592,8 @@ var ts; } } function emitVariableDeclaration(node) { - emitLeadingComments(node); if (ts.isBindingPattern(node.name)) { - if (compilerOptions.target < 2 /* ES6 */) { + if (languageVersion < 2 /* ES6 */) { emitDestructuring(node); } else { @@ -18366,10 +18605,8 @@ var ts; emitModuleMemberName(node); emitOptional(" = ", node.initializer); } - emitTrailingComments(node); } function emitVariableStatement(node) { - emitLeadingComments(node); if (!(node.flags & 1 /* Export */)) { if (ts.isLet(node.declarationList)) { write("let "); @@ -18383,11 +18620,9 @@ var ts; } emitCommaList(node.declarationList.declarations); write(";"); - emitTrailingComments(node); } function emitParameter(node) { - emitLeadingComments(node); - if (compilerOptions.target < 2 /* ES6 */) { + if (languageVersion < 2 /* ES6 */) { if (ts.isBindingPattern(node.name)) { var name = createTempVariable(node); if (!tempParameters) { @@ -18407,10 +18642,9 @@ var ts; emit(node.name); emitOptional(" = ", node.initializer); } - emitTrailingComments(node); } function emitDefaultValueAssignments(node) { - if (compilerOptions.target < 2 /* ES6 */) { + if (languageVersion < 2 /* ES6 */) { var tempIndex = 0; ts.forEach(node.parameters, function (p) { if (ts.isBindingPattern(p.name)) { @@ -18439,7 +18673,7 @@ var ts; } } function emitRestParameter(node) { - if (compilerOptions.target < 2 /* ES6 */ && ts.hasRestParameters(node)) { + if (languageVersion < 2 /* ES6 */ && ts.hasRestParameters(node)) { var restIndex = node.parameters.length - 1; var restParam = node.parameters[restIndex]; var tempName = createTempVariable(node, true).text; @@ -18477,11 +18711,9 @@ var ts; } } function emitAccessor(node) { - emitLeadingComments(node); write(node.kind === 130 /* GetAccessor */ ? "get " : "set "); emit(node.name); emitSignatureAndBody(node); - emitTrailingComments(node); } function emitFunctionDeclaration(node) { if (ts.nodeIsMissing(node.body)) { @@ -18512,7 +18744,7 @@ var ts; write("("); if (node) { var parameters = node.parameters; - var omitCount = compilerOptions.target < 2 /* ES6 */ && ts.hasRestParameters(node) ? 1 : 0; + var omitCount = languageVersion < 2 /* ES6 */ && ts.hasRestParameters(node) ? 1 : 0; emitList(parameters, 0, parameters.length - omitCount, false, false); } write(")"); @@ -18543,7 +18775,7 @@ var ts; write(" "); emitStart(node.body); write("return "); - emitNode(node.body); + emitNode(node.body, true); emitEnd(node.body); write(";"); emitTempDeclarations(false); @@ -18560,7 +18792,7 @@ var ts; writeLine(); emitLeadingComments(node.body); write("return "); - emit(node.body); + emit(node.body, true); write(";"); emitTrailingComments(node.body); } @@ -18734,7 +18966,6 @@ var ts; }); } function emitClassDeclaration(node) { - emitLeadingComments(node); write("var "); emit(node.name); write(" = (function ("); @@ -18784,7 +19015,6 @@ var ts; emitEnd(node); write(";"); } - emitTrailingComments(node); function emitConstructorOfClass() { var saveTempCount = tempCount; var saveTempVariables = tempVariables; @@ -18859,12 +19089,14 @@ var ts; function emitInterfaceDeclaration(node) { emitPinnedOrTripleSlashComments(node); } - function emitEnumDeclaration(node) { + function shouldEmitEnumDeclaration(node) { var isConstEnum = ts.isConst(node); - if (isConstEnum && !compilerOptions.preserveConstEnums) { + return !isConstEnum || compilerOptions.preserveConstEnums; + } + function emitEnumDeclaration(node) { + if (!shouldEmitEnumDeclaration(node)) { return; } - emitLeadingComments(node); if (!(node.flags & 1 /* Export */)) { emitStart(node); write("var "); @@ -18881,7 +19113,7 @@ var ts; write(") {"); increaseIndent(); scopeEmitStart(node); - emitEnumMemberDeclarations(isConstEnum); + emitLines(node.members); decreaseIndent(); writeLine(); emitToken(15 /* CloseBraceToken */, node.members.end); @@ -18902,31 +19134,26 @@ var ts; emitEnd(node); write(";"); } - emitTrailingComments(node); - function emitEnumMemberDeclarations(isConstEnum) { - ts.forEach(node.members, function (member) { - writeLine(); - emitLeadingComments(member); - emitStart(member); - write(resolver.getLocalNameOfContainer(node)); - write("["); - write(resolver.getLocalNameOfContainer(node)); - write("["); - emitExpressionForPropertyName(member.name); - write("] = "); - if (member.initializer && !isConstEnum) { - emit(member.initializer); - } - else { - write(resolver.getEnumMemberValue(member).toString()); - } - write("] = "); - emitExpressionForPropertyName(member.name); - emitEnd(member); - write(";"); - emitTrailingComments(member); - }); + } + function emitEnumMember(node) { + var enumParent = node.parent; + emitStart(node); + write(resolver.getLocalNameOfContainer(enumParent)); + write("["); + write(resolver.getLocalNameOfContainer(enumParent)); + write("["); + emitExpressionForPropertyName(node.name); + write("] = "); + if (node.initializer && !ts.isConst(enumParent)) { + emit(node.initializer); } + else { + write(resolver.getEnumMemberValue(node).toString()); + } + write("] = "); + emitExpressionForPropertyName(node.name); + emitEnd(node); + write(";"); } function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { if (moduleDeclaration.body.kind === 195 /* ModuleDeclaration */) { @@ -18934,12 +19161,14 @@ var ts; return recursiveInnerModule || moduleDeclaration.body; } } + function shouldEmitModuleDeclaration(node) { + return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums); + } function emitModuleDeclaration(node) { - var shouldEmit = ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums); + var shouldEmit = shouldEmitModuleDeclaration(node); if (!shouldEmit) { return emitPinnedOrTripleSlashComments(node); } - emitLeadingComments(node); emitStart(node); write("var "); emit(node.name); @@ -18984,7 +19213,6 @@ var ts; emitModuleMemberName(node); write(" = {}));"); emitEnd(node); - emitTrailingComments(node); } function emitImportDeclaration(node) { var emitImportDeclaration = resolver.isReferencedImportDeclaration(node); @@ -19157,13 +19385,38 @@ var ts; } emitLeadingComments(node.endOfFileToken); } - function emitNode(node) { + function emitNode(node, disableComments) { if (!node) { return; } if (node.flags & 2 /* Ambient */) { return emitPinnedOrTripleSlashComments(node); } + var emitComments = !disableComments && shouldEmitLeadingAndTrailingComments(node); + if (emitComments) { + emitLeadingComments(node); + } + emitJavaScriptWorker(node); + if (emitComments) { + emitTrailingComments(node); + } + } + function shouldEmitLeadingAndTrailingComments(node) { + switch (node.kind) { + case 192 /* InterfaceDeclaration */: + case 190 /* FunctionDeclaration */: + case 197 /* ImportDeclaration */: + case 193 /* TypeAliasDeclaration */: + case 198 /* ExportAssignment */: + return false; + case 195 /* ModuleDeclaration */: + return shouldEmitModuleDeclaration(node); + case 194 /* EnumDeclaration */: + return shouldEmitEnumDeclaration(node); + } + return true; + } + function emitJavaScriptWorker(node) { switch (node.kind) { case 64 /* Identifier */: return emitIdentifier(node); @@ -19300,6 +19553,8 @@ var ts; return emitInterfaceDeclaration(node); case 194 /* EnumDeclaration */: return emitEnumDeclaration(node); + case 206 /* EnumMember */: + return emitEnumMember(node); case 195 /* ModuleDeclaration */: return emitModuleDeclaration(node); case 197 /* ImportDeclaration */: @@ -19322,15 +19577,17 @@ var ts; return leadingComments; } function getLeadingCommentsToEmit(node) { - if (node.parent.kind === 207 /* SourceFile */ || node.pos !== node.parent.pos) { - var leadingComments; - if (hasDetachedComments(node.pos)) { - leadingComments = getLeadingCommentsWithoutDetachedComments(); + if (node.parent) { + if (node.parent.kind === 207 /* SourceFile */ || node.pos !== node.parent.pos) { + var leadingComments; + if (hasDetachedComments(node.pos)) { + leadingComments = getLeadingCommentsWithoutDetachedComments(); + } + else { + leadingComments = ts.getLeadingCommentRangesOfNode(node, currentSourceFile); + } + return leadingComments; } - else { - leadingComments = ts.getLeadingCommentRangesOfNode(node, currentSourceFile); - } - return leadingComments; } } function emitLeadingDeclarationComments(node) { @@ -19339,9 +19596,11 @@ var ts; emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); } function emitTrailingDeclarationComments(node) { - if (node.parent.kind === 207 /* SourceFile */ || node.end !== node.parent.end) { - var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, node.end); - emitComments(currentSourceFile, writer, trailingComments, false, newLine, writeComment); + if (node.parent) { + if (node.parent.kind === 207 /* SourceFile */ || node.end !== node.parent.end) { + var trailingComments = ts.getTrailingCommentRanges(currentSourceFile.text, node.end); + emitComments(currentSourceFile, writer, trailingComments, false, newLine, writeComment); + } } } function emitLeadingCommentsOfLocalPosition(pos) { @@ -19779,7 +20038,7 @@ var ts; return; } var firstExternalModule = ts.forEach(files, function (f) { return ts.isExternalModule(f) ? f : undefined; }); - if (firstExternalModule && options.module === 0 /* None */) { + if (firstExternalModule && !options.module) { var externalModuleErrorSpan = ts.getErrorSpanForNode(firstExternalModule.externalModuleIndicator); var errorStart = ts.skipTrivia(firstExternalModule.text, externalModuleErrorSpan.pos); var errorLength = externalModuleErrorSpan.end - errorStart; @@ -19859,6 +20118,10 @@ var ts; type: "boolean", description: ts.Diagnostics.Print_this_message }, + { + name: "listFiles", + type: "boolean" + }, { name: "locale", type: "string" @@ -19866,6 +20129,7 @@ var ts; { name: "mapRoot", type: "string", + isFilePath: true, description: ts.Diagnostics.Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations, paramType: ts.Diagnostics.LOCATION }, @@ -19916,6 +20180,7 @@ var ts; { name: "outDir", type: "string", + isFilePath: true, description: ts.Diagnostics.Redirect_output_structure_to_the_directory, paramType: ts.Diagnostics.DIRECTORY }, @@ -19924,6 +20189,14 @@ var ts; type: "boolean", description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code }, + { + name: "project", + shortName: "p", + type: "string", + isFilePath: true, + description: ts.Diagnostics.Compile_the_project_in_the_given_directory, + paramType: ts.Diagnostics.DIRECTORY + }, { name: "removeComments", type: "boolean", @@ -19937,6 +20210,7 @@ var ts; { name: "sourceRoot", type: "string", + isFilePath: true, description: ts.Diagnostics.Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations, paramType: ts.Diagnostics.LOCATION }, @@ -19966,21 +20240,18 @@ var ts; description: ts.Diagnostics.Watch_input_files } ]; - var shortOptionNames = {}; - var optionNameMap = {}; - ts.forEach(ts.optionDeclarations, function (option) { - optionNameMap[option.name.toLowerCase()] = option; - if (option.shortName) { - shortOptionNames[option.shortName] = option.name; - } - }); function parseCommandLine(commandLine) { - var options = { - target: 0 /* ES3 */, - module: 0 /* None */ - }; + var options = {}; var filenames = []; var errors = []; + var shortOptionNames = {}; + var optionNameMap = {}; + ts.forEach(ts.optionDeclarations, function (option) { + optionNameMap[option.name.toLowerCase()] = option; + if (option.shortName) { + shortOptionNames[option.shortName] = option.name; + } + }); parseStrings(commandLine); return { options: options, @@ -20070,6 +20341,83 @@ var ts; } } ts.parseCommandLine = parseCommandLine; + function readConfigFile(filename) { + try { + var text = ts.sys.readFile(filename); + return /\S/.test(text) ? JSON.parse(text) : {}; + } + catch (e) { + } + } + ts.readConfigFile = readConfigFile; + function parseConfigFile(json, basePath) { + var errors = []; + return { + options: getCompilerOptions(), + filenames: getFiles(), + errors: errors + }; + function getCompilerOptions() { + var options = {}; + var optionNameMap = {}; + ts.forEach(ts.optionDeclarations, function (option) { + optionNameMap[option.name] = option; + }); + var jsonOptions = json["compilerOptions"]; + if (jsonOptions) { + for (var id in jsonOptions) { + if (ts.hasProperty(optionNameMap, id)) { + var opt = optionNameMap[id]; + var optType = opt.type; + var value = jsonOptions[id]; + var expectedType = typeof optType === "string" ? optType : "string"; + if (typeof value === expectedType) { + if (typeof optType !== "string") { + var key = value.toLowerCase(); + if (ts.hasProperty(optType, key)) { + value = optType[key]; + } + else { + errors.push(ts.createCompilerDiagnostic(opt.error)); + value = 0; + } + } + if (opt.isFilePath) { + value = ts.normalizePath(ts.combinePaths(basePath, value)); + } + options[opt.name] = value; + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, id, expectedType)); + } + } + else { + errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_compiler_option_0, id)); + } + } + } + return options; + } + function getFiles() { + var files = []; + if (ts.hasProperty(json, "files")) { + if (json["files"] instanceof Array) { + var files = ts.map(json["files"], function (s) { return ts.combinePaths(basePath, s); }); + } + } + else { + var sysFiles = ts.sys.readDirectory(basePath, ".ts"); + for (var i = 0; i < sysFiles.length; i++) { + var name = sysFiles[i]; + if (!ts.fileExtensionIs(name, ".d.ts") || !ts.contains(sysFiles, name.substr(0, name.length - 5) + ".ts")) { + files.push(name); + } + } + } + return files; + } + } + ts.parseConfigFile = parseConfigFile; })(ts || (ts = {})); var ts; (function (ts) { @@ -20205,8 +20553,9 @@ var ts; case 145 /* ArrayBindingPattern */: ts.forEach(node.elements, visit); break; + case 146 /* BindingElement */: case 188 /* VariableDeclaration */: - if (ts.isBindingPattern(node)) { + if (ts.isBindingPattern(node.name)) { visit(node.name); break; } @@ -20353,17 +20702,30 @@ var ts; case 190 /* FunctionDeclaration */: return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.functionElement); case 188 /* VariableDeclaration */: - if (ts.isBindingPattern(node.name)) { - break; - } - if (ts.isConst(node)) { - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.constElement); - } - else if (ts.isLet(node)) { - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.letElement); + case 146 /* BindingElement */: + var variableDeclarationNode; + var name; + if (node.kind === 146 /* BindingElement */) { + name = node.name; + variableDeclarationNode = node; + while (variableDeclarationNode && variableDeclarationNode.kind !== 188 /* VariableDeclaration */) { + variableDeclarationNode = variableDeclarationNode.parent; + } + ts.Debug.assert(variableDeclarationNode !== undefined); } else { - return createItem(node, getTextOfNode(node.name), ts.ScriptElementKind.variableElement); + ts.Debug.assert(!ts.isBindingPattern(node.name)); + variableDeclarationNode = node; + name = node.name; + } + if (ts.isConst(variableDeclarationNode)) { + return createItem(node, getTextOfNode(name), ts.ScriptElementKind.constElement); + } + else if (ts.isLet(variableDeclarationNode)) { + return createItem(node, getTextOfNode(name), ts.ScriptElementKind.letElement); + } + else { + return createItem(node, getTextOfNode(name), ts.ScriptElementKind.variableElement); } case 129 /* Constructor */: return createItem(node, "constructor", ts.ScriptElementKind.constructorImplementationElement); @@ -21281,6 +21643,9 @@ var ts; end: scanner.getTextPos(), kind: currentToken }; + if (trailingTrivia) { + trailingTrivia = undefined; + } while (scanner.getStartPos() < endPos) { currentToken = scanner.scan(); if (!ts.isTrivia(currentToken)) { @@ -22227,7 +22592,9 @@ var ts; })(Constants || (Constants = {})); function formatOnEnter(position, sourceFile, rulesProvider, options) { var line = sourceFile.getLineAndCharacterFromPosition(position).line; - ts.Debug.assert(line >= 2); + if (line === 1) { + return []; + } var span = { pos: ts.getStartPositionOfLine(line - 1, sourceFile), end: ts.getEndLinePosition(line, sourceFile) + 1 @@ -22345,7 +22712,13 @@ var ts; return start; } var precedingToken = ts.findPrecedingToken(originalRange.pos, sourceFile); - return precedingToken ? precedingToken.end : enclosingNode.pos; + if (!precedingToken) { + return enclosingNode.pos; + } + if (precedingToken.end >= originalRange.pos) { + return enclosingNode.pos; + } + return precedingToken.end; } function getOwnOrInheritedDelta(n, options, sourceFile) { var previousLine = -1 /* Unknown */; @@ -22556,7 +22929,7 @@ var ts; if (listEndToken !== 0 /* Unknown */) { if (formattingScanner.isOnToken()) { var tokenInfo = formattingScanner.readTokenInfo(parent); - if (tokenInfo.token.kind === listEndToken) { + if (tokenInfo.token.kind === listEndToken && ts.rangeContainsRange(parent, tokenInfo.token)) { consumeTokenAndAdvanceScanner(tokenInfo, parent, listDynamicIndentation); } } @@ -22908,7 +23281,8 @@ var ts; if (!precedingToken) { return 0; } - if ((precedingToken.kind === 8 /* StringLiteral */ || precedingToken.kind === 9 /* RegularExpressionLiteral */) && precedingToken.getStart(sourceFile) <= position && precedingToken.end > position) { + var precedingTokenIsLiteral = precedingToken.kind === 8 /* StringLiteral */ || precedingToken.kind === 9 /* RegularExpressionLiteral */ || precedingToken.kind === 10 /* NoSubstitutionTemplateLiteral */ || precedingToken.kind === 11 /* TemplateHead */ || precedingToken.kind === 12 /* TemplateMiddle */ || precedingToken.kind === 13 /* TemplateTail */; + if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && precedingToken.end > position) { return 0; } var lineAtPosition = sourceFile.getLineAndCharacterFromPosition(position).line; @@ -23243,7 +23617,7 @@ var __extends = this.__extends || function (d, b) { }; var ts; (function (ts) { - ts.servicesVersion = "0.4"; + ts.servicesVersion = "0.5"; var ScriptSnapshot; (function (ScriptSnapshot) { var StringScriptSnapshot = (function () { @@ -23440,28 +23814,30 @@ var ts; function getJsDocCommentsSeparatedByNewLines() { var paramTag = "@param"; var jsDocCommentParts = []; - ts.forEach(declarations, function (declaration) { - var sourceFileOfDeclaration = ts.getSourceFileOfNode(declaration); - if (canUseParsedParamTagComments && declaration.kind === 124 /* Parameter */) { - ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration), function (jsDocCommentTextRange) { - var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); - if (cleanedParamJsDocComment) { - jsDocCommentParts.push.apply(jsDocCommentParts, cleanedParamJsDocComment); + ts.forEach(declarations, function (declaration, indexOfDeclaration) { + if (ts.indexOf(declarations, declaration) === indexOfDeclaration) { + var sourceFileOfDeclaration = ts.getSourceFileOfNode(declaration); + if (canUseParsedParamTagComments && declaration.kind === 124 /* Parameter */) { + ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration), function (jsDocCommentTextRange) { + var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); + if (cleanedParamJsDocComment) { + jsDocCommentParts.push.apply(jsDocCommentParts, cleanedParamJsDocComment); + } + }); + } + if (declaration.kind === 195 /* ModuleDeclaration */ && declaration.body.kind === 195 /* ModuleDeclaration */) { + return; + } + while (declaration.kind === 195 /* ModuleDeclaration */ && declaration.parent.kind === 195 /* ModuleDeclaration */) { + declaration = declaration.parent; + } + ts.forEach(getJsDocCommentTextRange(declaration.kind === 188 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { + var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); + if (cleanedJsDocComment) { + jsDocCommentParts.push.apply(jsDocCommentParts, cleanedJsDocComment); } }); } - if (declaration.kind === 195 /* ModuleDeclaration */ && declaration.body.kind === 195 /* ModuleDeclaration */) { - return; - } - while (declaration.kind === 195 /* ModuleDeclaration */ && declaration.parent.kind === 195 /* ModuleDeclaration */) { - declaration = declaration.parent; - } - ts.forEach(getJsDocCommentTextRange(declaration.kind === 188 /* VariableDeclaration */ ? declaration.parent.parent : declaration, sourceFileOfDeclaration), function (jsDocCommentTextRange) { - var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration); - if (cleanedJsDocComment) { - jsDocCommentParts.push.apply(jsDocCommentParts, cleanedJsDocComment); - } - }); }); return jsDocCommentParts; function getJsDocCommentTextRange(node, sourceFile) { @@ -24087,6 +24463,7 @@ var ts; function createLanguageServiceSourceFile(filename, scriptSnapshot, scriptTarget, version, isOpen, setNodeParents) { var sourceFile = ts.createSourceFile(filename, scriptSnapshot.getText(0, scriptSnapshot.getLength()), scriptTarget, setNodeParents); setSourceFileFields(sourceFile, scriptSnapshot, version, isOpen); + sourceFile.nameTable = sourceFile.identifiers; return sourceFile; } ts.createLanguageServiceSourceFile = createLanguageServiceSourceFile; @@ -24110,6 +24487,7 @@ var ts; if (!ts.disableIncrementalParsing) { var newSourceFile = sourceFile.update(scriptSnapshot.getText(0, scriptSnapshot.getLength()), textChangeRange); setSourceFileFields(newSourceFile, scriptSnapshot, version, isOpen); + newSourceFile.nameTable = undefined; return newSourceFile; } } @@ -24409,7 +24787,9 @@ var ts; getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: function (filename) { return useCaseSensitivefilenames ? filename : filename.toLowerCase(); }, useCaseSensitiveFileNames: function () { return useCaseSensitivefilenames; }, - getNewLine: function () { return "\r\n"; }, + getNewLine: function () { + return host.getNewLine ? host.getNewLine() : "\r\n"; + }, getDefaultLibFilename: function (options) { return host.getDefaultLibFilename(options); }, @@ -25395,7 +25775,7 @@ var ts; return undefined; } if (node.kind === 64 /* Identifier */ || node.kind === 92 /* ThisKeyword */ || node.kind === 90 /* SuperKeyword */ || isLiteralNameOfPropertyDeclarationOrIndexAccess(node) || isNameOfExternalModuleImportOrDeclaration(node)) { - return getReferencesForNode(node, [sourceFile], false, false); + return getReferencesForNode(node, [sourceFile], true, false, false); } switch (node.kind) { case 83 /* IfKeyword */: @@ -25817,9 +26197,27 @@ var ts; return undefined; } ts.Debug.assert(node.kind === 64 /* Identifier */ || node.kind === 7 /* NumericLiteral */ || node.kind === 8 /* StringLiteral */); - return getReferencesForNode(node, program.getSourceFiles(), findInStrings, findInComments); + return getReferencesForNode(node, program.getSourceFiles(), false, findInStrings, findInComments); } - function getReferencesForNode(node, sourceFiles, findInStrings, findInComments) { + function initializeNameTable(sourceFile) { + var nameTable = {}; + walk(sourceFile); + sourceFile.nameTable = nameTable; + function walk(node) { + switch (node.kind) { + case 64 /* Identifier */: + nameTable[node.text] = node.text; + break; + case 8 /* StringLiteral */: + case 7 /* NumericLiteral */: + nameTable[node.text] = node.text; + break; + default: + ts.forEachChild(node, walk); + } + } + } + function getReferencesForNode(node, sourceFiles, searchOnlyInCurrentFile, findInStrings, findInComments) { if (isLabelName(node)) { if (isJumpStatementTarget(node)) { var labelDefinition = getTargetLabel(node.parent, node.text); @@ -25852,14 +26250,25 @@ var ts; getReferencesInNode(scope, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result); } else { - var internedName = getInternedName(symbol, declarations); - ts.forEach(sourceFiles, function (sourceFile) { - cancellationToken.throwIfCancellationRequested(); - if (ts.lookUp(sourceFile.identifiers, internedName)) { - result = result || []; - getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result); - } - }); + if (searchOnlyInCurrentFile) { + ts.Debug.assert(sourceFiles.length === 1); + result = []; + getReferencesInNode(sourceFiles[0], symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result); + } + else { + var internedName = getInternedName(symbol, declarations); + ts.forEach(sourceFiles, function (sourceFile) { + cancellationToken.throwIfCancellationRequested(); + if (!sourceFile.nameTable) { + initializeNameTable(sourceFile); + } + ts.Debug.assert(sourceFile.nameTable !== undefined); + if (ts.lookUp(sourceFile.nameTable, internedName)) { + result = result || []; + getReferencesInNode(sourceFile, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result); + } + }); + } } return result; function getDeclaredName(symbol) { @@ -25891,7 +26300,7 @@ var ts; return ts.getAncestor(privateDeclaration, 191 /* ClassDeclaration */); } } - if (symbol.parent) { + if (symbol.parent || (symbol.getFlags() & 268435456 /* UnionProperty */)) { return undefined; } var scope = undefined; @@ -26026,7 +26435,7 @@ var ts; } } function getReferencesForSuperKeyword(superKeyword) { - var searchSpaceNode = ts.getSuperContainer(superKeyword); + var searchSpaceNode = ts.getSuperContainer(superKeyword, false); if (!searchSpaceNode) { return undefined; } @@ -26054,7 +26463,7 @@ var ts; if (!node || node.kind !== 90 /* SuperKeyword */) { return; } - var container = ts.getSuperContainer(node); + var container = ts.getSuperContainer(node, false); if (container && (128 /* Static */ & container.flags) === staticFlag && container.parent.symbol === searchSpaceNode.symbol) { result.push(getReferenceEntryFromNode(node)); } diff --git a/bin/typescriptServices_internal.d.ts b/bin/typescriptServices_internal.d.ts index 5731d6959de..82f5e606758 100644 --- a/bin/typescriptServices_internal.d.ts +++ b/bin/typescriptServices_internal.d.ts @@ -44,6 +44,7 @@ declare module ts { function getProperty(map: Map, key: string): T; function isEmpty(map: Map): boolean; function clone(object: T): T; + function extend(first: Map, second: Map): Map; function forEachValue(map: Map, callback: (value: T) => U): U; function forEachKey(map: Map, callback: (key: string) => U): U; function lookUp(map: Map, key: string): T; @@ -125,6 +126,7 @@ declare module ts { createDirectory(directoryName: string): void; getExecutingFilePath(): string; getCurrentDirectory(): string; + readDirectory(path: string, extension?: string): string[]; getMemoryUsage?(): number; exit(exitCode?: number): void; } @@ -186,7 +188,7 @@ declare module ts { function isObjectLiteralMethod(node: Node): boolean; function getContainingFunction(node: Node): FunctionLikeDeclaration; function getThisContainer(node: Node, includeArrowFunctions: boolean): Node; - function getSuperContainer(node: Node): Node; + function getSuperContainer(node: Node, includeFunctions: boolean): Node; function getInvokedExpression(node: CallLikeExpression): Expression; function isExpression(node: Node): boolean; function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean): boolean; @@ -244,6 +246,8 @@ declare module ts { declare module ts { var optionDeclarations: CommandLineOption[]; function parseCommandLine(commandLine: string[]): ParsedCommandLine; + function readConfigFile(filename: string): any; + function parseConfigFile(json: any, basePath?: string): ParsedCommandLine; } declare module ts { interface ListItemInfo { diff --git a/bin/typescript_internal.d.ts b/bin/typescript_internal.d.ts index e9bff0d37f9..2758ab3c212 100644 --- a/bin/typescript_internal.d.ts +++ b/bin/typescript_internal.d.ts @@ -44,6 +44,7 @@ declare module "typescript" { function getProperty(map: Map, key: string): T; function isEmpty(map: Map): boolean; function clone(object: T): T; + function extend(first: Map, second: Map): Map; function forEachValue(map: Map, callback: (value: T) => U): U; function forEachKey(map: Map, callback: (key: string) => U): U; function lookUp(map: Map, key: string): T; @@ -125,6 +126,7 @@ declare module "typescript" { createDirectory(directoryName: string): void; getExecutingFilePath(): string; getCurrentDirectory(): string; + readDirectory(path: string, extension?: string): string[]; getMemoryUsage?(): number; exit(exitCode?: number): void; } @@ -186,7 +188,7 @@ declare module "typescript" { function isObjectLiteralMethod(node: Node): boolean; function getContainingFunction(node: Node): FunctionLikeDeclaration; function getThisContainer(node: Node, includeArrowFunctions: boolean): Node; - function getSuperContainer(node: Node): Node; + function getSuperContainer(node: Node, includeFunctions: boolean): Node; function getInvokedExpression(node: CallLikeExpression): Expression; function isExpression(node: Node): boolean; function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean): boolean; @@ -244,6 +246,8 @@ declare module "typescript" { declare module "typescript" { var optionDeclarations: CommandLineOption[]; function parseCommandLine(commandLine: string[]): ParsedCommandLine; + function readConfigFile(filename: string): any; + function parseConfigFile(json: any, basePath?: string): ParsedCommandLine; } declare module "typescript" { interface ListItemInfo { diff --git a/doc/TypeScript Language Specification (Change Markup).docx b/doc/TypeScript Language Specification (Change Markup).docx index 7846303e15b..bc996cae590 100644 Binary files a/doc/TypeScript Language Specification (Change Markup).docx and b/doc/TypeScript Language Specification (Change Markup).docx differ diff --git a/doc/TypeScript Language Specification (Change Markup).pdf b/doc/TypeScript Language Specification (Change Markup).pdf index ea7cede20f8..7cb0009047b 100644 Binary files a/doc/TypeScript Language Specification (Change Markup).pdf and b/doc/TypeScript Language Specification (Change Markup).pdf differ diff --git a/doc/TypeScript Language Specification.docx b/doc/TypeScript Language Specification.docx index c7b95764525..6858fa905df 100644 Binary files a/doc/TypeScript Language Specification.docx and b/doc/TypeScript Language Specification.docx differ diff --git a/doc/TypeScript Language Specification.pdf b/doc/TypeScript Language Specification.pdf index 9a165b56df6..e28d6f2d7f4 100644 Binary files a/doc/TypeScript Language Specification.pdf and b/doc/TypeScript Language Specification.pdf differ diff --git a/doc/spec.md b/doc/spec.md index 62d27e0a808..66a622d9e73 100644 --- a/doc/spec.md +++ b/doc/spec.md @@ -1,8 +1,8 @@ # TypeScript Language Specification -Version 1.4 +Version 1.5 -October, 2014 +February, 2015
@@ -120,11 +120,15 @@ TypeScript is a trademark of Microsoft Corporation. * [4.15.7 The || operator](#4.15.7) * [4.16 The Conditional Operator](#4.16) * [4.17 Assignment Operators](#4.17) + * [4.17.1 Destructuring Assignment](#4.17.1) * [4.18 The Comma Operator](#4.18) * [4.19 Contextually Typed Expressions](#4.19) * [4.20 Type Guards](#4.20) * [5 Statements](#5) * [5.1 Variable Statements](#5.1) + * [5.1.1 Simple Variable Declarations](#5.1.1) + * [5.1.2 Destructuring Variable Declarations](#5.1.2) + * [5.1.3 Implied Type](#5.1.3) * [5.2 If, Do, and While Statements](#5.2) * [5.3 For Statements](#5.3) * [5.4 For-In Statements](#5.4) @@ -139,8 +143,9 @@ TypeScript is a trademark of Microsoft Corporation. * [6.1 Function Declarations](#6.1) * [6.2 Function Overloads](#6.2) * [6.3 Function Implementations](#6.3) - * [6.4 Generic Functions](#6.4) - * [6.5 Code Generation](#6.5) + * [6.4 Destructuring Parameter Declarations](#6.4) + * [6.5 Generic Functions](#6.5) + * [6.6 Code Generation](#6.6) * [7 Interfaces](#7) * [7.1 Interface Declarations](#7.1) * [7.2 Declaration Merging](#7.2) @@ -172,7 +177,8 @@ TypeScript is a trademark of Microsoft Corporation. * [9.1 Enum Declarations](#9.1) * [9.2 Enum Members](#9.2) * [9.3 Declaration Merging](#9.3) - * [9.4 Code Generation](#9.4) + * [9.4 Constant Enum Declarations](#9.4) + * [9.5 Code Generation](#9.5) * [10 Internal Modules](#10) * [10.1 Module Declarations](#10.1) * [10.2 Module Body](#10.2) @@ -420,7 +426,7 @@ getX({ x: 0, y: 0, color: "red" }); // Extra fields Ok getX({ x: 0 }); // Error: supplied parameter does not match ``` -See section [0](#0) for more information about type comparisons. +See section [3.10](#3.10) for more information about type comparisons. ## 1.5 Contextual Typing @@ -812,7 +818,7 @@ Declarations introduce names in the ***declaration spaces*** to which they belon * Each class declaration has a declaration space for instance members, a declaration space for static members, and a declaration space for type parameters. * Each interface declaration has a declaration space for members and a declaration space for type parameters. An interface's declaration space is shared with other interfaces that have the same root module and the same qualified name starting from that root module. * Each enum declaration has a declaration space for its enum members. An enum's declaration space is shared with other enums that have the same root module and the same qualified name starting from that root module. -* Each function declaration (including constructor, member function, and member accessor declarations) and each function expression has a declaration space for variables (parameters, local variables, and local functions) and a declaration space for type parameters. +* Each function declaration (including constructor, member function, and member accessor declarations) and each function expression has a declaration space for locals (introduced by parameter, variable, and function declarations) and a declaration space for type parameters. * Each object literal has a declaration space for its properties. * Each object type literal has a declaration space for its members. @@ -868,7 +874,7 @@ The ***scope*** of a name is the region of program text within which it is possi * The scope of a type parameter declared in a class or interface declaration is that entire declaration, including constraints, extends clause, implements clause, and declaration body, but not including static member declarations. * The scope of a member declared in an enum declaration is the body of that declaration and every enum declaration with the same root and the same qualified name relative to that root. * The scope of a type parameter declared in a call or construct signature is that entire signature declaration, including constraints, parameter list, and return type. If the signature is part of a function implementation, the scope includes the function body. -* The scope of a parameter, local variable, or local function declared within a function declaration (including a constructor, member function, or member accessor declaration) or function expression is the body of that function declaration or function expression. +* The scope of a local entity (parameter, variable, or function) declared within a function declaration (including a constructor, member function, or member accessor declaration) or function expression is the body of that function declaration or function expression. Scopes may overlap, for example through nesting of modules and functions. When the scopes of two entities with the same name overlap, the entity with the innermost declaration takes precedence and access to the outer entity is either not possible or only possible by qualifying its name. @@ -955,7 +961,7 @@ The Number primitive type corresponds to the similarly named JavaScript primitiv The `number` keyword references the Number primitive type and numeric literals may be used to write values of the Number primitive type. -For purposes of determining type relationships (section [0](#0)) and accessing properties (section [4.10](#4.10)), the Number primitive type behaves as an object type with the same properties as the global interface type 'Number'. +For purposes of determining type relationships (section [3.10](#3.10)) and accessing properties (section [4.10](#4.10)), the Number primitive type behaves as an object type with the same properties as the global interface type 'Number'. Some examples: @@ -972,7 +978,7 @@ The Boolean primitive type corresponds to the similarly named JavaScript primiti The `boolean` keyword references the Boolean primitive type and the `true` and `false` literals reference the two Boolean truth values. -For purposes of determining type relationships (section [0](#0)) and accessing properties (section [4.10](#4.10)), the Boolean primitive type behaves as an object type with the same properties as the global interface type 'Boolean'. +For purposes of determining type relationships (section [3.10](#3.10)) and accessing properties (section [4.10](#4.10)), the Boolean primitive type behaves as an object type with the same properties as the global interface type 'Boolean'. Some examples: @@ -988,7 +994,7 @@ The String primitive type corresponds to the similarly named JavaScript primitiv The `string` keyword references the String primitive type and string literals may be used to write values of the String primitive type. -For purposes of determining type relationships (section [0](#0)) and accessing properties (section [4.10](#4.10)), the String primitive type behaves as an object type with the same properties as the global interface type 'String'. +For purposes of determining type relationships (section [3.10](#3.10)) and accessing properties (section [4.10](#4.10)), the String primitive type behaves as an object type with the same properties as the global interface type 'String'. Some examples: @@ -1092,6 +1098,8 @@ Array literals (section [4.6](#4.6)) may be used to create values of array types var a: string[] = ["hello", "world"]; ``` +A type is said to be an ***array-like type*** if it is assignable (section [3.10.4](#3.10.4)) to the type `any[]`. + ### 3.3.3 Tuple Types ***Tuple types*** represent JavaScript arrays with individually tracked element types. Tuple types are written using tuple type literals (section [3.7.5](#3.7.5)). A tuple type combines a set of numerically named properties with the members of an array type. Specifically, a tuple type @@ -1131,6 +1139,8 @@ interface KeyValuePair extends Array { 0: K; 1: V; } var x: KeyValuePair = [10, "ten"]; ``` +A type is said to be a ***tuple-like type*** if it has a property with the numeric name '0'. + ### 3.3.4 Function Types An object type containing one or more call signatures is said to be a ***function type***. Function types may be written using function type literals (section [3.7.7](#3.7.7)) or by including call signatures in object type literals. @@ -1150,7 +1160,7 @@ Every object type is composed from zero or more of the following kinds of member Properties are either ***public***, ***private***, or ***protected*** and are either ***required*** or ***optional***: -* Properties in a class declaration may be designated public, private, or protected, while properties declared in other contexts are always considered public. Private members are only accessible within their declaring class, as described in section [8.2.2](#8.2.2), and private properties match only themselves in subtype and assignment compatibility checks, as described in section [0](#0). Protected members are only accessible within their declaring class and classes derived from it, as described in section [8.2.2](#8.2.2), and protected properties match only themselves and overrides in subtype and assignment compatibility checks, as described in section [0](#0). +* Properties in a class declaration may be designated public, private, or protected, while properties declared in other contexts are always considered public. Private members are only accessible within their declaring class, as described in section [8.2.2](#8.2.2), and private properties match only themselves in subtype and assignment compatibility checks, as described in section [3.10](#3.10). Protected members are only accessible within their declaring class and classes derived from it, as described in section [8.2.2](#8.2.2), and protected properties match only themselves and overrides in subtype and assignment compatibility checks, as described in section [3.10](#3.10). * Properties in an object type literal or interface declaration may be designated required or optional, while properties declared in other contexts are always considered required. Properties that are optional in the target type of an assignment may be omitted from source objects, as described in section [3.10.4](#3.10.4). Call and construct signatures may be ***specialized*** (section [3.8.2.4](#3.8.2.4)) by including parameters with string literal types. Specialized signatures are used to express patterns where specific string values for some parameters cause the types of other parameters or the function result to become further specialized. @@ -1193,7 +1203,7 @@ x = test ? 5 : "five"; // Ok x = test ? 0 : false; // Error, number | boolean not asssignable ``` -it is possible to assign 'x' a value of type string, number, or the union type string | number, but not any other type. To access a value in 'x', a type guard can be used to first narrow the type of 'x' to either string or number: +it is possible to assign 'x' a value of type `string`, `number`, or the union type `string | number`, but not any other type. To access a value in 'x', a type guard can be used to first narrow the type of 'x' to either `string` or `number`: ```TypeScript var n = typeof x === "string" ? x.length : x; // Type of n is number @@ -1276,7 +1286,7 @@ interface G { the base constraint of 'T' is the empty object type, and the base constraint of 'U' and 'V' is 'Function'. -For purposes of determining type relationships (section [0](#0)), type parameters appear to be subtypes of their base constraint. Likewise, in property accesses (section [4.10](#4.10)), `new` operations (section [4.11](#4.11)), and function calls (section [4.12](#4.12)), type parameters appear to have the members of their base constraint, but no other members. +For purposes of determining type relationships (section [3.10](#3.10)), type parameters appear to be subtypes of their base constraint. Likewise, in property accesses (section [4.10](#4.10)), `new` operations (section [4.11](#4.11)), and function calls (section [4.12](#4.12)), type parameters appear to have the members of their base constraint, but no other members. ### 3.5.2 Type Argument Lists @@ -1376,7 +1386,7 @@ Parentheses are required around union, function, or constructor types when they ```TypeScript (string | number)[] -((x: string) => string) | (x: number) => number) +((x: string) => string) | ((x: number) => number) ``` The different forms of type notations are described in the following sections. @@ -1598,7 +1608,7 @@ var a = { x: 10, y: 20 }; var b: typeof a; ``` -Above, 'b' is given the same type as 'a', namely '{ x: number; y: number; }'. +Above, 'b' is given the same type as 'a', namely `{ x: number; y: number; }`. If a declaration includes a type annotation that references the entity being declared through a circular path of type queries or type references containing type queries, the resulting type is the Any type. For example, all of the following variables are given the type Any: @@ -1705,7 +1715,7 @@ A signature's parameter list consists of zero or more required parameters, follo    *RequiredParameterList* `,` *RequiredParameter*   *RequiredParameter:* -   *AccessibilityModifieropt* *Identifier* *TypeAnnotationopt* +   *AccessibilityModifieropt* *IdentifierOrPattern* *TypeAnnotationopt*    *Identifier* `:` *StringLiteral*   *AccessibilityModifier:* @@ -1713,29 +1723,39 @@ A signature's parameter list consists of zero or more required parameters, follo    `private`    `protected` +  *IdentifierOrPattern:* +   *Identifier* +   *BindingPattern* +   *OptionalParameterList:*    *OptionalParameter*    *OptionalParameterList* `,` *OptionalParameter*   *OptionalParameter:* -   *AccessibilityModifieropt* *Identifier* `?` *TypeAnnotationopt* -   *AccessibilityModifieropt* *Identifier* *TypeAnnotationopt* *Initialiser* +   *AccessibilityModifieropt* *IdentifierOrPattern* `?` *TypeAnnotationopt* +   *AccessibilityModifieropt* *IdentifierOrPattern* *TypeAnnotationopt* *Initialiser*    *Identifier* `?` `:` *StringLiteral*   *RestParameter:*    `...` *Identifier* *TypeAnnotationopt* -Parameter names must be unique. A compile-time error occurs if two or more parameters have the same name. +A parameter declaration may specify either an identifier or a binding pattern ([5.1.2](#5.1.2)). The identifiers specified in parameter declarations and binding patterns in a parameter list must be unique within that parameter list. -A parameter is permitted to include a `public`, `private`, or `protected` modifier only if it occurs in the parameter list of a *ConstructorImplementation* (section [8.3.1](#8.3.1)). +The type of a parameter in a signature is determined as follows: -A parameter with a type annotation is considered to be of that type. A type annotation for a rest parameter must denote an array type. +* If the declaration includes a type annotation, the parameter is of that type. +* Otherwise, if the declaration includes an initializer expression (which is permitted only when the parameter list occurs in conjunction with a function body), the parameter type is the widened form (section [3.11](#3.11)) of the type of the initializer expression. +* Otherwise, if the declaration specifies a binding pattern, the parameter type is the implied type of that binding pattern (section [5.1.3](#5.1.3)). +* Otherwise, if the parameter is a rest parameter, the parameter type is `any[]`. +* Otherwise, the parameter type is `any`. -A parameter with no type annotation or initializer is considered to be of type `any`, unless it is a rest parameter, in which case it is considered to be of type `any[]`. +A parameter is permitted to include a `public`, `private`, or `protected` modifier only if it occurs in the parameter list of a *ConstructorImplementation* (section [8.3.1](#8.3.1)) and only if it doesn't specify a *BindingPattern*. -When a parameter type annotation specifies a string literal type, the containing signature is a specialized signature (section [3.8.2.4](#3.8.2.4)). Specialized signatures are not permitted in conjunction with a function body, i.e. the *FunctionExpression*, *FunctionImplementation*, *MemberFunctionImplementation*, and *ConstructorImplementation* grammar productions do not permit parameters with string literal types. +A type annotation for a rest parameter must denote an array type. -A parameter can be marked optional by following its name with a question mark (`?`) or by including an initializer. The form that includes an initializer is permitted only in conjunction with a function body, i.e. only in a *FunctionExpression*, *FunctionImplementation*, *MemberFunctionImplementation*, or *ConstructorImplementation* grammar production. +When a parameter type annotation specifies a string literal type, the containing signature is a specialized signature (section [3.8.2.4](#3.8.2.4)). Specialized signatures are not permitted in conjunction with a function body, i.e. the *FunctionExpression*, *FunctionImplementation*, *MemberFunctionImplementation*, and *ConstructorImplementation* grammar productions do not permit parameters with string literal types. + +A parameter can be marked optional by following its name or binding pattern with a question mark (`?`) or by including an initializer. Initializers (including binding property or element initializers) are permitted only when the parameter list occurs in conjunction with a function body, i.e. only in a *FunctionExpression*, *FunctionImplementation*, *MemberFunctionImplementation*, or *ConstructorImplementation* grammar production. #### 3.8.2.3 Return Type @@ -1917,7 +1937,6 @@ However, doing so means the following capabilities are lost: * An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot. * An interface can have multiple merged declarations, but a type alias for an object type literal cannot. * An interface can have type parameters, but a type alias for an object type literal cannot. -* An interface is referenced by its name in error messages and tooling, but a type alias is always expanded to its structural representation. ## 3.10 Type Relationships @@ -2263,7 +2282,18 @@ If a get accessor is declared for a property, the return type of the get accesso When an object literal is contextually typed by a type that includes a string index signature, the resulting type of the object literal includes a string index signature with the union type of the types of the properties declared in the object literal, or the Undefined type if the object literal is empty. Likewise, when an object literal is contextually typed by a type that includes a numeric index signature, the resulting type of the object literal includes a numeric index signature with the union type of the types of the numerically named properties (section [3.8.4](#3.8.4)) declared in the object literal, or the Undefined type if the object literal declares no numerically named properties. -## 4.6 Array Literals +## 4.6 Array Literals + +Array literals are extended to support the spread (`...`) operator. + +  *ElementList:* *( Modified )* +   *Elisionopt* *AssignmentExpression* +   *Elisionopt* *SpreadElement* +   *ElementList* `,` *Elisionopt* *AssignmentExpression* +   *ElementList* `,` *Elisionopt* *SpreadElement* + +  *SpreadElement:* +   `...` *AssignmentExpression* An array literal @@ -2275,17 +2305,20 @@ denotes a value of an array type (section [3.3.2](#3.3.2)) or a tuple type (sect Each element expression in a non-empty array literal is processed as follows: -* If the array literal is contextually typed (section [4.19](#4.19)) by a type *T* and *T* has a property with the numeric name *N*, where *N* is the index of the element expression in the array literal, the element expression is contextually typed by the type of that property. +* If the array literal contains no spread elements, and if the array literal is contextually typed (section [4.19](#4.19)) by a type *T* and *T* has a property with the numeric name *N*, where *N* is the index of the element expression in the array literal, the element expression is contextually typed by the type of that property. * Otherwise, if the array literal is contextually typed by a type *T* with a numeric index signature, the element expression is contextually typed by the type of the numeric index signature. * Otherwise, the element expression is not contextually typed. The resulting type an array literal expression is determined as follows: * If the array literal is empty, the resulting type is an array type with the element type Undefined. -* Otherwise, if the array literal is contextually typed by a type that has a property with the numeric name '0', the resulting type is a tuple type constructed from the types of the element expressions. -* Otherwise, the resulting type is an array type with an element type that is the union of the types of the element expressions. +* Otherwise, if the array literal contains no spread elements and is contextually typed by a tuple-like type (section [3.3.3](#3.3.3)), the resulting type is a tuple type constructed from the types of the element expressions. +* Otherwise, if the array literal contains no spread elements and is an array assignment pattern in a destructuring assignment (section [4.17.1](#4.17.1)), the resulting type is a tuple type constructed from the types of the element expressions. +* Otherwise, the resulting type is an array type with an element type that is the union of the types of the non-spread element expressions and the numeric index signature types of the spread element expressions. -The rules above mean that an array literal is always of an array type, unless it is contextually typed by a type with numerically named properties (such as a tuple type). For example +A spread element must specify an expression of an array-like type (section [3.3.2](#3.3.2)), or otherwise an error occurs. + +The rules above mean that an array literal is always of an array type, unless it is contextually typed by a tuple-like type. For example ```TypeScript var a = [1, 2]; // number[] @@ -2293,6 +2326,20 @@ var b = ["hello", true]; // (string | boolean)[] var c: [number, string] = [3, "three"]; // [number, string] ``` +When the output target is ECMAScript 3 or 5, array literals containing spread elements are rewritten to invocations of the `concat` method. For example, the assignments + +```TypeScript +var a = [2, 3, 4]; +var b = [0, 1, ...a, 5, 6]; +``` + +are rewritten to + +```TypeScript +var a = [2, 3, 4]; +var b = [0, 1].concat(a, [5, 6]); +``` + ## 4.7 Parentheses A parenthesized expression @@ -2364,7 +2411,7 @@ The descriptions of function declarations provided in section [6.1](#6.1) apply Standard function expressions are function expressions written with the `function` keyword. The type of `this` in a standard function expression is the Any type. -Standard function expressions are transformed to JavaScript in the same manner as function declarations (see section [6.5](#6.5)). +Standard function expressions are transformed to JavaScript in the same manner as function declarations (see section [6.6](#6.6)). ### 4.9.2 Arrow Function Expressions @@ -2452,11 +2499,23 @@ could be parsed as an arrow function expression with a type parameter or a type ### 4.9.3 Contextually Typed Function Expressions -Function expressions with no type parameters and no parameter type annotations (but possibly with optional parameters and default parameter values) are contextually typed in certain circumstances, as described in section [4.19](#4.19). +When a function expression with no type parameters and no parameter type annotations is contextually typed (section [4.19](#4.19)) by a type *T* and a contextual signature *S* can be extracted from *T*, the function expression is processed as if it had explicitly specified parameter type annotations as they exist in *S*. Parameters are matched by position and need not have matching names. If the function expression has fewer parameters than *S*, the additional parameters in *S* are ignored. If the function expression has more parameters than *S*, the additional parameters are all considered to have type Any. -When a function expression is contextually typed by a function type *T*, the function expression is processed as if it had explicitly specified parameter type annotations as they exist in *T*. Parameters are matched by position and need not have matching names. If the function expression has fewer parameters than *T*, the additional parameters in *T* are ignored. If the function expression has more parameters than *T*, the additional parameters are all considered to have type Any. +Likewise, when a function expression with no return type annotation is contextually typed (section [4.19](#4.19)) by a function type *T* and a contextual signature *S* can be extracted from *T*, expressions in contained return statements (section [5.7](#5.7)) are contextually typed by the return type of *S*. -Furthermore, when a function expression has no return type annotation and is contextually typed by a function type *T*, expressions in contained return statements (section [5.7](#5.7)) are contextually typed by *T*'s return type. +A contextual signature *S* is extracted from a function type *T* as follows: + +* If *T* is a function type with exactly one call signature, and if that call signature is non-generic, *S* is that signature. +* If *T* is a union type, let *U* be the set of element types in *T* that have call signatures. If each type in *U* has exactly one call signature and that call signature is non-generic, and if all of the signatures are identical ignoring return types, then *S* is a signature with the same parameters and a union of the return types. +* Otherwise, no contextual signature can be extracted from *T* and *S* is undefined. + +In the example + +```TypeScript +var f: (s: string) => string = s => s.toLowerCase(); +``` + +the function expression is contextually typed by the type of 'f', and since the function expression has no type parameters or type annotations its parameter type information is extracted from the contextual type, thus inferring the type of 's' to be the String primitive type. ## 4.10 Property Access @@ -2687,7 +2746,7 @@ TypeScript extends the JavaScript expression grammar with the ability to assert A type assertion expression consists of a type enclosed in `<` and `>` followed by a unary expression. Type assertion expressions are purely a compile-time construct. Type assertions are *not* checked at run-time and have no impact on the emitted JavaScript (and therefore no run-time cost). The type and the enclosing `<` and `>` are simply removed from the generated code. -In a type assertion expression of the form `<` *T* `>` *e*, *e* is contextually typed (section [4.19](#4.19)) by *T* and the resulting type of* e* is required to be assignable to *T*, or *T* is required to be assignable to the widened form of the resulting type of *e*, or otherwise a compile-time error occurs. The type of the result is *T*. +In a type assertion expression of the form < *T* > *e*, *e* is contextually typed (section [4.19](#4.19)) by *T* and the resulting type of* e* is required to be assignable to *T*, or *T* is required to be assignable to the widened form of the resulting type of *e*, or otherwise a compile-time error occurs. The type of the result is *T*. Type assertions check for assignment compatibility in both directions. Thus, type assertions allow type conversions that *might* be correct, but aren't *known* to be correct. In the example @@ -2882,7 +2941,7 @@ An assignment of the form v = expr ``` -requires *v* to be classified as a reference (section [4.1](#4.1)). The *expr* expression is contextually typed (section [4.19](#4.19)) by the type of *v*, and the type of *expr* must be assignable to (section [3.10.4](#3.10.4)) the type of *v*, or otherwise a compile-time error occurs. The result is a value with the type of *expr*. +requires *v* to be classified as a reference (section [4.1](#4.1)) or as an assignment pattern (section [4.17.1](#4.17.1)). The *expr* expression is contextually typed (section [4.19](#4.19)) by the type of *v*, and the type of *expr* must be assignable to (section [3.10.4](#3.10.4)) the type of *v*, or otherwise a compile-time error occurs. The result is a value with the type of *expr*. A compound assignment of the form @@ -2896,7 +2955,78 @@ where ??= is one of the compound assignment operators *= /= %= += -= <<= >>= >>>= &= ^= |= ``` -is subject to the same requirements, and produces a value of the same type, as the corresponding non-compound operation. A compound assignment furthermore requires *v* to be classified as a reference (section [4.1](#4.1)) and the type of the non-compound operation to be assignable to the type of *v*. +is subject to the same requirements, and produces a value of the same type, as the corresponding non-compound operation. A compound assignment furthermore requires *v* to be classified as a reference (section [4.1](#4.1)) and the type of the non-compound operation to be assignable to the type of *v*. Note that *v* is not permitted to be an assignment pattern in a compound assignment. + +### 4.17.1 Destructuring Assignment + +A ***destructuring assignment*** is an assignment operation in which the left hand operand is a destructuring assignment pattern. + +  *AssignmentPattern:* +   *ObjectAssignmentPattern* +   *ArrayAssignmentPattern* + +  *ObjectBindingPattern:* +   `{` `}` +   `{` *AssignmentPropertyList* `,`*opt* `}` + +  *AssignmentPropertyList:* +   *AssignmentProperty* +   *AssignmentPropertyList* `,` *AssignmentProperty* + +  *AssignmentProperty:* +   *Identifier* *Initialiseropt* +   *PropertyName* `:` *LeftHandSideExpression* *Initialiseropt* +   *PropertyName* `:` *AssignmentPattern* *Initialiseropt* + +  *ArrayAssignmentPattern:* +   `[` *Elisionopt* *AssignmentRestElementopt* `]` +   `[` *AssignmentElementList* `]` +   `[` *AssignmentElementList* `,` *Elisionopt* *AssignmentRestElementopt* `]` + +  *AssignmentElementList:* +   *Elisionopt* *AssignmentElement* +   *AssignmentElementList* `,` *Elisionopt* *AssignmentElement* + +  *AssignmentElement:* +   *LeftHandSideExpression* *Initialiseropt* +   *AssignmentPattern* *Initialiseropt* + +  *AssignmentRestElement:* +   `...` *LeftHandSideExpression* + +In a destructuring assignment expression, the type of the expression on the right must be assignable to the assignment target on the left. An expression of type *S* is considered assignable to an assignment target *V* if one of the following is true: + +* *V* is variable and *S* is assignable to the type of *V*. +* *V* is an object assignment pattern and, for each assignment property *P* in *V*, + * *S* is the type Any, or + * *S* has an apparent property with the property name specified in *P* of a type that is assignable to the target given in *P*, or + * *P* specifies a numeric property name and *S* has a numeric index signature of a type that is assignable to the target given in *P*, or + * *S* has a string index signature of a type that is assignable to the target given in *P*. +* *V* is an array assignment pattern, *S* is the type Any or an array-like type (section [3.3.2](#3.3.2)), and, for each assignment element *E* in *V*, + * *S* is the type Any, or + * *S* is a tuple-like type (section [3.3.3](#3.3.3)) with a property named *N* of a type that is assignable to the target given in *E*, where *N* is the numeric index of *E* in the array assignment pattern, or + * *S* is not a tuple-like type and the numeric index signature type of *S* is assignable to the target given in *E*. + +In an assignment property or element that includes a default value, the type of the default value must be assignable to the target given in the assignment property or element. + +When the output target is ECMAScript 6 or higher, destructuring variable assignments remain unchanged in the emitted JavaScript code. + +When the output target is ECMAScript 3 or 5, destructuring variable assignments are rewritten to series of simple assignments. For example, the destructuring assignment + +```TypeScript +var x = 1; +var y = 2; +[x, y] = [y, x]; +``` + +is rewritten to the simple variable assignments + +```TypeScript +var x = 1; +var y = 2; +_a = [y, x], x = _a[0], y = _a[1]; +var _a; +``` ## 4.18 The Comma Operator @@ -2904,53 +3034,30 @@ The comma operator permits the operands to be of any type and produces a result ## 4.19 Contextually Typed Expressions -In certain situations, parameter and return types of function expressions are automatically inferred from the contexts in which the function expressions occur. For example, given the declaration +Type checking of an expression is improved in several contexts by factoring in the type of the destination of the value computed by the expression. In such situations, the expression is said to be ***contextually typed*** by the type of the destination. An expression is contextually typed in the following circumstances: -```TypeScript -var f: (s: string) => string; -``` - -the assignment - -```TypeScript -f = function(s) { return s.toLowerCase(); } -``` - -infers the type of the 's' parameter to be the String primitive type even though there is no type annotation to that effect. The function expression is said to be ***contextually typed*** by the variable to which it is being assigned. Contextual typing occurs in the following situations: - -* In variable, parameter, and member declarations with a type annotation and an initializer, the initializer expression is contextually typed by the type of the variable, parameter, or property. -* In return statements, if the containing function includes a return type annotation, return expressions are contextually typed by that return type. Otherwise, if the containing function is contextually typed by a type *T*, return expressions are contextually typed by *T*'s return type. -* In typed function calls, argument expressions are contextually typed by their parameter types. -* In type assertions, the expression is contextually typed by the indicated type. -* In || operator expressions without a contextual type, the right hand expression is contextually typed by the type of the left hand expression. -* In assignment expressions, the right hand expression is contextually typed by the type of the left hand expression. -* In contextually typed object literals, property assignments are contextually typed by their property types. -* In contextually typed array literals, element expressions are contextually typed by the array element type. -* In contextually typed || operator expressions, the operands are contextually typed as well. -* In contextually typed conditional operator expressions, the operands are contextually typed as well. - -Contextual typing of an expression *e* by a type *T* proceeds as follows: - -* If *e* is an *ObjectLiteral* and *T* is an object type, *e* is processed with the contextual type *T*, as described in section [4.5](#4.5). -* If *e* is an *ArrayLiteral* and *T* is an object type with a numeric index signature, *e* is processed with the contextual type *T*, as described in section [4.6](#4.6). -* If *e* is a *FunctionExpression* or *ArrowFunctionExpression* with no type parameters and no parameter type annotations, *T* is a function type with exactly one call signature and *T*'s call signature is non-generic, then any inferences made for type parameters referenced by the parameters of *T*'s call signature are fixed (section [4.12.2](#4.12.2)) and *e* is processed with the contextual type *T*, as described in section [4.9.3](#4.9.3). -* If *e* is a || operator expression and *T* is an object type, *e* is processed with the contextual type *T*, as described in section [4.15.7](#4.15.7). -* If *e* is a conditional operator expression and *T* is an object type, *e* is processed with the contextual type *T*, as described in section [4.16](#4.16). -* Otherwise, *e* is processed without a contextual type. - -The rules above require expressions be of the exact syntactic forms specified in order to be processed as contextually typed constructs. For example, given the declaration of the variable 'f' above, the assignment - -```TypeScript -f = s => s.toLowerCase(); -``` - -causes the function expression to be contextually typed, inferring the String primitive type for 's'. However, simply enclosing the construct in parentheses - -```TypeScript -f = (s => s.toLowerCase()); -``` - -causes the function expression to be processed without a contextual type, now inferring 's' and the result of the function to be of type Any as no type annotations are present. +* In a variable, parameter, binding property, binding element, or member declaration, an initializer expression is contextually typed by + * the type given in the declaration's type annotation, if any, or otherwise + * for a parameter, the contextual type for the declaration (section [4.9.3](#4.9.3)), if any, or otherwise + * the type implied by the binding pattern in the declaration (section [5.1.3](#5.1.3)), if any. +* In the body of a function declaration, function expression, arrow function, method declaration, or get accessor declaration that has a return type annotation, return expressions are contextually typed by the type given in the return type annotation. +* In the body of a function expression or arrow function that has no return type annotation, if the function expression or arrow function is contextually typed by a function type with exactly one call signature, and if that call signature is non-generic, return expressions are contextually typed by the return type of that call signature. +* In the body of a constructor declaration, return expressions are contextually typed by the containing class type. +* In the body of a get accessor with no return type annotation, if a matching set accessor exists and that set accessor has a parameter type annotation, return expressions are contextually typed by the type given in the set accessor's parameter type annotation. +* In a typed function call, argument expressions are contextually typed by their corresponding parameter types. +* In a contextually typed object literal, each property value expression is contextually typed by + * the type of the property with a matching name in the contextual type, if any, or otherwise + * for a numerically named property, the numeric index type of the contextual type, if any, or otherwise + * the string index type of the contextual type, if any. +* In a contextually typed array literal expression containing no spread elements, an element expression at index *N* is contextually typed by + * the type of the property with the numeric name *N* in the contextual type, if any, or otherwise + * the numeric index type of the contextual type, if any. +* In a contextually typed array literal expression containing one or more spread elements, an element expression at index *N* is contextually typed by the numeric index type of the contextual type, if any. +* In a contextually typed parenthesized expression, the contained expression is contextually typed by the same type. +* In a type assertion, the expression is contextually typed by the indicated type. +* In a || operator expression, if the expression is contextually typed, the operands are contextually typed by the same type. Otherwise, the right expression is contextually typed by the type of the left expression. +* In a contextually typed conditional operator expression, the operands are contextually typed by the same type. +* In an assignment expression, the right hand expression is contextually typed by the type of the left hand expression. In the following example @@ -2993,23 +3100,23 @@ function foo(x: number | string) { The type of a variable or parameter is narrowed in the following situations: -* In the true branch statement of an 'if' statement, the type of a variable or parameter is *narrowed* by any type guard in the 'if' condition *when true*, provided the true branch statement contains no assignments to the variable or parameter. -* In the false branch statement of an 'if' statement, the type of a variable or parameter is *narrowed* by any type guard in the 'if' condition *when false*, provided the false branch statement contains no assignments to the variable or parameter. -* In the true expression of a conditional expression, the type of a variable or parameter is *narrowed* by any type guard in the condition *when true*, provided the true expression contains no assignments to the variable or parameter. -* In the false expression of a conditional expression, the type of a variable or parameter is *narrowed* by any type guard in the condition *when false*, provided the false expression contains no assignments to the variable or parameter. -* In the right operand of a && operation, the type of a variable or parameter is *narrowed* by any type guard in the left operand *when true*, provided the right operand contains no assignments to the variable or parameter. -* In the right operand of a || operation, the type of a variable or parameter is *narrowed* by any type guard in the left operand *when false*, provided the right operand contains no assignments to the variable or parameter. +* In the true branch statement of an 'if' statement, the type of a variable or parameter is *narrowed* by a type guard in the 'if' condition *when true*, provided the true branch statement contains no assignments to the variable or parameter. +* In the false branch statement of an 'if' statement, the type of a variable or parameter is *narrowed* by a type guard in the 'if' condition *when false*, provided the false branch statement contains no assignments to the variable or parameter. +* In the true expression of a conditional expression, the type of a variable or parameter is *narrowed* by a type guard in the condition *when true*, provided the true expression contains no assignments to the variable or parameter. +* In the false expression of a conditional expression, the type of a variable or parameter is *narrowed* by a type guard in the condition *when false*, provided the false expression contains no assignments to the variable or parameter. +* In the right operand of a && operation, the type of a variable or parameter is *narrowed* by a type guard in the left operand *when true*, provided the right operand contains no assignments to the variable or parameter. +* In the right operand of a || operation, the type of a variable or parameter is *narrowed* by a type guard in the left operand *when false*, provided the right operand contains no assignments to the variable or parameter. A type guard is simply an expression that follows a particular pattern. The process of narrowing the type of a variable *x* by a type guard *when true* or *when false* depends on the type guard as follows: -* A type guard of the form `x instanceof C`, where *C* is of a subtype of the global type 'Function' and *C* has a property named 'prototype' - * *when true*, narrows the type of *x* to the type of the 'prototype' property in *C* provided it is a subtype of the type of *x*, or +* A type guard of the form `x instanceof C`, where *x* is not of type Any, *C* is of a subtype of the global type 'Function', and *C* has a property named 'prototype' + * *when true*, narrows the type of *x* to the type of the 'prototype' property in *C* provided it is a subtype of the type of *x*, or, if the type of *x* is a union type, removes from the type of *x* all constituent types that aren't subtypes of the type of the 'prototype' property in *C*, or * *when false*, has no effect on the type of *x*. * A type guard of the form `typeof x === s`, where *s* is a string literal with the value 'string', 'number', or 'boolean', - * *when true*, narrows the type of *x* to the given primitive type, or + * *when true*, narrows the type of *x* to the given primitive type provided it is a subtype of the type of *x*, or, if the type of *x* is a union type, removes from the type of *x* all constituent types that aren't subtypes of the given primitive type, or * *when false*, removes the primitive type from the type of *x*. * A type guard of the form `typeof x === s`, where *s* is a string literal with any value but 'string', 'number', or 'boolean', - * *when true*, removes the primitive types string, number, and boolean from the type of *x*, or + * *when true*, if *x* is a union type, removes from the type of *x* all constituent types that are subtypes of the string, number, or boolean primitive type, or * *when false*, has no effect on the type of *x*. * A type guard of the form `typeof x !== s`, where *s* is a string literal, * *when true*, narrows the type of x by `typeof x === s` *when false*, or @@ -3025,10 +3132,7 @@ A type guard is simply an expression that follows a particular pattern. The proc * *when false*, narrows the type of *x* by *expr1* *when false* and then by *expr2* *when false*. * A type guard of any other form has no effect on the type of *x*. -A primitive type *P* is removed from a type *T* as follows: - -* If *T* is a union type *P* | *T1* | *T2* | … | *Tn*, the result is the type *T1* | *T2* | … | *Tn*. -* Otherwise, the result is *T*. +In the rules above, when a narrowing operation would remove all constituent types from a union type, the operation has no effect on the union type. Note that type guards affect types of variables and parameters only and have no effect on members of objects such as properties. Also note that it is possible to defeat a type guard by calling a function that changes the type of the guarded variable. @@ -3040,7 +3144,18 @@ function isLongString(obj: any) { } ``` -the 'obj' parameter has type string in the right operand of the && operator. +the `obj` parameter has type `string` in the right operand of the && operator. + +In the example + +```TypeScript +function processValue(value: number | (() => number)) { + var x = typeof value !== "number" ? value() : value; + // Process number in x +} +``` + +the value parameter has type `() => number` in the first conditional expression and type `number` in the second conditional expression, and the inferred type of x is `number`. In the example @@ -3055,18 +3170,21 @@ function f(x: string | number | boolean) { } ``` -the type of 'x' is string | number | boolean in left operand of the || operator, number | boolean in the right operand of the || operator, string | number in the first branch of the 'if' statement, and boolean in the second branch of the 'if' statement. +the type of x is `string | number | boolean` in the left operand of the || operator, `number | boolean` in the right operand of the || operator, `string | number` in the first branch of the if statement, and `boolean` in the second branch of the if statement. In the example ```TypeScript -function processData(data: string | { (): string }) { - var d = typeof data !== "string" ? data() : data; - // Process string in d +class C { + data: string | string[]; + getData() { + var data = this.data; + return typeof data === "string" ? data : data.join(" "); + } } ``` -the inferred type of 'd' is string. +the type of the `data` variable is `string` in the first conditional expression and `string[]` in the second conditional expression, and the inferred type of `getData` is `string`. Note that the `data` property must be copied to a local variable for the type guard to have an effect. In the example @@ -3075,12 +3193,12 @@ class NamedItem { name: string; } -function getName(obj: any) { +function getName(obj: Object) { return obj instanceof NamedItem ? obj.name : "unknown"; } ``` -the inferred type of the 'getName' function is string. +the type of `obj` is narrowed to `NamedItem` in the first condtional expression, and the inferred type of the `getName` function is `string`.
@@ -3090,26 +3208,37 @@ This chapter describes the static type checking TypeScript provides for JavaScri ##
5.1 Variable Statements -Variable statements are extended to include optional type annotations. +Variable statements are extended to include optional type annotations and ECMAScript 6 destructuring declarations.   *VariableDeclaration:* *( Modified )* -   *Identifier* *TypeAnnotationopt* *Initialiseropt* +   *SimpleVariableDeclaration* +   *DestructuringVariableDeclaration* -  *VariableDeclarationNoIn:* *( Modified )* -   *Identifier* *TypeAnnotationopt* *InitialiserNoInopt* +A variable declaration is either a simple variable declaration or a destructuring variable declaration. + +### 5.1.1 Simple Variable Declarations + +A ***simple variable declaration*** introduces a single named variable and optionally assigns it an initial value. + +  *SimpleVariableDeclaration:* +   *Identifier* *TypeAnnotationopt* *Initialiseropt*   *TypeAnnotation:*    `:` *Type* -A variable declaration introduces a variable with the given name in the containing declaration space. The type associated with a variable is determined as follows: +The type *T* of a variable introduced by a simple variable declaration is determined as follows: -* If the declaration includes a type annotation, the stated type becomes the type of the variable. If an initializer is present, the initializer expression is contextually typed (section [4.19](#4.19)) by the stated type and must be assignable to the stated type, or otherwise a compile-time error occurs. -* If the declaration includes an initializer but no type annotation, and if the initializer doesn't directly or indirectly reference the variable, the widened type (section [3.11](#3.11)) of the initializer expression becomes the type of the variable. If the initializer directly or indirectly references the variable, the type of the variable becomes the Any type. -* If the declaration includes neither a type annotation nor an initializer, the type of the variable becomes the Any type. +* If the declaration includes a type annotation, *T* is that type. +* Otherwise, if the declaration includes an initializer expression, *T* is the widened form (section [3.11](#3.11)) of the type of the initializer expression. +* Otherwise, *T* is the Any type. + +When a variable declaration specifies both a type annotation and an initializer expression, the type of the initializer expression is required to be assignable to (section [3.10.4](#3.10.4)) the type given in the type annotation. 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. -Below are some examples of variable declarations and their associated types. +When a variable declaration has a type annotation, it is an error for that type annotation to use the `typeof` operator to reference the variable being declared. + +Below are some examples of simple variable declarations and their associated types. ```TypeScript var a; // any @@ -3141,6 +3270,167 @@ var d: { x: number; y: number; } = { x: 0, y: undefined }; var e = <{ x: number; y: number; }> { x: 0, y: undefined }; ``` +### 5.1.2 Destructuring Variable Declarations + +A ***destructuring variable declaration*** introduces zero or more named variables and initializes them with values extracted from properties of an object or elements of an array. + +  *DestructuringVariableDeclaration:* +   *BindingPattern* *TypeAnnotationopt* *Initialiser* + +  *BindingPattern:* +   *ObjectBindingPattern* +   *ArrayBindingPattern* + +  *ObjectBindingPattern:* +   `{` `}` +   `{` *BindingPropertyList* `,`*opt* `}` + +  *BindingPropertyList:* +   *BindingProperty* +   *BindingPropertyList* `,` *BindingProperty* + +  *BindingProperty:* +   *Identifier* *Initialiseropt* +   *PropertyName* `:` *Identifier* *Initialiseropt* +   *PropertyName* `:` *BindingPattern* *Initialiseropt* + +  *ArrayBindingPattern:* +   `[` *Elisionopt* *BindingRestElementopt* `]` +   `[` *BindingElementList* `]` +   `[` *BindingElementList* `,` *Elisionopt* *BindingRestElementopt* `]` + +  *BindingElementList:* +   *Elisionopt* *BindingElement* +   *BindingElementList* `,` *Elisionopt* *BindingElement* + +  *BindingElement:* +   *Identifier* *Initialiseropt* +   *BindingPattern* *Initialiseropt* + +  *BindingRestElement:* +   `...` *Identifier* + +Each binding property or element that specifies an identifier introduces a variable by that name. The type of the variable is the widened form (section [3.11](#3.11)) of the type associated with the binding property or element, as defined in the following. + +The type *T* associated with a destructuring variable declaration is determined as follows: + +* If the declaration includes a type annotation, *T* is that type. +* Otherwise, if the declaration includes an initializer expression, *T* is the type of that initializer expression. +* Otherwise, *T* is the Any type. + +The type *T* associated with a binding property is determined as follows: + +* Let *S* be the type associated with the immediately containing destructuring variable declaration, binding property, or binding element. +* If *S* is the Any type: + * If the binding property specifies an initializer expression, *T* is the type of that initializer expression. + * Otherwise, *T* is the Any type. +* Let *P* be the property name specified in the binding property. +* If *S* has an apparent property with the name *P*, *T* is the type of that property. +* Otherwise, if *S* has a numeric index signature and *P* is a numerical name, *T* is the type of the numeric index signature. +* Otherwise, if *S* has a string index signature, *T* is the type of the string index signature. +* Otherwise, no type is associated with the binding property and an error occurs. + +The type *T* associated with a binding element is determined as follows: + +* Let *S* be the type associated with the immediately containing destructuring variable declaration, binding property, or binding element. +* If *S* is the Any type: + * If the binding element specifies an initializer expression, *T* is the type of that initializer expression. + * Otherwise, *T* is the Any type. +* If *S* is not an array-like type (section [3.3.2](#3.3.2)), no type is associated with the binding property and an error occurs. +* If the binding element is a rest element, *T* is an array type with an element type *E*, where *E* is the type of the numeric index signature of *S*. +* Otherwise, if *S* is a tuple-like type (section [3.3.3](#3.3.3)): + * Let *N* be the zero-based index of the binding element in the array binding pattern. + * If *S* has a property with the numerical name *N*, *T* is the type of that property. + * Otherwise, no type is associated with the binding element and an error occurs. +* Otherwise, if *S* has a numeric index signature, *T* is the type of the numeric index signature. +* Otherwise, no type is associated with the binding element and an error occurs. + +When a destructuring variable declaration, binding property, or binding element specifies an initializer expression, the type of the initializer expression is required to be assignable to the widened form of the type associated with the destructuring variable declaration, binding property, or binding element. + +When the output target is ECMAScript 6 or higher, except for removing the optional type annotation, destructuring variable declarations remain unchanged in the emitted JavaScript code. + +When the output target is ECMAScript 3 or 5, destructuring variable declarations are rewritten to simple variable declarations. For example, an object destructuring declaration of the form + +```TypeScript +var { x, p: y, q: z = false } = getSomeObject(); +``` + +is rewritten to the simple variable declarations + +```TypeScript +var _a = getSomeObject(), + x = _a.x, + y = _a.p, + _b = _a.q, + z = _b === void 0 ? false : _b; +``` + +The '_a' and '_b' temporary variables exist to ensure the assigned expression is evaluated only once, and the expression 'void 0' simply denotes the JavaScript value 'undefined'. + +Similarly, an array destructuring declaration of the form + +```TypeScript +var [x, y, z = 10] = getSomeArray(); +``` + +is rewritten to the simple variable declarations + +```TypeScript +var _a = getSomeArray(), + x = _a[0], + y = _a[1], + _b = _a[2], + z = _b === void 0 ? 10 : _b; +``` + +Combining both forms of destructuring, the example + +```TypeScript +var { x, p: [y, z = 10] = getSomeArray() } = getSomeObject(); +``` + +is rewritten to + +```TypeScript +var _a = getSomeObject(), + x = _a.x, + _b = _a.p, + _c = _b === void 0 ? getSomeArray() : _b, + y = _c[0], + _d = _c[1], + z = _d === void 0 ? 10 : _d; +``` + +### 5.1.3 Implied Type + +A variable, parameter, binding property, or binding element declaration that specifies a binding pattern has an ***implied type*** which is determined as follows: + +* If the declaration specifies an object binding pattern, the implied type is an object type with a set of properties corresponding to the specified binding property declarations. The type of each property is the type implied by its binding property declaration, and a property is optional when its binding property declaration specifies an initializer expression. +* If the declaration specifies an array binding pattern without a rest element, the implied type is a tuple type with elements corresponding to the specified binding element declarations. The type of each element is the type implied by its binding element declaration. +* If the declaration specifies an array binding pattern with a rest element, the implied type is an array type with an element type of Any. + +The implied type of a binding property or binding element declaration is + +* the type of the declaration's initializer expression, if any, or otherwise +* the implied type of the binding pattern specified in the declaration, if any, or otherwise +* the type Any. + +In the example + +```TypeScript +function f({ a, b = "hello", c = 1 }) { ... } +``` + +the implied type of the binding pattern in the function's parameter is '{ a: any; b?: string; c?: number; }'. Since the parameter has no type annotation, this becomes the type of the parameter. + +In the example + +```TypeScript +var [a, b, c] = [1, "hello", true]; +``` + +the array literal initializer expression is contextually typed by the implied type of the binding pattern, specifically the tuple type '[any, any, any]'. Because the contextual type is a tuple type, the resulting type of the array literal is the tuple type '[number, string, boolean]', and the destructuring declaration thus gives the types number, string, and boolean to a, b, and c respectively. + ## 5.2 If, Do, and While Statements Expressions controlling 'if', 'do', and 'while' statements can be of any type (and not just type Boolean). @@ -3304,7 +3594,7 @@ In the signature of a function implementation, a parameter can be marked optiona Initializer expressions are evaluated in the scope of the function body but are not permitted to reference local variables and are only permitted to access parameters that are declared to the left of the parameter they initialize, unless the parameter reference occurs in a nested function expression. -For each parameter with an initializer, a statement that substitutes the default value for an omitted argument is included in the generated JavaScript, as described in section [6.5](#6.5). The example +For each parameter with an initializer, a statement that substitutes the default value for an omitted argument is included in the generated JavaScript, as described in section [6.6](#6.6). The example ```TypeScript function strange(x: number, y = x * 2, z = x + y) { @@ -3333,7 +3623,65 @@ function f(a = x) { the local variable 'x' is in scope in the parameter initializer (thus hiding the outer 'x'), but it is an error to reference it because it will always be uninitialized at the time the parameter initializer is evaluated. -## 6.4 Generic Functions +## 6.4 Destructuring Parameter Declarations + +Parameter declarations can specify binding patterns (section [3.8.2.2](#3.8.2.2)) and are then called ***destructuring parameter declarations***. Similar to a destructuring variable declaration (section [5.1.2](#5.1.2)), a destructuring parameter declaration introduces zero or more named locals and initializes them with values extracted from properties or elements of the object or array passed as an argument for the parameter. + +The type of local introduced in a destructuring parameter declaration is determined in the same manner as a local introduced by a destructuring variable declaration, except the type *T* associated with a destructuring parameter declaration is determined as follows: + +* If the declaration includes a type annotation, *T* is that type. +* Otherwise, if the declaration includes an initializer expression, *T* is the widened form (section [3.11](#3.11)) of the type of the initializer expression. +* Otherwise, if the declaration specifies a binding pattern, *T* is the implied type of that binding pattern (section [5.1.3](#5.1.3)). +* Otherwise, if the parameter is a rest parameter, *T* is `any[]`. +* Otherwise, *T* is `any`. + +When the output target is ECMAScript 6 or higher, except for removing the optional type annotation, destructuring parameter declarations remain unchanged in the emitted JavaScript code. When the output target is ECMAScript 3 or 5, destructuring parameter declarations are rewritten to local variable declarations. + +The example + +```TypeScript +function drawText({ text = "", location: [x, y] = [0, 0], bold = false }) { + // Draw text +} +``` + +declares a function `drawText` that takes a single parameter of the type + +```TypeScript +{ text?: string; location?: [number, number]; bold?: boolean; } +``` + +When the output target is ECMAScript 3 or 5, the function is rewritten to + +```TypeScript +function drawText(_a) { + var _b = _a.text, + text = _b === void 0 ? "" : _b, + _c = _a.location, + _d = _c === void 0 ? [0, 0] : _c, + x = _d[0], + y = _d[1], + _e = _a.bold, + bold = _e === void 0 ? false : _e; + // Draw text +} +``` + +Destructuring parameter declarations do not permit type annotations on the individual binding patterns, as such annotations would conflict with the already established meaning of colons in object literals. Type annotations must instead be written on the top-level parameter declaration. For example + +```TypeScript +interface DrawTextInfo { + text?: string; + location?: [number, number]; + bold?: boolean; +} + +function drawText({ text, location: [x, y], bold }: DrawTextInfo) { + // Draw text +} +``` + +## 6.5 Generic Functions A function implementation may include type parameters in its signature (section [3.8.2.1](#3.8.2.1)) and is then called a ***generic function***. Type parameters provide a mechanism for expressing relationships between parameter and return types in call operations. Type parameters have no run-time representation—they are purely a compile-time construct. @@ -3368,7 +3716,7 @@ class Person { the type argument to 'compare' is automatically inferred to be the String type because the two arguments are strings. -## 6.5 Code Generation +## 6.6 Code Generation A function declaration generates JavaScript code that is equivalent to: @@ -3543,7 +3891,7 @@ class Location { } ``` -In the above example, 'SelectableControl' contains all of the members of 'Control', including the private 'state' property. Since 'state' is a private member it is only possible for descendants of 'Control' to implement 'SelectableControl'. This is because only descendants of 'Control' will have a 'state' private member that originates in the same declaration, which is a requirement for private members to be compatible (section [0](#0)). +In the above example, 'SelectableControl' contains all of the members of 'Control', including the private 'state' property. Since 'state' is a private member it is only possible for descendants of 'Control' to implement 'SelectableControl'. This is because only descendants of 'Control' will have a 'state' private member that originates in the same declaration, which is a requirement for private members to be compatible (section [3.10](#3.10)). Within the 'Control' class it is possible to access the 'state' private member through an instance of 'SelectableControl'. Effectively, a 'SelectableControl' acts like a 'Control' that is known to have a 'select' method. The 'Button' and 'TextBox' classes are subtypes of 'SelectableControl' (because they both inherit from 'Control' and have a 'select' method), but the 'Image' and 'Location' classes are not. @@ -4183,7 +4531,7 @@ var = (function () { *ConstructorParameters* is a comma separated list of the constructor's parameter names. -*DefaultValueAssignments* is a sequence of default property value assignments corresponding to those generated for a regular function declaration, as described in section [6.5](#6.5). +*DefaultValueAssignments* is a sequence of default property value assignments corresponding to those generated for a regular function declaration, as described in section [6.6](#6.6). *ParameterPropertyAssignments* is a sequence of assignments, one for each parameter property declaration in the constructor, in order they are declared, of the form @@ -4223,7 +4571,7 @@ and static member function declaration generates a statement of the form } ``` -where *MemberName* is the name of the member function, and *FunctionParameters*, *DefaultValueAssignments*, and *FunctionStatements* correspond to those generated for a regular function declaration, as described in section [6.5](#6.5). +where *MemberName* is the name of the member function, and *FunctionParameters*, *DefaultValueAssignments*, and *FunctionStatements* correspond to those generated for a regular function declaration, as described in section [6.6](#6.6). A get or set instance member accessor declaration, or a pair of get and set instance member accessor declarations with the same name, generates a statement of the form @@ -4351,12 +4699,14 @@ An enum type is a distinct subtype of the Number primitive type with an associat An enum declaration declares an ***enum type*** and an ***enum object*** in the containing module.   *EnumDeclaration:* -   `enum` *Identifier* `{` *EnumBodyopt* `}` +   `const`*opt* `enum` *Identifier* `{` *EnumBodyopt* `}` The enum type and enum object declared by an *EnumDeclaration* both have the name given by the *Identifier* of the declaration. The enum type is a distinct subtype of the Number primitive type. The enum object is a variable of an anonymous object type containing a set of properties, all of the enum type, corresponding to the values declared for the enum type in the body of the declaration. The enum object's type furthermore includes a numeric index signature with the signature '[x: number]: string'. The *Identifier* of an enum declaration may not be one of the predefined type names (section [3.7.1](#3.7.1)). +When an enum declaration includes a `const` modifier it is said to be a constant enum declaration. The members of a constant enum declaration must all have constant values that can be computed at compile time. Constant enum declarations are discussed in section [9.4](#9.4). + The example ```TypeScript @@ -4374,7 +4724,7 @@ var Color: { }; ``` -The numeric index signature reflects a "reverse mapping" that is automatically generated in every enum object, as described in section [9.4](#9.4). The reverse mapping provides a convenient way to obtain the string representation of an enum value. For example +The numeric index signature reflects a "reverse mapping" that is automatically generated in every enum object, as described in section [9.5](#9.5). The reverse mapping provides a convenient way to obtain the string representation of an enum value. For example ```TypeScript var c = Color.Red; @@ -4385,43 +4735,37 @@ console.log(Color[c]); // Outputs "Red" The body of an enum declaration defines zero or more enum members which are the named values of the enum type. Each enum member has an associated numeric value of the primitive type introduced by the enum declaration. -  *EnumBody*: -   *ConstantEnumMembers* `,`*opt* -   *ConstantEnumMembers* `,` *EnumMemberSections* `,`*opt* -   *EnumMemberSections* `,`*opt* +  *EnumBody:* +   *EnumMemberList* `,`*opt* -  *ConstantEnumMembers:* +  *EnumMemberList:* +   *EnumMember* +   *EnumMemberList* `,` *EnumMember* + +  *EnumMember:*    *PropertyName* -   *ConstantEnumMembers* `,` *PropertyName* +   *PropertyName* = *EnumValue* -  *EnumMemberSections:* -   *EnumMemberSection* -   *EnumMemberSections* `,` *EnumMemberSection* - -  *EnumMemberSection:* -   *ConstantEnumMemberSection* -   *ComputedEnumMember* - -  *ConstantEnumMemberSection:* -   *PropertyName* `=` *ConstantEnumValue* -   *PropertyName* `=` *ConstantEnumValue* `,` *ConstantEnumMembers* - -  *ConstantEnumValue:* -   *SignedInteger* -   *HexIntegerLiteral* - -  *ComputedEnumMember:* -   *PropertyName* `=` *AssignmentExpression* +  *EnumValue:* +   *AssignmentExpression* Enum members are either ***constant members*** or ***computed members***. Constant members have known constant values that are substituted in place of references to the members in the generated JavaScript code. Computed members have values that are computed at run-time and not known at compile-time. No substitution is performed for references to computed members. -The body of an enum declaration consists of an optional *ConstantEnumMembers* production followed by any number of *ConstantEnumMemberSection* or *ComputedEnumMember* productions. +An enum member is classified as follows: -* If present, the initial *ConstantEnumMembers* production introduces a series of constant members with consecutive integral values starting at the value zero. -* A *ConstantEnumMemberSection* introduces one or more constant members with consecutive integral values starting at the specified constant value. -* A *ComputedEnumMember* introduces a computed member with a value computed by an expression. +* If the member declaration specifies no value, the member is considered a constant enum member. If the member is the first member in the enum declaration, it is assigned the value zero. Otherwise, it is assigned the value of the immediately preceding member plus one, and an error occurs if the immediately preceding member is not a constant enum member. +* If the member declaration specifies a value that can be classified as a constant enum expression (as defined below), the member is considered a constant enum member. +* Otherwise, the member is considered a computed enum member. -Expressions specified for computed members must produce values of type Any, the Number primitive type, or the enum type itself. +Enum value expressions must be of type Any, the Number primitive type, or the enum type itself. + +A ***constant enum expression*** is a subset of the expression grammar that can be evaluated fully at compile time. An expression is considered a constant enum expression if it is one of the following: + +* A numeric literal. +* An identifier or property access that denotes a previously declared member in the same constant enum declaration. +* A parenthesized constant enum expression. +* A +, –, or ~ unary operator applied to a constant enum expression. +* A +, –, *, /, %, <<, >>, >>>, &, ^, or | operator applied to two constant enum expressions. In the example @@ -4450,7 +4794,7 @@ enum Style { } ``` -the first four members are constant members and the last two are computed members. Note that computed member declarations can reference other enum members without qualification. Also, because enums are subtypes of the Number primitive type, numeric operators, such as the bitwise OR operator, can be used to compute enum values. +all members are constant members. Note that enum member declarations can reference other enum members without qualification. Also, because enums are subtypes of the Number primitive type, numeric operators, such as the bitwise OR operator, can be used to compute enum values. ## 9.3 Declaration Merging @@ -4458,7 +4802,29 @@ Enums are "open-ended" and enum declarations with the same qualified name relati It isn't possible for one enum declaration to continue the automatic numbering sequence of another, and when an enum type has multiple declarations, only one declaration is permitted to omit a value for the first member. -## 9.4 Code Generation +When enum declarations are merged, they must either all specify a `const` modifier or all specify no `const` modifier. + +## 9.4 Constant Enum Declarations + +An enum declaration that specifies a `const` modifier is a ***constant enum declaration***. In a constant enum declaration, all members must have constant values and it is an error for a member declaration to specify an expression that isn't classified as a constant enum expression. + +Unlike regular enum declarations, constant enum declarations are completely erased in the emitted JavaScript code. For this reason, it is an error to reference a constant enum object in any other context than a property access that selects one of the enum's members. For example: + +```TypeScript +const enum Comparison { + LessThan = -1, + EqualTo = 0, + GreaterThan = 1 +} + +var x = Comparison.EqualTo; // Ok, replaced with 0 in emitted code +var y = Comparison[Comparison.EqualTo]; // Error +var z = Comparison; // Error +``` + +The entire const enum declaration is erased in the emitted JavaScript code. Thus, the only permitted references to the enum object are those that are replaced with an enum member value. + +## 9.5 Code Generation An enum declaration generates JavaScript equivalent to the following: @@ -5119,23 +5485,17 @@ An ambient class declaration declares a class instance type and a constructor fu ### 12.1.4 Ambient Enum Declarations -An ambient enum declaration declares an enum type and an enum object in the containing module. +An ambient enum is grammatically equivalent to a non-ambient enum declaration.   *AmbientEnumDeclaration:* -   `enum` *Identifier* `{` *AmbientEnumBodyopt* `}` +   *EnumDeclaration* -  *AmbientEnumBody:* -   *AmbientEnumMemberList* `,`*opt* +Ambient enum declarations differ from non-ambient enum declarations in two ways: -  *AmbientEnumMemberList:* -   *AmbientEnumMember* -   *AmbientEnumMemberList* `,` *AmbientEnumMember* +* In ambient enum declarations, all values specified in enum member declarations must be classified as constant enum expressions. +* In ambient enum declarations that specify no `const` modifier, enum member declarations that omit a value are considered computed members (as opposed to having auto-incremented values assigned). -  *AmbientEnumMember:* -   *PropertyName* -   *PropertyName* = *ConstantEnumValue* - -An *AmbientEnumMember* that includes a *ConstantEnumValue* value is considered a constant member. An *AmbientEnumMember* with no *ConstantEnumValue* value is considered a computed member. +Ambient enum declarations are otherwise processed in the same manner as non-ambient enum declarations. ### 12.1.5 Ambient Module Declarations @@ -5167,7 +5527,7 @@ Except for *ImportDeclarations*, *AmbientModuleElements* always declare exported An *AmbientExternalModuleDeclaration* declares an external module. This type of declaration is permitted only at the top level in a source file that contributes to the global module (section [11.1](#11.1)). The *StringLiteral* must specify a top-level external module name. Relative external module names are not permitted.   *AmbientExternalModuleDeclaration:* -   `module` *StringLiteral* `{`  *AmbientExternalModuleBody* `}` +   `declare` `module` *StringLiteral* `{`  *AmbientExternalModuleBody* `}`   *AmbientExternalModuleBody:*    *AmbientExternalModuleElementsopt* @@ -5394,6 +5754,15 @@ This appendix contains a summary of the grammar found in the main document. As d   *SetAccessor:*    `set` *PropertyName* `(` *Identifier* *TypeAnnotationopt* `)` `{` *FunctionBody* `}` +  *ElementList:* *( Modified )* +   *Elisionopt* *AssignmentExpression* +   *Elisionopt* *SpreadElement* +   *ElementList* `,` *Elisionopt* *AssignmentExpression* +   *ElementList* `,` *Elisionopt* *SpreadElement* + +  *SpreadElement:* +   `...` *AssignmentExpression* +   *CallExpression:* *( Modified )*    …    `super` `(` *ArgumentListopt* `)` @@ -5424,14 +5793,51 @@ This appendix contains a summary of the grammar found in the main document. As d ## A.3 Statements   *VariableDeclaration:* *( Modified )* -   *Identifier* *TypeAnnotationopt* *Initialiseropt* +   *SimpleVariableDeclaration* +   *DestructuringVariableDeclaration* -  *VariableDeclarationNoIn:* *( Modified )* -   *Identifier* *TypeAnnotationopt* *InitialiserNoInopt* +  *SimpleVariableDeclaration:* +   *Identifier* *TypeAnnotationopt* *Initialiseropt*   *TypeAnnotation:*    `:` *Type* +  *DestructuringVariableDeclaration:* +   *BindingPattern* *TypeAnnotationopt* *Initialiser* + +  *BindingPattern:* +   *ObjectBindingPattern* +   *ArrayBindingPattern* + +  *ObjectBindingPattern:* +   `{` `}` +   `{` *BindingPropertyList* `,`*opt* `}` + +  *BindingPropertyList:* +   *BindingProperty* +   *BindingPropertyList* `,` *BindingProperty* + +  *BindingProperty:* +   *Identifier* *Initialiseropt* +   *PropertyName* `:` *Identifier* *Initialiseropt* +   *PropertyName* `:` *BindingPattern* *Initialiseropt* + +  *ArrayBindingPattern:* +   `[` *Elisionopt* *BindingRestElementopt* `]` +   `[` *BindingElementList* `]` +   `[` *BindingElementList* `,` *Elisionopt* *BindingRestElementopt* `]` + +  *BindingElementList:* +   *Elisionopt* *BindingElement* +   *BindingElementList* `,` *Elisionopt* *BindingElement* + +  *BindingElement:* +   *Identifier* *Initialiseropt* +   *BindingPattern* *Initialiseropt* + +  *BindingRestElement:* +   `...` *Identifier* + ## A.4 Functions   *FunctionDeclaration:* *( Modified )* @@ -5535,35 +5941,21 @@ This appendix contains a summary of the grammar found in the main document. As d ## A.7 Enums   *EnumDeclaration:* -   `enum` *Identifier* `{` *EnumBodyopt* `}` +   `const`*opt* `enum` *Identifier* `{` *EnumBodyopt* `}` -  *EnumBody*: -   *ConstantEnumMembers* `,`*opt* -   *ConstantEnumMembers* `,` *EnumMemberSections* `,`*opt* -   *EnumMemberSections* `,`*opt* +  *EnumBody:* +   *EnumMemberList* `,`*opt* -  *ConstantEnumMembers:* +  *EnumMemberList:* +   *EnumMember* +   *EnumMemberList* `,` *EnumMember* + +  *EnumMember:*    *PropertyName* -   *ConstantEnumMembers* `,` *PropertyName* +   *PropertyName* = *EnumValue* -  *EnumMemberSections:* -   *EnumMemberSection* -   *EnumMemberSections* `,` *EnumMemberSection* - -  *EnumMemberSection:* -   *ConstantEnumMemberSection* -   *ComputedEnumMember* - -  *ConstantEnumMemberSection:* -   *PropertyName* `=` *ConstantEnumValue* -   *PropertyName* `=` *ConstantEnumValue* `,` *ConstantEnumMembers* - -  *ConstantEnumValue:* -   *SignedInteger* -   *HexIntegerLiteral* - -  *ComputedEnumMember:* -   *PropertyName* `=` *AssignmentExpression* +  *EnumValue:* +   *AssignmentExpression* ## A.8 Internal Modules @@ -5682,18 +6074,7 @@ This appendix contains a summary of the grammar found in the main document. As d    *AccessibilityModifieropt* `static`*opt* *PropertyName* *CallSignature* `;`   *AmbientEnumDeclaration:* -   `enum` *Identifier* `{` *AmbientEnumBodyopt* `}` - -  *AmbientEnumBody:* -   *AmbientEnumMemberList* `,`*opt* - -  *AmbientEnumMemberList:* -   *AmbientEnumMember* -   *AmbientEnumMemberList* `,` *AmbientEnumMember* - -  *AmbientEnumMember:* -   *PropertyName* -   *PropertyName* = *ConstantEnumValue* +   *EnumDeclaration*   *AmbientModuleDeclaration:*    `module` *IdentifierPath* `{` *AmbientModuleBody* `}` @@ -5715,7 +6096,7 @@ This appendix contains a summary of the grammar found in the main document. As d    `export`*opt* *ImportDeclaration*   *AmbientExternalModuleDeclaration:* -   `module` *StringLiteral* `{`  *AmbientExternalModuleBody* `}` +   `declare` `module` *StringLiteral* `{`  *AmbientExternalModuleBody* `}`   *AmbientExternalModuleBody:*    *AmbientExternalModuleElementsopt* diff --git a/package.json b/package.json index a52067a3d08..2bd89706606 100644 --- a/package.json +++ b/package.json @@ -1,46 +1,46 @@ { - "name": "typescript", - "author": "Microsoft Corp.", - "homepage": "http://typescriptlang.org/", - "version": "1.4.0", - "licenses": [ - { - "type": "Apache License 2.0", - "url": "https://github.com/Microsoft/TypeScript/blob/master/LICENSE.txt" - } - ], - "description": "TypeScript is a language for application scale JavaScript development", - "keywords": [ - "TypeScript", - "Microsoft", - "compiler", - "language", - "javascript" - ], - "bugs": { - "url" : "https://github.com/Microsoft/TypeScript/issues" - }, - "repository" : { - "type" : "git", - "url" : "https://github.com/Microsoft/TypeScript.git" - }, - "preferGlobal" : true, - "main" : "./bin/typescriptServices.js", - "bin" : { - "tsc" : "./bin/tsc" - }, - "engines" : { - "node" : ">=0.8.0" - }, - "devDependencies": { - "jake" : "latest", - "mocha" : "latest", - "chai" : "latest", - "browserify" : "latest", - "istanbul": "latest", - "codeclimate-test-reporter": "latest" - }, - "scripts": { - "test": "jake generate-code-coverage" - } + "name": "typescript", + "author": "Microsoft Corp.", + "homepage": "http://typescriptlang.org/", + "version": "1.5.0", + "licenses": [ + { + "type": "Apache License 2.0", + "url": "https://github.com/Microsoft/TypeScript/blob/master/LICENSE.txt" + } + ], + "description": "TypeScript is a language for application scale JavaScript development", + "keywords": [ + "TypeScript", + "Microsoft", + "compiler", + "language", + "javascript" + ], + "bugs": { + "url": "https://github.com/Microsoft/TypeScript/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/Microsoft/TypeScript.git" + }, + "preferGlobal": true, + "main": "./bin/typescriptServices.js", + "bin": { + "tsc": "./bin/tsc" + }, + "engines": { + "node": ">=0.8.0" + }, + "devDependencies": { + "jake": "latest", + "mocha": "latest", + "chai": "latest", + "browserify": "latest", + "istanbul": "latest", + "codeclimate-test-reporter": "latest" + }, + "scripts": { + "test": "jake generate-code-coverage" + } } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ed89032b781..f44c9b118f8 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1069,7 +1069,7 @@ module ts { * Enclosing declaration is optional when we don't want to get qualified name in the enclosing declaration scope * Meaning needs to be specified if the enclosing declaration is given */ - function buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void { + function buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags, typeFlags?: TypeFormatFlags): void { var parentSymbol: Symbol; function appendParentTypeArgumentsAndSymbolName(symbol: Symbol): void { if (parentSymbol) { @@ -1131,11 +1131,12 @@ module ts { } } - // Get qualified name - if (enclosingDeclaration && - // TypeParameters do not need qualification - !(symbol.flags & SymbolFlags.TypeParameter)) { - + // Get qualified name if the symbol is not a type parameter + // and there is an enclosing declaration or we specifically + // asked for it + var isTypeParameter = symbol.flags & SymbolFlags.TypeParameter; + var typeFormatFlag = TypeFormatFlags.UseFullyQualifiedType & typeFlags; + if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { walkSymbol(symbol, meaning); return; } @@ -1158,7 +1159,8 @@ module ts { writeTypeReference(type, flags); } else if (type.flags & (TypeFlags.Class | TypeFlags.Interface | TypeFlags.Enum | TypeFlags.TypeParameter)) { - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, SymbolFlags.Type); + // The specified symbol flags need to be reinterpreted as type flags + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, flags); } else if (type.flags & TypeFlags.Tuple) { writeTupleType(type); @@ -1229,17 +1231,18 @@ module ts { function writeAnonymousType(type: ObjectType, flags: TypeFormatFlags) { // Always use 'typeof T' for type of class, enum, and module objects if (type.symbol && type.symbol.flags & (SymbolFlags.Class | SymbolFlags.Enum | SymbolFlags.ValueModule)) { - writeTypeofSymbol(type); + writeTypeofSymbol(type, flags); } // Use 'typeof T' for types of functions and methods that circularly reference themselves else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeofSymbol(type); + writeTypeofSymbol(type, flags); } else if (typeStack && contains(typeStack, type)) { // If type is an anonymous type literal in a type alias declaration, use type alias name var typeAlias = getTypeAliasForTypeLiteral(type); if (typeAlias) { - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, SymbolFlags.Type); + // The specified symbol flags need to be reinterpreted as type flags + buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, SymbolFlags.Type, SymbolFormatFlags.None, flags); } else { // Recursive usage, use any @@ -1273,10 +1276,10 @@ module ts { } } - function writeTypeofSymbol(type: ObjectType) { + function writeTypeofSymbol(type: ObjectType, typeFormatFlags?: TypeFormatFlags) { writeKeyword(writer, SyntaxKind.TypeOfKeyword); writeSpace(writer); - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, SymbolFlags.Value); + buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, SymbolFlags.Value, SymbolFormatFlags.None, typeFormatFlags); } function getIndexerParameterName(type: ObjectType, indexKind: IndexKind, fallbackName: string): string { @@ -3562,7 +3565,13 @@ module ts { } if (reportErrors) { headMessage = headMessage || Diagnostics.Type_0_is_not_assignable_to_type_1; - reportError(headMessage, typeToString(source), typeToString(target)); + var sourceType = typeToString(source); + var targetType = typeToString(target); + if (sourceType === targetType) { + sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType); + targetType = typeToString(target, /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType); + } + reportError(headMessage, sourceType, targetType); } return Ternary.False; } @@ -4331,6 +4340,9 @@ module ts { } function inferFromTypes(source: Type, target: Type) { + if (source === anyFunctionType) { + return; + } if (target.flags & TypeFlags.TypeParameter) { // If target is a type parameter, make an inference var typeParameters = context.typeParameters; @@ -4849,6 +4861,16 @@ module ts { function checkIdentifier(node: Identifier): Type { var symbol = getResolvedSymbol(node); + // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects. + // Although in down-level emit of arrow function, we emit it using function expression which means that + // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects + // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior. + // To avoid that we will give an error to users if they use arguments objects in arrow function so that they + // can explicitly bound arguments objects + if (symbol === argumentsSymbol && getContainingFunction(node).kind === SyntaxKind.ArrowFunction) { + error(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_Consider_using_a_standard_function_expression); + } + if (symbol.flags & SymbolFlags.Import) { var symbolLinks = getSymbolLinks(symbol); if (!symbolLinks.referenced) { @@ -4903,7 +4925,9 @@ module ts { // Now skip arrow functions to get the "real" owner of 'this'. if (container.kind === SyntaxKind.ArrowFunction) { container = getThisContainer(container, /* includeArrowFunctions */ false); - needToCaptureLexicalThis = true; + + // When targeting es6, arrow function lexically bind "this" so we do not need to do the work of binding "this" in emitted code + needToCaptureLexicalThis = (languageVersion < ScriptTarget.ES6); } switch (container.kind) { @@ -5895,28 +5919,31 @@ module ts { return getSignatureInstantiation(signature, getInferredTypes(context)); } - function inferTypeArguments(signature: Signature, args: Expression[], excludeArgument?: boolean[]): InferenceContext { + function inferTypeArguments(signature: Signature, args: Expression[], excludeArgument: boolean[]): InferenceContext { var typeParameters = signature.typeParameters; var context = createInferenceContext(typeParameters, /*inferUnionTypes*/ false); - var mapper = createInferenceMapper(context); - // First infer from arguments that are not context sensitive + var inferenceMapper = createInferenceMapper(context); + + // We perform two passes over the arguments. In the first pass we infer from all arguments, but use + // wildcards for all context sensitive function expressions. for (var i = 0; i < args.length; i++) { if (args[i].kind === SyntaxKind.OmittedExpression) { continue; } - if (!excludeArgument || excludeArgument[i] === undefined) { - var parameterType = getTypeAtPosition(signature, i); - - if (i === 0 && args[i].parent.kind === SyntaxKind.TaggedTemplateExpression) { - inferTypes(context, globalTemplateStringsArrayType, parameterType); - continue; - } - - inferTypes(context, checkExpressionWithContextualType(args[i], parameterType, mapper), parameterType); + var parameterType = getTypeAtPosition(signature, i); + if (i === 0 && args[i].parent.kind === SyntaxKind.TaggedTemplateExpression) { + inferTypes(context, globalTemplateStringsArrayType, parameterType); + continue; } + // For context sensitive arguments we pass the identityMapper, which is a signal to treat all + // context sensitive function expressions as wildcards + var mapper = excludeArgument && excludeArgument[i] !== undefined ? identityMapper : inferenceMapper; + inferTypes(context, checkExpressionWithContextualType(args[i], parameterType, mapper), parameterType); } - // Next, infer from those context sensitive arguments that are no longer excluded + // In the second pass we visit only context sensitive arguments, and only those that aren't excluded, this + // time treating function expressions normally (which may cause previously inferred type arguments to be fixed + // as we construct types for contextually typed parameters) if (excludeArgument) { for (var i = 0; i < args.length; i++) { if (args[i].kind === SyntaxKind.OmittedExpression) { @@ -5925,10 +5952,11 @@ module ts { // No need to special-case tagged templates; their excludeArgument value will be 'undefined'. if (excludeArgument[i] === false) { var parameterType = getTypeAtPosition(signature, i); - inferTypes(context, checkExpressionWithContextualType(args[i], parameterType, mapper), parameterType); + inferTypes(context, checkExpressionWithContextualType(args[i], parameterType, inferenceMapper), parameterType); } } } + var inferredTypes = getInferredTypes(context); // Inference has failed if the inferenceFailureType type is in list of inferences context.failedTypeParameterIndex = indexOf(inferredTypes, inferenceFailureType); @@ -6525,6 +6553,9 @@ module ts { function getReturnTypeFromBody(func: FunctionLikeDeclaration, contextualMapper?: TypeMapper): Type { var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func); + if (!func.body) { + return unknownType; + } if (func.body.kind !== SyntaxKind.Block) { var type = checkExpressionCached(func.body, contextualMapper); } @@ -6622,7 +6653,7 @@ module ts { } // The identityMapper object is used to indicate that function expressions are wildcards - if (contextualMapper === identityMapper) { + if (contextualMapper === identityMapper && isContextSensitive(node)) { return anyFunctionType; } var links = getNodeLinks(node); @@ -7296,7 +7327,7 @@ module ts { case SyntaxKind.TypeAssertionExpression: return checkTypeAssertion(node); case SyntaxKind.ParenthesizedExpression: - return checkExpression((node).expression); + return checkExpression((node).expression, contextualMapper); case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: return checkFunctionExpressionOrObjectLiteralMethod(node, contextualMapper); @@ -10088,7 +10119,7 @@ module ts { return isImportResolvedToValue(getSymbolOfNode(node)); } - function hasSemanticErrors(sourceFile?: SourceFile) { + function hasSemanticDiagnostics(sourceFile?: SourceFile) { // Return true if there is any semantic error in a file or globally return getDiagnostics(sourceFile).length > 0 || getGlobalDiagnostics().length > 0; } @@ -10187,7 +10218,7 @@ module ts { getNodeCheckFlags, getEnumMemberValue, isTopLevelValueImportWithEntityName, - hasSemanticErrors, + hasSemanticDiagnostics, isDeclarationVisible, isImplementationOfOverload, writeTypeOfDeclaration, diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 4a710c035ba..3599c95f760 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -280,7 +280,6 @@ module ts { messageText: text, category: message.category, code: message.code, - isEarly: message.isEarly }; } @@ -299,8 +298,7 @@ module ts { messageText: text, category: message.category, - code: message.code, - isEarly: message.isEarly + code: message.code }; } diff --git a/src/compiler/diagnosticInformationMap.generated.ts b/src/compiler/diagnosticInformationMap.generated.ts index f333520733e..dc7ef322c9b 100644 --- a/src/compiler/diagnosticInformationMap.generated.ts +++ b/src/compiler/diagnosticInformationMap.generated.ts @@ -4,87 +4,87 @@ module ts { export var Diagnostics = { Unterminated_string_literal: { code: 1002, category: DiagnosticCategory.Error, key: "Unterminated string literal." }, Identifier_expected: { code: 1003, category: DiagnosticCategory.Error, key: "Identifier expected." }, - _0_expected: { code: 1005, category: DiagnosticCategory.Error, key: "'{0}' expected.", isEarly: true }, + _0_expected: { code: 1005, category: DiagnosticCategory.Error, key: "'{0}' expected." }, A_file_cannot_have_a_reference_to_itself: { code: 1006, category: DiagnosticCategory.Error, key: "A file cannot have a reference to itself." }, - Trailing_comma_not_allowed: { code: 1009, category: DiagnosticCategory.Error, key: "Trailing comma not allowed.", isEarly: true }, + Trailing_comma_not_allowed: { code: 1009, category: DiagnosticCategory.Error, key: "Trailing comma not allowed." }, Asterisk_Slash_expected: { code: 1010, category: DiagnosticCategory.Error, key: "'*/' expected." }, Unexpected_token: { code: 1012, category: DiagnosticCategory.Error, key: "Unexpected token." }, - Catch_clause_parameter_cannot_have_a_type_annotation: { code: 1013, category: DiagnosticCategory.Error, key: "Catch clause parameter cannot have a type annotation.", isEarly: true }, - A_rest_parameter_must_be_last_in_a_parameter_list: { code: 1014, category: DiagnosticCategory.Error, key: "A rest parameter must be last in a parameter list.", isEarly: true }, - Parameter_cannot_have_question_mark_and_initializer: { code: 1015, category: DiagnosticCategory.Error, key: "Parameter cannot have question mark and initializer.", isEarly: true }, - A_required_parameter_cannot_follow_an_optional_parameter: { code: 1016, category: DiagnosticCategory.Error, key: "A required parameter cannot follow an optional parameter.", isEarly: true }, - An_index_signature_cannot_have_a_rest_parameter: { code: 1017, category: DiagnosticCategory.Error, key: "An index signature cannot have a rest parameter.", isEarly: true }, - An_index_signature_parameter_cannot_have_an_accessibility_modifier: { code: 1018, category: DiagnosticCategory.Error, key: "An index signature parameter cannot have an accessibility modifier.", isEarly: true }, - An_index_signature_parameter_cannot_have_a_question_mark: { code: 1019, category: DiagnosticCategory.Error, key: "An index signature parameter cannot have a question mark.", isEarly: true }, - An_index_signature_parameter_cannot_have_an_initializer: { code: 1020, category: DiagnosticCategory.Error, key: "An index signature parameter cannot have an initializer.", isEarly: true }, - An_index_signature_must_have_a_type_annotation: { code: 1021, category: DiagnosticCategory.Error, key: "An index signature must have a type annotation.", isEarly: true }, - An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: DiagnosticCategory.Error, key: "An index signature parameter must have a type annotation.", isEarly: true }, - An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: DiagnosticCategory.Error, key: "An index signature parameter type must be 'string' or 'number'.", isEarly: true }, + Catch_clause_parameter_cannot_have_a_type_annotation: { code: 1013, category: DiagnosticCategory.Error, key: "Catch clause parameter cannot have a type annotation." }, + A_rest_parameter_must_be_last_in_a_parameter_list: { code: 1014, category: DiagnosticCategory.Error, key: "A rest parameter must be last in a parameter list." }, + Parameter_cannot_have_question_mark_and_initializer: { code: 1015, category: DiagnosticCategory.Error, key: "Parameter cannot have question mark and initializer." }, + A_required_parameter_cannot_follow_an_optional_parameter: { code: 1016, category: DiagnosticCategory.Error, key: "A required parameter cannot follow an optional parameter." }, + An_index_signature_cannot_have_a_rest_parameter: { code: 1017, category: DiagnosticCategory.Error, key: "An index signature cannot have a rest parameter." }, + An_index_signature_parameter_cannot_have_an_accessibility_modifier: { code: 1018, category: DiagnosticCategory.Error, key: "An index signature parameter cannot have an accessibility modifier." }, + An_index_signature_parameter_cannot_have_a_question_mark: { code: 1019, category: DiagnosticCategory.Error, key: "An index signature parameter cannot have a question mark." }, + An_index_signature_parameter_cannot_have_an_initializer: { code: 1020, category: DiagnosticCategory.Error, key: "An index signature parameter cannot have an initializer." }, + An_index_signature_must_have_a_type_annotation: { code: 1021, category: DiagnosticCategory.Error, key: "An index signature must have a type annotation." }, + An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: DiagnosticCategory.Error, key: "An index signature parameter must have a type annotation." }, + An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: DiagnosticCategory.Error, key: "An index signature parameter type must be 'string' or 'number'." }, A_class_or_interface_declaration_can_only_have_one_extends_clause: { code: 1024, category: DiagnosticCategory.Error, key: "A class or interface declaration can only have one 'extends' clause." }, An_extends_clause_must_precede_an_implements_clause: { code: 1025, category: DiagnosticCategory.Error, key: "An 'extends' clause must precede an 'implements' clause." }, A_class_can_only_extend_a_single_class: { code: 1026, category: DiagnosticCategory.Error, key: "A class can only extend a single class." }, A_class_declaration_can_only_have_one_implements_clause: { code: 1027, category: DiagnosticCategory.Error, key: "A class declaration can only have one 'implements' clause." }, - Accessibility_modifier_already_seen: { code: 1028, category: DiagnosticCategory.Error, key: "Accessibility modifier already seen.", isEarly: true }, - _0_modifier_must_precede_1_modifier: { code: 1029, category: DiagnosticCategory.Error, key: "'{0}' modifier must precede '{1}' modifier.", isEarly: true }, - _0_modifier_already_seen: { code: 1030, category: DiagnosticCategory.Error, key: "'{0}' modifier already seen.", isEarly: true }, - _0_modifier_cannot_appear_on_a_class_element: { code: 1031, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a class element.", isEarly: true }, + Accessibility_modifier_already_seen: { code: 1028, category: DiagnosticCategory.Error, key: "Accessibility modifier already seen." }, + _0_modifier_must_precede_1_modifier: { code: 1029, category: DiagnosticCategory.Error, key: "'{0}' modifier must precede '{1}' modifier." }, + _0_modifier_already_seen: { code: 1030, category: DiagnosticCategory.Error, key: "'{0}' modifier already seen." }, + _0_modifier_cannot_appear_on_a_class_element: { code: 1031, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a class element." }, An_interface_declaration_cannot_have_an_implements_clause: { code: 1032, category: DiagnosticCategory.Error, key: "An interface declaration cannot have an 'implements' clause." }, super_must_be_followed_by_an_argument_list_or_member_access: { code: 1034, category: DiagnosticCategory.Error, key: "'super' must be followed by an argument list or member access." }, - Only_ambient_modules_can_use_quoted_names: { code: 1035, category: DiagnosticCategory.Error, key: "Only ambient modules can use quoted names.", isEarly: true }, - Statements_are_not_allowed_in_ambient_contexts: { code: 1036, category: DiagnosticCategory.Error, key: "Statements are not allowed in ambient contexts.", isEarly: true }, - A_declare_modifier_cannot_be_used_in_an_already_ambient_context: { code: 1038, category: DiagnosticCategory.Error, key: "A 'declare' modifier cannot be used in an already ambient context.", isEarly: true }, - Initializers_are_not_allowed_in_ambient_contexts: { code: 1039, category: DiagnosticCategory.Error, key: "Initializers are not allowed in ambient contexts.", isEarly: true }, - _0_modifier_cannot_appear_on_a_module_element: { code: 1044, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a module element.", isEarly: true }, - A_declare_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: DiagnosticCategory.Error, key: "A 'declare' modifier cannot be used with an interface declaration.", isEarly: true }, + Only_ambient_modules_can_use_quoted_names: { code: 1035, category: DiagnosticCategory.Error, key: "Only ambient modules can use quoted names." }, + Statements_are_not_allowed_in_ambient_contexts: { code: 1036, category: DiagnosticCategory.Error, key: "Statements are not allowed in ambient contexts." }, + A_declare_modifier_cannot_be_used_in_an_already_ambient_context: { code: 1038, category: DiagnosticCategory.Error, key: "A 'declare' modifier cannot be used in an already ambient context." }, + Initializers_are_not_allowed_in_ambient_contexts: { code: 1039, category: DiagnosticCategory.Error, key: "Initializers are not allowed in ambient contexts." }, + _0_modifier_cannot_appear_on_a_module_element: { code: 1044, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a module element." }, + A_declare_modifier_cannot_be_used_with_an_interface_declaration: { code: 1045, category: DiagnosticCategory.Error, key: "A 'declare' modifier cannot be used with an interface declaration." }, A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file: { code: 1046, category: DiagnosticCategory.Error, key: "A 'declare' modifier is required for a top level declaration in a .d.ts file." }, - A_rest_parameter_cannot_be_optional: { code: 1047, category: DiagnosticCategory.Error, key: "A rest parameter cannot be optional.", isEarly: true }, - A_rest_parameter_cannot_have_an_initializer: { code: 1048, category: DiagnosticCategory.Error, key: "A rest parameter cannot have an initializer.", isEarly: true }, - A_set_accessor_must_have_exactly_one_parameter: { code: 1049, category: DiagnosticCategory.Error, key: "A 'set' accessor must have exactly one parameter.", isEarly: true }, - A_set_accessor_cannot_have_an_optional_parameter: { code: 1051, category: DiagnosticCategory.Error, key: "A 'set' accessor cannot have an optional parameter.", isEarly: true }, - A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: DiagnosticCategory.Error, key: "A 'set' accessor parameter cannot have an initializer.", isEarly: true }, - A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: DiagnosticCategory.Error, key: "A 'set' accessor cannot have rest parameter.", isEarly: true }, - A_get_accessor_cannot_have_parameters: { code: 1054, category: DiagnosticCategory.Error, key: "A 'get' accessor cannot have parameters.", isEarly: true }, - Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: DiagnosticCategory.Error, key: "Accessors are only available when targeting ECMAScript 5 and higher.", isEarly: true }, - Enum_member_must_have_initializer: { code: 1061, category: DiagnosticCategory.Error, key: "Enum member must have initializer.", isEarly: true }, - An_export_assignment_cannot_be_used_in_an_internal_module: { code: 1063, category: DiagnosticCategory.Error, key: "An export assignment cannot be used in an internal module.", isEarly: true }, - Ambient_enum_elements_can_only_have_integer_literal_initializers: { code: 1066, category: DiagnosticCategory.Error, key: "Ambient enum elements can only have integer literal initializers.", isEarly: true }, + A_rest_parameter_cannot_be_optional: { code: 1047, category: DiagnosticCategory.Error, key: "A rest parameter cannot be optional." }, + A_rest_parameter_cannot_have_an_initializer: { code: 1048, category: DiagnosticCategory.Error, key: "A rest parameter cannot have an initializer." }, + A_set_accessor_must_have_exactly_one_parameter: { code: 1049, category: DiagnosticCategory.Error, key: "A 'set' accessor must have exactly one parameter." }, + A_set_accessor_cannot_have_an_optional_parameter: { code: 1051, category: DiagnosticCategory.Error, key: "A 'set' accessor cannot have an optional parameter." }, + A_set_accessor_parameter_cannot_have_an_initializer: { code: 1052, category: DiagnosticCategory.Error, key: "A 'set' accessor parameter cannot have an initializer." }, + A_set_accessor_cannot_have_rest_parameter: { code: 1053, category: DiagnosticCategory.Error, key: "A 'set' accessor cannot have rest parameter." }, + A_get_accessor_cannot_have_parameters: { code: 1054, category: DiagnosticCategory.Error, key: "A 'get' accessor cannot have parameters." }, + Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher: { code: 1056, category: DiagnosticCategory.Error, key: "Accessors are only available when targeting ECMAScript 5 and higher." }, + Enum_member_must_have_initializer: { code: 1061, category: DiagnosticCategory.Error, key: "Enum member must have initializer." }, + An_export_assignment_cannot_be_used_in_an_internal_module: { code: 1063, category: DiagnosticCategory.Error, key: "An export assignment cannot be used in an internal module." }, + Ambient_enum_elements_can_only_have_integer_literal_initializers: { code: 1066, category: DiagnosticCategory.Error, key: "Ambient enum elements can only have integer literal initializers." }, Unexpected_token_A_constructor_method_accessor_or_property_was_expected: { code: 1068, category: DiagnosticCategory.Error, key: "Unexpected token. A constructor, method, accessor, or property was expected." }, - A_declare_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: DiagnosticCategory.Error, key: "A 'declare' modifier cannot be used with an import declaration.", isEarly: true }, + A_declare_modifier_cannot_be_used_with_an_import_declaration: { code: 1079, category: DiagnosticCategory.Error, key: "A 'declare' modifier cannot be used with an import declaration." }, Invalid_reference_directive_syntax: { code: 1084, category: DiagnosticCategory.Error, key: "Invalid 'reference' directive syntax." }, - Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: { code: 1085, category: DiagnosticCategory.Error, key: "Octal literals are not available when targeting ECMAScript 5 and higher.", isEarly: true }, - An_accessor_cannot_be_declared_in_an_ambient_context: { code: 1086, category: DiagnosticCategory.Error, key: "An accessor cannot be declared in an ambient context.", isEarly: true }, - _0_modifier_cannot_appear_on_a_constructor_declaration: { code: 1089, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a constructor declaration.", isEarly: true }, - _0_modifier_cannot_appear_on_a_parameter: { code: 1090, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a parameter.", isEarly: true }, - Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: { code: 1091, category: DiagnosticCategory.Error, key: "Only a single variable declaration is allowed in a 'for...in' statement.", isEarly: true }, - Type_parameters_cannot_appear_on_a_constructor_declaration: { code: 1092, category: DiagnosticCategory.Error, key: "Type parameters cannot appear on a constructor declaration.", isEarly: true }, - Type_annotation_cannot_appear_on_a_constructor_declaration: { code: 1093, category: DiagnosticCategory.Error, key: "Type annotation cannot appear on a constructor declaration.", isEarly: true }, - An_accessor_cannot_have_type_parameters: { code: 1094, category: DiagnosticCategory.Error, key: "An accessor cannot have type parameters.", isEarly: true }, - A_set_accessor_cannot_have_a_return_type_annotation: { code: 1095, category: DiagnosticCategory.Error, key: "A 'set' accessor cannot have a return type annotation.", isEarly: true }, - An_index_signature_must_have_exactly_one_parameter: { code: 1096, category: DiagnosticCategory.Error, key: "An index signature must have exactly one parameter.", isEarly: true }, - _0_list_cannot_be_empty: { code: 1097, category: DiagnosticCategory.Error, key: "'{0}' list cannot be empty.", isEarly: true }, - Type_parameter_list_cannot_be_empty: { code: 1098, category: DiagnosticCategory.Error, key: "Type parameter list cannot be empty.", isEarly: true }, - Type_argument_list_cannot_be_empty: { code: 1099, category: DiagnosticCategory.Error, key: "Type argument list cannot be empty.", isEarly: true }, - Invalid_use_of_0_in_strict_mode: { code: 1100, category: DiagnosticCategory.Error, key: "Invalid use of '{0}' in strict mode.", isEarly: true }, - with_statements_are_not_allowed_in_strict_mode: { code: 1101, category: DiagnosticCategory.Error, key: "'with' statements are not allowed in strict mode.", isEarly: true }, - delete_cannot_be_called_on_an_identifier_in_strict_mode: { code: 1102, category: DiagnosticCategory.Error, key: "'delete' cannot be called on an identifier in strict mode.", isEarly: true }, - A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: { code: 1104, category: DiagnosticCategory.Error, key: "A 'continue' statement can only be used within an enclosing iteration statement.", isEarly: true }, - A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: { code: 1105, category: DiagnosticCategory.Error, key: "A 'break' statement can only be used within an enclosing iteration or switch statement.", isEarly: true }, - Jump_target_cannot_cross_function_boundary: { code: 1107, category: DiagnosticCategory.Error, key: "Jump target cannot cross function boundary.", isEarly: true }, - A_return_statement_can_only_be_used_within_a_function_body: { code: 1108, category: DiagnosticCategory.Error, key: "A 'return' statement can only be used within a function body.", isEarly: true }, - Expression_expected: { code: 1109, category: DiagnosticCategory.Error, key: "Expression expected.", isEarly: true }, - Type_expected: { code: 1110, category: DiagnosticCategory.Error, key: "Type expected.", isEarly: true }, - A_class_member_cannot_be_declared_optional: { code: 1112, category: DiagnosticCategory.Error, key: "A class member cannot be declared optional.", isEarly: true }, - A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: { code: 1113, category: DiagnosticCategory.Error, key: "A 'default' clause cannot appear more than once in a 'switch' statement.", isEarly: true }, - Duplicate_label_0: { code: 1114, category: DiagnosticCategory.Error, key: "Duplicate label '{0}'", isEarly: true }, - A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: { code: 1115, category: DiagnosticCategory.Error, key: "A 'continue' statement can only jump to a label of an enclosing iteration statement.", isEarly: true }, - A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: { code: 1116, category: DiagnosticCategory.Error, key: "A 'break' statement can only jump to a label of an enclosing statement.", isEarly: true }, - An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: { code: 1117, category: DiagnosticCategory.Error, key: "An object literal cannot have multiple properties with the same name in strict mode.", isEarly: true }, - An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: { code: 1118, category: DiagnosticCategory.Error, key: "An object literal cannot have multiple get/set accessors with the same name.", isEarly: true }, - An_object_literal_cannot_have_property_and_accessor_with_the_same_name: { code: 1119, category: DiagnosticCategory.Error, key: "An object literal cannot have property and accessor with the same name.", isEarly: true }, - An_export_assignment_cannot_have_modifiers: { code: 1120, category: DiagnosticCategory.Error, key: "An export assignment cannot have modifiers.", isEarly: true }, - Octal_literals_are_not_allowed_in_strict_mode: { code: 1121, category: DiagnosticCategory.Error, key: "Octal literals are not allowed in strict mode.", isEarly: true }, - A_tuple_type_element_list_cannot_be_empty: { code: 1122, category: DiagnosticCategory.Error, key: "A tuple type element list cannot be empty.", isEarly: true }, - Variable_declaration_list_cannot_be_empty: { code: 1123, category: DiagnosticCategory.Error, key: "Variable declaration list cannot be empty.", isEarly: true }, + Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher: { code: 1085, category: DiagnosticCategory.Error, key: "Octal literals are not available when targeting ECMAScript 5 and higher." }, + An_accessor_cannot_be_declared_in_an_ambient_context: { code: 1086, category: DiagnosticCategory.Error, key: "An accessor cannot be declared in an ambient context." }, + _0_modifier_cannot_appear_on_a_constructor_declaration: { code: 1089, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a constructor declaration." }, + _0_modifier_cannot_appear_on_a_parameter: { code: 1090, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a parameter." }, + Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement: { code: 1091, category: DiagnosticCategory.Error, key: "Only a single variable declaration is allowed in a 'for...in' statement." }, + Type_parameters_cannot_appear_on_a_constructor_declaration: { code: 1092, category: DiagnosticCategory.Error, key: "Type parameters cannot appear on a constructor declaration." }, + Type_annotation_cannot_appear_on_a_constructor_declaration: { code: 1093, category: DiagnosticCategory.Error, key: "Type annotation cannot appear on a constructor declaration." }, + An_accessor_cannot_have_type_parameters: { code: 1094, category: DiagnosticCategory.Error, key: "An accessor cannot have type parameters." }, + A_set_accessor_cannot_have_a_return_type_annotation: { code: 1095, category: DiagnosticCategory.Error, key: "A 'set' accessor cannot have a return type annotation." }, + An_index_signature_must_have_exactly_one_parameter: { code: 1096, category: DiagnosticCategory.Error, key: "An index signature must have exactly one parameter." }, + _0_list_cannot_be_empty: { code: 1097, category: DiagnosticCategory.Error, key: "'{0}' list cannot be empty." }, + Type_parameter_list_cannot_be_empty: { code: 1098, category: DiagnosticCategory.Error, key: "Type parameter list cannot be empty." }, + Type_argument_list_cannot_be_empty: { code: 1099, category: DiagnosticCategory.Error, key: "Type argument list cannot be empty." }, + Invalid_use_of_0_in_strict_mode: { code: 1100, category: DiagnosticCategory.Error, key: "Invalid use of '{0}' in strict mode." }, + with_statements_are_not_allowed_in_strict_mode: { code: 1101, category: DiagnosticCategory.Error, key: "'with' statements are not allowed in strict mode." }, + delete_cannot_be_called_on_an_identifier_in_strict_mode: { code: 1102, category: DiagnosticCategory.Error, key: "'delete' cannot be called on an identifier in strict mode." }, + A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement: { code: 1104, category: DiagnosticCategory.Error, key: "A 'continue' statement can only be used within an enclosing iteration statement." }, + A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement: { code: 1105, category: DiagnosticCategory.Error, key: "A 'break' statement can only be used within an enclosing iteration or switch statement." }, + Jump_target_cannot_cross_function_boundary: { code: 1107, category: DiagnosticCategory.Error, key: "Jump target cannot cross function boundary." }, + A_return_statement_can_only_be_used_within_a_function_body: { code: 1108, category: DiagnosticCategory.Error, key: "A 'return' statement can only be used within a function body." }, + Expression_expected: { code: 1109, category: DiagnosticCategory.Error, key: "Expression expected." }, + Type_expected: { code: 1110, category: DiagnosticCategory.Error, key: "Type expected." }, + A_class_member_cannot_be_declared_optional: { code: 1112, category: DiagnosticCategory.Error, key: "A class member cannot be declared optional." }, + A_default_clause_cannot_appear_more_than_once_in_a_switch_statement: { code: 1113, category: DiagnosticCategory.Error, key: "A 'default' clause cannot appear more than once in a 'switch' statement." }, + Duplicate_label_0: { code: 1114, category: DiagnosticCategory.Error, key: "Duplicate label '{0}'" }, + A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement: { code: 1115, category: DiagnosticCategory.Error, key: "A 'continue' statement can only jump to a label of an enclosing iteration statement." }, + A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement: { code: 1116, category: DiagnosticCategory.Error, key: "A 'break' statement can only jump to a label of an enclosing statement." }, + An_object_literal_cannot_have_multiple_properties_with_the_same_name_in_strict_mode: { code: 1117, category: DiagnosticCategory.Error, key: "An object literal cannot have multiple properties with the same name in strict mode." }, + An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name: { code: 1118, category: DiagnosticCategory.Error, key: "An object literal cannot have multiple get/set accessors with the same name." }, + An_object_literal_cannot_have_property_and_accessor_with_the_same_name: { code: 1119, category: DiagnosticCategory.Error, key: "An object literal cannot have property and accessor with the same name." }, + An_export_assignment_cannot_have_modifiers: { code: 1120, category: DiagnosticCategory.Error, key: "An export assignment cannot have modifiers." }, + Octal_literals_are_not_allowed_in_strict_mode: { code: 1121, category: DiagnosticCategory.Error, key: "Octal literals are not allowed in strict mode." }, + A_tuple_type_element_list_cannot_be_empty: { code: 1122, category: DiagnosticCategory.Error, key: "A tuple type element list cannot be empty." }, + Variable_declaration_list_cannot_be_empty: { code: 1123, category: DiagnosticCategory.Error, key: "Variable declaration list cannot be empty." }, Digit_expected: { code: 1124, category: DiagnosticCategory.Error, key: "Digit expected." }, Hexadecimal_digit_expected: { code: 1125, category: DiagnosticCategory.Error, key: "Hexadecimal digit expected." }, Unexpected_end_of_text: { code: 1126, category: DiagnosticCategory.Error, key: "Unexpected end of text." }, @@ -96,53 +96,53 @@ module ts { Enum_member_expected: { code: 1132, category: DiagnosticCategory.Error, key: "Enum member expected." }, Type_reference_expected: { code: 1133, category: DiagnosticCategory.Error, key: "Type reference expected." }, Variable_declaration_expected: { code: 1134, category: DiagnosticCategory.Error, key: "Variable declaration expected." }, - Argument_expression_expected: { code: 1135, category: DiagnosticCategory.Error, key: "Argument expression expected.", isEarly: true }, + Argument_expression_expected: { code: 1135, category: DiagnosticCategory.Error, key: "Argument expression expected." }, Property_assignment_expected: { code: 1136, category: DiagnosticCategory.Error, key: "Property assignment expected." }, Expression_or_comma_expected: { code: 1137, category: DiagnosticCategory.Error, key: "Expression or comma expected." }, Parameter_declaration_expected: { code: 1138, category: DiagnosticCategory.Error, key: "Parameter declaration expected." }, Type_parameter_declaration_expected: { code: 1139, category: DiagnosticCategory.Error, key: "Type parameter declaration expected." }, Type_argument_expected: { code: 1140, category: DiagnosticCategory.Error, key: "Type argument expected." }, - String_literal_expected: { code: 1141, category: DiagnosticCategory.Error, key: "String literal expected.", isEarly: true }, - Line_break_not_permitted_here: { code: 1142, category: DiagnosticCategory.Error, key: "Line break not permitted here.", isEarly: true }, + String_literal_expected: { code: 1141, category: DiagnosticCategory.Error, key: "String literal expected." }, + Line_break_not_permitted_here: { code: 1142, category: DiagnosticCategory.Error, key: "Line break not permitted here." }, or_expected: { code: 1144, category: DiagnosticCategory.Error, key: "'{' or ';' expected." }, - Modifiers_not_permitted_on_index_signature_members: { code: 1145, category: DiagnosticCategory.Error, key: "Modifiers not permitted on index signature members.", isEarly: true }, + Modifiers_not_permitted_on_index_signature_members: { code: 1145, category: DiagnosticCategory.Error, key: "Modifiers not permitted on index signature members." }, Declaration_expected: { code: 1146, category: DiagnosticCategory.Error, key: "Declaration expected." }, - Import_declarations_in_an_internal_module_cannot_reference_an_external_module: { code: 1147, category: DiagnosticCategory.Error, key: "Import declarations in an internal module cannot reference an external module.", isEarly: true }, + Import_declarations_in_an_internal_module_cannot_reference_an_external_module: { code: 1147, category: DiagnosticCategory.Error, key: "Import declarations in an internal module cannot reference an external module." }, Cannot_compile_external_modules_unless_the_module_flag_is_provided: { code: 1148, category: DiagnosticCategory.Error, key: "Cannot compile external modules unless the '--module' flag is provided." }, Filename_0_differs_from_already_included_filename_1_only_in_casing: { code: 1149, category: DiagnosticCategory.Error, key: "Filename '{0}' differs from already included filename '{1}' only in casing" }, - new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: DiagnosticCategory.Error, key: "'new T[]' cannot be used to create an array. Use 'new Array()' instead.", isEarly: true }, + new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: DiagnosticCategory.Error, key: "'new T[]' cannot be used to create an array. Use 'new Array()' instead." }, var_let_or_const_expected: { code: 1152, category: DiagnosticCategory.Error, key: "'var', 'let' or 'const' expected." }, - let_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1153, category: DiagnosticCategory.Error, key: "'let' declarations are only available when targeting ECMAScript 6 and higher.", isEarly: true }, - const_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1154, category: DiagnosticCategory.Error, key: "'const' declarations are only available when targeting ECMAScript 6 and higher.", isEarly: true }, - const_declarations_must_be_initialized: { code: 1155, category: DiagnosticCategory.Error, key: "'const' declarations must be initialized", isEarly: true }, - const_declarations_can_only_be_declared_inside_a_block: { code: 1156, category: DiagnosticCategory.Error, key: "'const' declarations can only be declared inside a block.", isEarly: true }, - let_declarations_can_only_be_declared_inside_a_block: { code: 1157, category: DiagnosticCategory.Error, key: "'let' declarations can only be declared inside a block.", isEarly: true }, - Tagged_templates_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1159, category: DiagnosticCategory.Error, key: "Tagged templates are only available when targeting ECMAScript 6 and higher.", isEarly: true }, + let_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1153, category: DiagnosticCategory.Error, key: "'let' declarations are only available when targeting ECMAScript 6 and higher." }, + const_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1154, category: DiagnosticCategory.Error, key: "'const' declarations are only available when targeting ECMAScript 6 and higher." }, + const_declarations_must_be_initialized: { code: 1155, category: DiagnosticCategory.Error, key: "'const' declarations must be initialized" }, + const_declarations_can_only_be_declared_inside_a_block: { code: 1156, category: DiagnosticCategory.Error, key: "'const' declarations can only be declared inside a block." }, + let_declarations_can_only_be_declared_inside_a_block: { code: 1157, category: DiagnosticCategory.Error, key: "'let' declarations can only be declared inside a block." }, + Tagged_templates_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1159, category: DiagnosticCategory.Error, key: "Tagged templates are only available when targeting ECMAScript 6 and higher." }, Unterminated_template_literal: { code: 1160, category: DiagnosticCategory.Error, key: "Unterminated template literal." }, Unterminated_regular_expression_literal: { code: 1161, category: DiagnosticCategory.Error, key: "Unterminated regular expression literal." }, - An_object_member_cannot_be_declared_optional: { code: 1162, category: DiagnosticCategory.Error, key: "An object member cannot be declared optional.", isEarly: true }, - yield_expression_must_be_contained_within_a_generator_declaration: { code: 1163, category: DiagnosticCategory.Error, key: "'yield' expression must be contained_within a generator declaration.", isEarly: true }, - Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: DiagnosticCategory.Error, key: "Computed property names are not allowed in enums.", isEarly: true }, - Computed_property_names_are_not_allowed_in_an_ambient_context: { code: 1165, category: DiagnosticCategory.Error, key: "Computed property names are not allowed in an ambient context.", isEarly: true }, - Computed_property_names_are_not_allowed_in_class_property_declarations: { code: 1166, category: DiagnosticCategory.Error, key: "Computed property names are not allowed in class property declarations.", isEarly: true }, - Computed_property_names_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1167, category: DiagnosticCategory.Error, key: "Computed property names are only available when targeting ECMAScript 6 and higher.", isEarly: true }, - Computed_property_names_are_not_allowed_in_method_overloads: { code: 1168, category: DiagnosticCategory.Error, key: "Computed property names are not allowed in method overloads.", isEarly: true }, - Computed_property_names_are_not_allowed_in_interfaces: { code: 1169, category: DiagnosticCategory.Error, key: "Computed property names are not allowed in interfaces.", isEarly: true }, - Computed_property_names_are_not_allowed_in_type_literals: { code: 1170, category: DiagnosticCategory.Error, key: "Computed property names are not allowed in type literals.", isEarly: true }, + An_object_member_cannot_be_declared_optional: { code: 1162, category: DiagnosticCategory.Error, key: "An object member cannot be declared optional." }, + yield_expression_must_be_contained_within_a_generator_declaration: { code: 1163, category: DiagnosticCategory.Error, key: "'yield' expression must be contained_within a generator declaration." }, + Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: DiagnosticCategory.Error, key: "Computed property names are not allowed in enums." }, + Computed_property_names_are_not_allowed_in_an_ambient_context: { code: 1165, category: DiagnosticCategory.Error, key: "Computed property names are not allowed in an ambient context." }, + Computed_property_names_are_not_allowed_in_class_property_declarations: { code: 1166, category: DiagnosticCategory.Error, key: "Computed property names are not allowed in class property declarations." }, + Computed_property_names_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1167, category: DiagnosticCategory.Error, key: "Computed property names are only available when targeting ECMAScript 6 and higher." }, + Computed_property_names_are_not_allowed_in_method_overloads: { code: 1168, category: DiagnosticCategory.Error, key: "Computed property names are not allowed in method overloads." }, + Computed_property_names_are_not_allowed_in_interfaces: { code: 1169, category: DiagnosticCategory.Error, key: "Computed property names are not allowed in interfaces." }, + Computed_property_names_are_not_allowed_in_type_literals: { code: 1170, category: DiagnosticCategory.Error, key: "Computed property names are not allowed in type literals." }, A_comma_expression_is_not_allowed_in_a_computed_property_name: { code: 1171, category: DiagnosticCategory.Error, key: "A comma expression is not allowed in a computed property name." }, - extends_clause_already_seen: { code: 1172, category: DiagnosticCategory.Error, key: "'extends' clause already seen.", isEarly: true }, - extends_clause_must_precede_implements_clause: { code: 1173, category: DiagnosticCategory.Error, key: "'extends' clause must precede 'implements' clause.", isEarly: true }, - Classes_can_only_extend_a_single_class: { code: 1174, category: DiagnosticCategory.Error, key: "Classes can only extend a single class.", isEarly: true }, - implements_clause_already_seen: { code: 1175, category: DiagnosticCategory.Error, key: "'implements' clause already seen.", isEarly: true }, - Interface_declaration_cannot_have_implements_clause: { code: 1176, category: DiagnosticCategory.Error, key: "Interface declaration cannot have 'implements' clause.", isEarly: true }, + extends_clause_already_seen: { code: 1172, category: DiagnosticCategory.Error, key: "'extends' clause already seen." }, + extends_clause_must_precede_implements_clause: { code: 1173, category: DiagnosticCategory.Error, key: "'extends' clause must precede 'implements' clause." }, + Classes_can_only_extend_a_single_class: { code: 1174, category: DiagnosticCategory.Error, key: "Classes can only extend a single class." }, + implements_clause_already_seen: { code: 1175, category: DiagnosticCategory.Error, key: "'implements' clause already seen." }, + Interface_declaration_cannot_have_implements_clause: { code: 1176, category: DiagnosticCategory.Error, key: "Interface declaration cannot have 'implements' clause." }, Binary_digit_expected: { code: 1177, category: DiagnosticCategory.Error, key: "Binary digit expected." }, Octal_digit_expected: { code: 1178, category: DiagnosticCategory.Error, key: "Octal digit expected." }, Unexpected_token_expected: { code: 1179, category: DiagnosticCategory.Error, key: "Unexpected token. '{' expected." }, Property_destructuring_pattern_expected: { code: 1180, category: DiagnosticCategory.Error, key: "Property destructuring pattern expected." }, Array_element_destructuring_pattern_expected: { code: 1181, category: DiagnosticCategory.Error, key: "Array element destructuring pattern expected." }, - A_destructuring_declaration_must_have_an_initializer: { code: 1182, category: DiagnosticCategory.Error, key: "A destructuring declaration must have an initializer.", isEarly: true }, - Destructuring_declarations_are_not_allowed_in_ambient_contexts: { code: 1183, category: DiagnosticCategory.Error, key: "Destructuring declarations are not allowed in ambient contexts.", isEarly: true }, - An_implementation_cannot_be_declared_in_ambient_contexts: { code: 1184, category: DiagnosticCategory.Error, key: "An implementation cannot be declared in ambient contexts.", isEarly: true }, + A_destructuring_declaration_must_have_an_initializer: { code: 1182, category: DiagnosticCategory.Error, key: "A destructuring declaration must have an initializer." }, + Destructuring_declarations_are_not_allowed_in_ambient_contexts: { code: 1183, category: DiagnosticCategory.Error, key: "Destructuring declarations are not allowed in ambient contexts." }, + An_implementation_cannot_be_declared_in_ambient_contexts: { code: 1184, category: DiagnosticCategory.Error, key: "An implementation cannot be declared in ambient contexts." }, Modifiers_cannot_appear_here: { code: 1184, category: DiagnosticCategory.Error, key: "Modifiers cannot appear here." }, Merge_conflict_marker_encountered: { code: 1185, category: DiagnosticCategory.Error, key: "Merge conflict marker encountered." }, A_rest_element_cannot_have_an_initializer: { code: 1186, category: DiagnosticCategory.Error, key: "A rest element cannot have an initializer." }, @@ -284,10 +284,10 @@ module ts { Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses: { code: 2445, category: DiagnosticCategory.Error, key: "Property '{0}' is protected and only accessible within class '{1}' and its subclasses." }, Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1: { code: 2446, category: DiagnosticCategory.Error, key: "Property '{0}' is protected and only accessible through an instance of class '{1}'." }, The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead: { code: 2447, category: DiagnosticCategory.Error, key: "The '{0}' operator is not allowed for boolean types. Consider using '{1}' instead." }, - Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: DiagnosticCategory.Error, key: "Block-scoped variable '{0}' used before its declaration.", isEarly: true }, - The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant: { code: 2449, category: DiagnosticCategory.Error, key: "The operand of an increment or decrement operator cannot be a constant.", isEarly: true }, - Left_hand_side_of_assignment_expression_cannot_be_a_constant: { code: 2450, category: DiagnosticCategory.Error, key: "Left-hand side of assignment expression cannot be a constant.", isEarly: true }, - Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: DiagnosticCategory.Error, key: "Cannot redeclare block-scoped variable '{0}'.", isEarly: true }, + Block_scoped_variable_0_used_before_its_declaration: { code: 2448, category: DiagnosticCategory.Error, key: "Block-scoped variable '{0}' used before its declaration." }, + The_operand_of_an_increment_or_decrement_operator_cannot_be_a_constant: { code: 2449, category: DiagnosticCategory.Error, key: "The operand of an increment or decrement operator cannot be a constant." }, + Left_hand_side_of_assignment_expression_cannot_be_a_constant: { code: 2450, category: DiagnosticCategory.Error, key: "Left-hand side of assignment expression cannot be a constant." }, + Cannot_redeclare_block_scoped_variable_0: { code: 2451, category: DiagnosticCategory.Error, key: "Cannot redeclare block-scoped variable '{0}'." }, An_enum_member_cannot_have_a_numeric_name: { code: 2452, category: DiagnosticCategory.Error, key: "An enum member cannot have a numeric name." }, The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_type_arguments_explicitly: { code: 2453, category: DiagnosticCategory.Error, key: "The type argument for type parameter '{0}' cannot be inferred from the usage. Consider specifying the type arguments explicitly." }, Type_argument_candidate_1_is_not_a_valid_type_argument_because_it_is_not_a_supertype_of_candidate_0: { code: 2455, category: DiagnosticCategory.Error, key: "Type argument candidate '{1}' is not a valid type argument because it is not a supertype of candidate '{0}'." }, @@ -373,12 +373,12 @@ module ts { Parameter_0_of_exported_function_has_or_is_using_private_name_1: { code: 4078, category: DiagnosticCategory.Error, key: "Parameter '{0}' of exported function has or is using private name '{1}'." }, 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 }, + 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." }, 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." }, - A_const_enum_member_can_only_be_accessed_using_a_string_literal: { code: 4085, category: DiagnosticCategory.Error, key: "A const enum member can only be accessed using a string literal.", isEarly: true }, + A_const_enum_member_can_only_be_accessed_using_a_string_literal: { code: 4085, category: DiagnosticCategory.Error, key: "A const enum member can only be accessed using a string literal." }, 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'." }, - Property_0_does_not_exist_on_const_enum_1: { code: 4088, category: DiagnosticCategory.Error, key: "Property '{0}' does not exist on 'const' enum '{1}'.", isEarly: true }, + Property_0_does_not_exist_on_const_enum_1: { code: 4088, category: DiagnosticCategory.Error, key: "Property '{0}' does not exist on 'const' enum '{1}'." }, 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}" }, @@ -450,7 +450,8 @@ module ts { _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: { code: 7023, category: DiagnosticCategory.Error, key: "'{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." }, 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: { code: 7024, category: DiagnosticCategory.Error, key: "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." }, You_cannot_rename_this_element: { code: 8000, category: DiagnosticCategory.Error, key: "You cannot rename this element." }, - yield_expressions_are_not_currently_supported: { code: 9000, category: DiagnosticCategory.Error, key: "'yield' expressions are not currently supported.", isEarly: true }, - Generators_are_not_currently_supported: { code: 9001, category: DiagnosticCategory.Error, key: "Generators are not currently supported.", isEarly: true }, + yield_expressions_are_not_currently_supported: { code: 9000, category: DiagnosticCategory.Error, key: "'yield' expressions are not currently supported." }, + Generators_are_not_currently_supported: { code: 9001, category: DiagnosticCategory.Error, key: "Generators are not currently supported." }, + The_arguments_object_cannot_be_referenced_in_an_arrow_function_Consider_using_a_standard_function_expression: { code: 9002, category: DiagnosticCategory.Error, key: "The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression." }, }; } \ No newline at end of file diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 49ee8eebcd9..5ee826812f2 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -9,8 +9,7 @@ }, "'{0}' expected.": { "category": "Error", - "code": 1005, - "isEarly": true + "code": 1005 }, "A file cannot have a reference to itself.": { "category": "Error", @@ -18,8 +17,7 @@ }, "Trailing comma not allowed.": { "category": "Error", - "code": 1009, - "isEarly": true + "code": 1009 }, "'*/' expected.": { "category": "Error", @@ -31,58 +29,47 @@ }, "Catch clause parameter cannot have a type annotation.": { "category": "Error", - "code": 1013, - "isEarly": true + "code": 1013 }, "A rest parameter must be last in a parameter list.": { "category": "Error", - "code": 1014, - "isEarly": true + "code": 1014 }, "Parameter cannot have question mark and initializer.": { "category": "Error", - "code": 1015, - "isEarly": true + "code": 1015 }, "A required parameter cannot follow an optional parameter.": { "category": "Error", - "code": 1016, - "isEarly": true + "code": 1016 }, "An index signature cannot have a rest parameter.": { "category": "Error", - "code": 1017, - "isEarly": true + "code": 1017 }, "An index signature parameter cannot have an accessibility modifier.": { "category": "Error", - "code": 1018, - "isEarly": true + "code": 1018 }, "An index signature parameter cannot have a question mark.": { "category": "Error", - "code": 1019, - "isEarly": true + "code": 1019 }, "An index signature parameter cannot have an initializer.": { "category": "Error", - "code": 1020, - "isEarly": true + "code": 1020 }, "An index signature must have a type annotation.": { "category": "Error", - "code": 1021, - "isEarly": true + "code": 1021 }, "An index signature parameter must have a type annotation.": { "category": "Error", - "code": 1022, - "isEarly": true + "code": 1022 }, "An index signature parameter type must be 'string' or 'number'.": { "category": "Error", - "code": 1023, - "isEarly": true + "code": 1023 }, "A class or interface declaration can only have one 'extends' clause.": { "category": "Error", @@ -102,23 +89,19 @@ }, "Accessibility modifier already seen.": { "category": "Error", - "code": 1028, - "isEarly": true + "code": 1028 }, "'{0}' modifier must precede '{1}' modifier.": { "category": "Error", - "code": 1029, - "isEarly": true + "code": 1029 }, "'{0}' modifier already seen.": { "category": "Error", - "code": 1030, - "isEarly": true + "code": 1030 }, "'{0}' modifier cannot appear on a class element.": { "category": "Error", - "code": 1031, - "isEarly": true + "code": 1031 }, "An interface declaration cannot have an 'implements' clause.": { "category": "Error", @@ -130,33 +113,27 @@ }, "Only ambient modules can use quoted names.": { "category": "Error", - "code": 1035, - "isEarly": true + "code": 1035 }, "Statements are not allowed in ambient contexts.": { "category": "Error", - "code": 1036, - "isEarly": true + "code": 1036 }, "A 'declare' modifier cannot be used in an already ambient context.": { "category": "Error", - "code": 1038, - "isEarly": true + "code": 1038 }, "Initializers are not allowed in ambient contexts.": { "category": "Error", - "code": 1039, - "isEarly": true + "code": 1039 }, "'{0}' modifier cannot appear on a module element.": { "category": "Error", - "code": 1044, - "isEarly": true + "code": 1044 }, "A 'declare' modifier cannot be used with an interface declaration.": { "category": "Error", - "code": 1045, - "isEarly": true + "code": 1045 }, "A 'declare' modifier is required for a top level declaration in a .d.ts file.": { "category": "Error", @@ -164,58 +141,47 @@ }, "A rest parameter cannot be optional.": { "category": "Error", - "code": 1047, - "isEarly": true + "code": 1047 }, "A rest parameter cannot have an initializer.": { "category": "Error", - "code": 1048, - "isEarly": true + "code": 1048 }, "A 'set' accessor must have exactly one parameter.": { "category": "Error", - "code": 1049, - "isEarly": true + "code": 1049 }, "A 'set' accessor cannot have an optional parameter.": { "category": "Error", - "code": 1051, - "isEarly": true + "code": 1051 }, "A 'set' accessor parameter cannot have an initializer.": { "category": "Error", - "code": 1052, - "isEarly": true + "code": 1052 }, "A 'set' accessor cannot have rest parameter.": { "category": "Error", - "code": 1053, - "isEarly": true + "code": 1053 }, "A 'get' accessor cannot have parameters.": { "category": "Error", - "code": 1054, - "isEarly": true + "code": 1054 }, "Accessors are only available when targeting ECMAScript 5 and higher.": { "category": "Error", - "code": 1056, - "isEarly": true + "code": 1056 }, "Enum member must have initializer.": { "category": "Error", - "code": 1061, - "isEarly": true + "code": 1061 }, "An export assignment cannot be used in an internal module.": { "category": "Error", - "code": 1063, - "isEarly": true + "code": 1063 }, "Ambient enum elements can only have integer literal initializers.": { "category": "Error", - "code": 1066, - "isEarly": true + "code": 1066 }, "Unexpected token. A constructor, method, accessor, or property was expected.": { "category": "Error", @@ -223,8 +189,7 @@ }, "A 'declare' modifier cannot be used with an import declaration.": { "category": "Error", - "code": 1079, - "isEarly": true + "code": 1079 }, "Invalid 'reference' directive syntax.": { "category": "Error", @@ -232,173 +197,139 @@ }, "Octal literals are not available when targeting ECMAScript 5 and higher.": { "category": "Error", - "code": 1085, - "isEarly": true + "code": 1085 }, "An accessor cannot be declared in an ambient context.": { "category": "Error", - "code": 1086, - "isEarly": true + "code": 1086 }, "'{0}' modifier cannot appear on a constructor declaration.": { "category": "Error", - "code": 1089, - "isEarly": true + "code": 1089 }, "'{0}' modifier cannot appear on a parameter.": { "category": "Error", - "code": 1090, - "isEarly": true + "code": 1090 }, "Only a single variable declaration is allowed in a 'for...in' statement.": { "category": "Error", - "code": 1091, - "isEarly": true + "code": 1091 }, "Type parameters cannot appear on a constructor declaration.": { "category": "Error", - "code": 1092, - "isEarly": true + "code": 1092 }, "Type annotation cannot appear on a constructor declaration.": { "category": "Error", - "code": 1093, - "isEarly": true + "code": 1093 }, "An accessor cannot have type parameters.": { "category": "Error", - "code": 1094, - "isEarly": true + "code": 1094 }, "A 'set' accessor cannot have a return type annotation.": { "category": "Error", - "code": 1095, - "isEarly": true + "code": 1095 }, "An index signature must have exactly one parameter.": { "category": "Error", - "code": 1096, - "isEarly": true + "code": 1096 }, "'{0}' list cannot be empty.": { "category": "Error", - "code": 1097, - "isEarly": true + "code": 1097 }, "Type parameter list cannot be empty.": { "category": "Error", - "code": 1098, - "isEarly": true + "code": 1098 }, "Type argument list cannot be empty.": { "category": "Error", - "code": 1099, - "isEarly": true + "code": 1099 }, "Invalid use of '{0}' in strict mode.": { "category": "Error", - "code": 1100, - "isEarly": true + "code": 1100 }, "'with' statements are not allowed in strict mode.": { "category": "Error", - "code": 1101, - "isEarly": true + "code": 1101 }, "'delete' cannot be called on an identifier in strict mode.": { "category": "Error", - "code": 1102, - "isEarly": true + "code": 1102 }, "A 'continue' statement can only be used within an enclosing iteration statement.": { "category": "Error", - "code": 1104, - "isEarly": true + "code": 1104 }, "A 'break' statement can only be used within an enclosing iteration or switch statement.": { "category": "Error", - "code": 1105, - "isEarly": true + "code": 1105 }, "Jump target cannot cross function boundary.": { "category": "Error", - "code": 1107, - "isEarly": true + "code": 1107 }, "A 'return' statement can only be used within a function body.": { "category": "Error", - "code": 1108, - "isEarly": true + "code": 1108 }, "Expression expected.": { "category": "Error", - "code": 1109, - "isEarly": true + "code": 1109 }, "Type expected.": { "category": "Error", - "code": 1110, - "isEarly": true + "code": 1110 }, "A class member cannot be declared optional.": { "category": "Error", - "code": 1112, - "isEarly": true + "code": 1112 }, "A 'default' clause cannot appear more than once in a 'switch' statement.": { "category": "Error", - "code": 1113, - "isEarly": true + "code": 1113 }, "Duplicate label '{0}'": { "category": "Error", - "code": 1114, - "isEarly": true + "code": 1114 }, "A 'continue' statement can only jump to a label of an enclosing iteration statement.": { "category": "Error", - "code": 1115, - "isEarly": true + "code": 1115 }, "A 'break' statement can only jump to a label of an enclosing statement.": { "category": "Error", - "code": 1116, - "isEarly": true + "code": 1116 }, "An object literal cannot have multiple properties with the same name in strict mode.": { "category": "Error", - "code": 1117, - "isEarly": true + "code": 1117 }, "An object literal cannot have multiple get/set accessors with the same name.": { "category": "Error", - "code": 1118, - "isEarly": true + "code": 1118 }, "An object literal cannot have property and accessor with the same name.": { "category": "Error", - "code": 1119, - "isEarly": true + "code": 1119 }, "An export assignment cannot have modifiers.": { "category": "Error", - "code": 1120, - "isEarly": true + "code": 1120 }, "Octal literals are not allowed in strict mode.": { "category": "Error", - "code": 1121, - "isEarly": true + "code": 1121 }, "A tuple type element list cannot be empty.": { "category": "Error", - "code": 1122, - "isEarly": true + "code": 1122 }, "Variable declaration list cannot be empty.": { "category": "Error", - "code": 1123, - "isEarly": true + "code": 1123 }, "Digit expected.": { "category": "Error", @@ -446,8 +377,7 @@ }, "Argument expression expected.": { "category": "Error", - "code": 1135, - "isEarly": true + "code": 1135 }, "Property assignment expected.": { "category": "Error", @@ -471,13 +401,11 @@ }, "String literal expected.": { "category": "Error", - "code": 1141, - "isEarly": true + "code": 1141 }, "Line break not permitted here.": { "category": "Error", - "code": 1142, - "isEarly": true + "code": 1142 }, "'{' or ';' expected.": { "category": "Error", @@ -485,8 +413,7 @@ }, "Modifiers not permitted on index signature members.": { "category": "Error", - "code": 1145, - "isEarly": true + "code": 1145 }, "Declaration expected.": { "category": "Error", @@ -494,8 +421,7 @@ }, "Import declarations in an internal module cannot reference an external module.": { "category": "Error", - "code": 1147, - "isEarly": true + "code": 1147 }, "Cannot compile external modules unless the '--module' flag is provided.": { "category": "Error", @@ -507,8 +433,7 @@ }, "'new T[]' cannot be used to create an array. Use 'new Array()' instead.": { "category": "Error", - "code": 1150, - "isEarly": true + "code": 1150 }, "'var', 'let' or 'const' expected.": { "category": "Error", @@ -516,33 +441,27 @@ }, "'let' declarations are only available when targeting ECMAScript 6 and higher.": { "category": "Error", - "code": 1153, - "isEarly": true + "code": 1153 }, "'const' declarations are only available when targeting ECMAScript 6 and higher.": { "category": "Error", - "code": 1154, - "isEarly": true + "code": 1154 }, "'const' declarations must be initialized": { "category": "Error", - "code": 1155, - "isEarly": true + "code": 1155 }, "'const' declarations can only be declared inside a block.": { "category": "Error", - "code": 1156, - "isEarly": true + "code": 1156 }, "'let' declarations can only be declared inside a block.": { "category": "Error", - "code": 1157, - "isEarly": true + "code": 1157 }, "Tagged templates are only available when targeting ECMAScript 6 and higher.": { "category": "Error", - "code": 1159, - "isEarly": true + "code": 1159 }, "Unterminated template literal.": { "category": "Error", @@ -554,48 +473,39 @@ }, "An object member cannot be declared optional.": { "category": "Error", - "code": 1162, - "isEarly": true + "code": 1162 }, "'yield' expression must be contained_within a generator declaration.": { "category": "Error", - "code": 1163, - "isEarly": true + "code": 1163 }, "Computed property names are not allowed in enums.": { "category": "Error", - "code": 1164, - "isEarly": true + "code": 1164 }, "Computed property names are not allowed in an ambient context.": { "category": "Error", - "code": 1165, - "isEarly": true + "code": 1165 }, "Computed property names are not allowed in class property declarations.": { "category": "Error", - "code": 1166, - "isEarly": true + "code": 1166 }, "Computed property names are only available when targeting ECMAScript 6 and higher.": { "category": "Error", - "code": 1167, - "isEarly": true + "code": 1167 }, "Computed property names are not allowed in method overloads.": { "category": "Error", - "code": 1168, - "isEarly": true + "code": 1168 }, "Computed property names are not allowed in interfaces.": { "category": "Error", - "code": 1169, - "isEarly": true + "code": 1169 }, "Computed property names are not allowed in type literals.": { "category": "Error", - "code": 1170, - "isEarly": true + "code": 1170 }, "A comma expression is not allowed in a computed property name.": { "category": "Error", @@ -603,28 +513,23 @@ }, "'extends' clause already seen.": { "category": "Error", - "code": 1172, - "isEarly": true + "code": 1172 }, "'extends' clause must precede 'implements' clause.": { "category": "Error", - "code": 1173, - "isEarly": true + "code": 1173 }, "Classes can only extend a single class.": { "category": "Error", - "code": 1174, - "isEarly": true + "code": 1174 }, "'implements' clause already seen.": { "category": "Error", - "code": 1175, - "isEarly": true + "code": 1175 }, "Interface declaration cannot have 'implements' clause.": { "category": "Error", - "code": 1176, - "isEarly": true + "code": 1176 }, "Binary digit expected.": { "category": "Error", @@ -648,18 +553,15 @@ }, "A destructuring declaration must have an initializer.": { "category": "Error", - "code": 1182, - "isEarly": true + "code": 1182 }, "Destructuring declarations are not allowed in ambient contexts.": { "category": "Error", - "code": 1183, - "isEarly": true + "code": 1183 }, "An implementation cannot be declared in ambient contexts.": { "category": "Error", - "code": 1184, - "isEarly": true + "code": 1184 }, "Modifiers cannot appear here.": { "category": "Error", @@ -1228,23 +1130,19 @@ }, "Block-scoped variable '{0}' used before its declaration.": { "category": "Error", - "code": 2448, - "isEarly": true + "code": 2448 }, "The operand of an increment or decrement operator cannot be a constant.": { "category": "Error", - "code": 2449, - "isEarly": true + "code": 2449 }, "Left-hand side of assignment expression cannot be a constant.": { "category": "Error", - "code": 2450, - "isEarly": true + "code": 2450 }, "Cannot redeclare block-scoped variable '{0}'.": { "category": "Error", - "code": 2451, - "isEarly": true + "code": 2451 }, "An enum member cannot have a numeric name.": { "category": "Error", @@ -1589,8 +1487,7 @@ }, "In 'const' enum declarations member initializer must be constant expression.": { "category": "Error", - "code": 4083, - "isEarly": true + "code": 4083 }, "'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", @@ -1598,8 +1495,7 @@ }, "A const enum member can only be accessed using a string literal.": { "category": "Error", - "code": 4085, - "isEarly": true + "code": 4085 }, "'const' enum member initializer was evaluated to a non-finite value.": { "category": "Error", @@ -1611,8 +1507,7 @@ }, "Property '{0}' does not exist on 'const' enum '{1}'.": { "category": "Error", - "code": 4088, - "isEarly": true + "code": 4088 }, "The current host does not support the '{0}' option.": { "category": "Error", @@ -1901,12 +1796,14 @@ }, "'yield' expressions are not currently supported.": { "category": "Error", - "code": 9000, - "isEarly": true + "code": 9000 }, "Generators are not currently supported.": { "category": "Error", - "code": 9001, - "isEarly": true + "code": 9001 + }, + "The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression.": { + "category": "Error", + "code": 9002 } } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 34978ed7fd6..b15a493de92 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1487,7 +1487,6 @@ module ts { // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compilerOnSave feature export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile?: SourceFile): EmitResult { - // var program = resolver.getProgram(); var compilerOptions = host.getCompilerOptions(); var languageVersion = compilerOptions.target || ScriptTarget.ES3; var sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap ? [] : undefined; @@ -2075,8 +2074,6 @@ module ts { return; } - Debug.assert(node.parent.kind !== SyntaxKind.TaggedTemplateExpression); - var emitOuterParens = isExpression(node.parent) && templateNeedsParens(node, node.parent); @@ -2154,10 +2151,9 @@ module ts { case SyntaxKind.CallExpression: case SyntaxKind.NewExpression: return (parent).expression === template; + case SyntaxKind.TaggedTemplateExpression: case SyntaxKind.ParenthesizedExpression: return false; - case SyntaxKind.TaggedTemplateExpression: - Debug.fail("Path should be unreachable; tagged templates not supported pre-ES6."); default: return comparePrecedenceToBinaryPlus(parent) !== Comparison.LessThan; } @@ -2177,7 +2173,6 @@ module ts { // // TODO (drosen): Note that we need to account for the upcoming 'yield' and // spread ('...') unary operators that are anticipated for ES6. - Debug.assert(languageVersion < ScriptTarget.ES6); switch (expression.kind) { case SyntaxKind.BinaryExpression: switch ((expression).operator) { @@ -2462,8 +2457,11 @@ module ts { function tryEmitConstantValue(node: PropertyAccessExpression | ElementAccessExpression): boolean { var constantValue = resolver.getConstantValue(node); if (constantValue !== undefined) { - var propertyName = node.kind === SyntaxKind.PropertyAccessExpression ? declarationNameToString((node).name) : getTextOfNode((node).argumentExpression); - write(constantValue.toString() + " /* " + propertyName + " */"); + write(constantValue.toString()); + if (!compilerOptions.removeComments) { + var propertyName: string = node.kind === SyntaxKind.PropertyAccessExpression ? declarationNameToString((node).name) : getTextOfNode((node).argumentExpression); + write(" /* " + propertyName + " */"); + } return true; } return false; @@ -2531,7 +2529,6 @@ module ts { } function emitTaggedTemplateExpression(node: TaggedTemplateExpression): void { - Debug.assert(languageVersion >= ScriptTarget.ES6, "Trying to emit a tagged template in pre-ES6 mode."); emit(node.tag); write(" "); emit(node.template); @@ -3240,6 +3237,10 @@ module ts { emitSignatureAndBody(node); } + function shouldEmitAsArrowFunction(node: FunctionLikeDeclaration): boolean { + return node.kind === SyntaxKind.ArrowFunction && languageVersion >= ScriptTarget.ES6; + } + function emitFunctionDeclaration(node: FunctionLikeDeclaration) { if (nodeIsMissing(node.body)) { return emitPinnedOrTripleSlashComments(node); @@ -3249,7 +3250,13 @@ module ts { // Methods will emit the comments as part of emitting method declaration emitLeadingComments(node); } - write("function "); + + // For targeting below es6, emit functions-like declaration including arrow function using function keyword. + // When targeting ES6, emit arrow function natively in ES6 by omitting function keyword and using fat arrow instead + if (!shouldEmitAsArrowFunction(node)) { + write("function "); + } + if (node.kind === SyntaxKind.FunctionDeclaration || (node.kind === SyntaxKind.FunctionExpression && node.name)) { emit(node.name); } @@ -3280,6 +3287,15 @@ module ts { decreaseIndent(); } + function emitSignatureParametersForArrow(node: FunctionLikeDeclaration) { + // Check whether the parameter list needs parentheses and preserve no-parenthesis + if (node.parameters.length === 1 && node.pos === node.parameters[0].pos) { + emit(node.parameters[0]); + return; + } + emitSignatureParameters(node); + } + function emitSignatureAndBody(node: FunctionLikeDeclaration) { var saveTempCount = tempCount; var saveTempVariables = tempVariables; @@ -3287,64 +3303,82 @@ module ts { tempCount = 0; tempVariables = undefined; tempParameters = undefined; - emitSignatureParameters(node); - write(" {"); - scopeEmitStart(node); - increaseIndent(); - emitDetachedComments(node.body.kind === SyntaxKind.Block ? (node.body).statements : node.body); - - var startIndex = 0; - if (node.body.kind === SyntaxKind.Block) { - startIndex = emitDirectivePrologues((node.body).statements, /*startWithNewLine*/ true); - } - var outPos = writer.getTextPos(); - emitCaptureThisForNodeIfNecessary(node); - emitDefaultValueAssignments(node); - emitRestParameter(node); - if (node.body.kind !== SyntaxKind.Block && outPos === writer.getTextPos()) { - decreaseIndent(); - write(" "); - emitStart(node.body); - write("return "); - - // Don't emit comments on this body. We'll have already taken care of it above - // when we called emitDetachedComments. - emitNode(node.body, /*disableComments:*/ true); - emitEnd(node.body); - write(";"); - emitTempDeclarations(/*newLine*/ false); - write(" "); - emitStart(node.body); - write("}"); - emitEnd(node.body); + // When targeting ES6, emit arrow function natively in ES6 + if (shouldEmitAsArrowFunction(node)) { + emitSignatureParametersForArrow(node); + write(" =>"); } else { - if (node.body.kind === SyntaxKind.Block) { - emitLinesStartingAt((node.body).statements, startIndex); - } - else { - writeLine(); - emitLeadingComments(node.body); - write("return "); - emit(node.body, /*disableComments:*/ true); - write(";"); - emitTrailingComments(node.body); - } - emitTempDeclarations(/*newLine*/ true); + emitSignatureParameters(node); + } + + write(" {"); + scopeEmitStart(node); + + if (!node.body) { writeLine(); + write("}"); + } + else { + increaseIndent(); + + emitDetachedComments(node.body.kind === SyntaxKind.Block ? (node.body).statements : node.body); + + var startIndex = 0; if (node.body.kind === SyntaxKind.Block) { - emitLeadingCommentsOfPosition((node.body).statements.end); - decreaseIndent(); - emitToken(SyntaxKind.CloseBraceToken,(node.body).statements.end); + startIndex = emitDirectivePrologues((node.body).statements, /*startWithNewLine*/ true); } - else { + var outPos = writer.getTextPos(); + + emitCaptureThisForNodeIfNecessary(node); + emitDefaultValueAssignments(node); + emitRestParameter(node); + if (node.body.kind !== SyntaxKind.Block && outPos === writer.getTextPos()) { decreaseIndent(); + write(" "); + emitStart(node.body); + write("return "); + + // Don't emit comments on this body. We'll have already taken care of it above + // when we called emitDetachedComments. + emitNode(node.body, /*disableComments:*/ true); + emitEnd(node.body); + write(";"); + emitTempDeclarations(/*newLine*/ false); + write(" "); emitStart(node.body); write("}"); emitEnd(node.body); } + else { + if (node.body.kind === SyntaxKind.Block) { + emitLinesStartingAt((node.body).statements, startIndex); + } + else { + writeLine(); + emitLeadingComments(node.body); + write("return "); + emit(node.body, /*disableComments:*/ true); + write(";"); + emitTrailingComments(node.body); + } + emitTempDeclarations(/*newLine*/ true); + writeLine(); + if (node.body.kind === SyntaxKind.Block) { + emitLeadingCommentsOfPosition((node.body).statements.end); + decreaseIndent(); + emitToken(SyntaxKind.CloseBraceToken, (node.body).statements.end); + } + else { + decreaseIndent(); + emitStart(node.body); + write("}"); + emitEnd(node.body); + } + } } + scopeEmitEnd(); if (node.flags & NodeFlags.Export) { writeLine(); @@ -3694,18 +3728,30 @@ module ts { write("["); emitExpressionForPropertyName(node.name); write("] = "); - if (node.initializer && !isConst(enumParent)) { - emit(node.initializer); - } - else { - write(resolver.getEnumMemberValue(node).toString()); - } + writeEnumMemberDeclarationValue(node); write("] = "); emitExpressionForPropertyName(node.name); emitEnd(node); write(";"); } + function writeEnumMemberDeclarationValue(member: EnumMember) { + if (!member.initializer || isConst(member.parent)) { + var value = resolver.getEnumMemberValue(member); + if (value !== undefined) { + write(value.toString()); + return; + } + } + + if (member.initializer) { + emit(member.initializer); + } + else { + write("undefined"); + } + } + function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration: ModuleDeclaration): ModuleDeclaration { if (moduleDeclaration.body.kind === SyntaxKind.ModuleDeclaration) { var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); @@ -4329,12 +4375,12 @@ module ts { } } - var hasSemanticErrors: boolean = false; - var isEmitBlocked: boolean = false; + var hasSemanticDiagnostics = false; + var isEmitBlocked = false; if (targetSourceFile === undefined) { // No targetSourceFile is specified (e.g. calling emitter from batch compiler) - hasSemanticErrors = resolver.hasSemanticErrors(); + hasSemanticDiagnostics = resolver.hasSemanticDiagnostics(); isEmitBlocked = host.isEmitBlocked(); forEach(host.getSourceFiles(), sourceFile => { @@ -4352,7 +4398,7 @@ module ts { // targetSourceFile is specified (e.g calling emitter from language service or calling getSemanticDiagnostic from language service) if (shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { // If shouldEmitToOwnFile returns true or targetSourceFile is an external module file, then emit targetSourceFile in its own output file - hasSemanticErrors = resolver.hasSemanticErrors(targetSourceFile); + hasSemanticDiagnostics = resolver.hasSemanticDiagnostics(targetSourceFile); isEmitBlocked = host.isEmitBlocked(targetSourceFile); var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); @@ -4363,7 +4409,7 @@ module ts { // Emit all, non-external-module file, into one single output file forEach(host.getSourceFiles(), sourceFile => { if (!shouldEmitToOwnFile(sourceFile, compilerOptions)) { - hasSemanticErrors = hasSemanticErrors || resolver.hasSemanticErrors(sourceFile); + hasSemanticDiagnostics = hasSemanticDiagnostics || resolver.hasSemanticDiagnostics(sourceFile); isEmitBlocked = isEmitBlocked || host.isEmitBlocked(sourceFile); } }); @@ -4375,7 +4421,7 @@ module ts { function emitFile(jsFilePath: string, sourceFile?: SourceFile) { if (!isEmitBlocked) { emitJavaScript(jsFilePath, sourceFile); - if (!hasSemanticErrors && compilerOptions.declaration) { + if (!hasSemanticDiagnostics && compilerOptions.declaration) { writeDeclarationFile(jsFilePath, sourceFile); } } @@ -4394,9 +4440,9 @@ module ts { emitResultStatus = EmitReturnStatus.AllOutputGenerationSkipped; } else if (hasEmitterError) { emitResultStatus = EmitReturnStatus.EmitErrorsEncountered; - } else if (hasSemanticErrors && compilerOptions.declaration) { + } else if (hasSemanticDiagnostics && compilerOptions.declaration) { emitResultStatus = EmitReturnStatus.DeclarationGenerationSkipped; - } else if (hasSemanticErrors && !compilerOptions.declaration) { + } else if (hasSemanticDiagnostics && !compilerOptions.declaration) { emitResultStatus = EmitReturnStatus.JSGeneratedWithSemanticErrors; } else { emitResultStatus = EmitReturnStatus.Succeeded; diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 06e63635232..a2a735bc1d8 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -113,14 +113,12 @@ module ts { return emitHost || (emitHost = createEmitHostFromProgram(program)); } - function hasEarlyErrors(sourceFile?: SourceFile): boolean { - return forEach(getDiagnosticsProducingTypeChecker().getDiagnostics(sourceFile), d => d.isEarly); - } - function isEmitBlocked(sourceFile?: SourceFile): boolean { - return getDiagnostics(sourceFile).length !== 0 || - hasEarlyErrors(sourceFile) || - (options.noEmitOnError && getDiagnosticsProducingTypeChecker().getDiagnostics(sourceFile).length !== 0); + if (options.noEmitOnError) { + return getDiagnostics(sourceFile).length !== 0 || getDiagnosticsProducingTypeChecker().getDiagnostics(sourceFile).length !== 0; + } + + return false; } function getDiagnosticsProducingTypeChecker() { diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts index ee5dc5104ff..52a9fb110db 100644 --- a/src/compiler/tsc.ts +++ b/src/compiler/tsc.ts @@ -2,7 +2,7 @@ /// module ts { - var version = "1.4.0.0"; + var version = "1.5.0.0"; export interface SourceFile { fileWatcher: FileWatcher; diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 80bdc875177..c8572c6b5c1 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -1080,6 +1080,7 @@ module ts { WriteOwnNameForAnyLike = 0x00000010, // Write symbol's own name instead of 'any' for any like types (eg. unknown, __resolving__ etc) WriteTypeArgumentsOfSignature = 0x00000020, // Write the type arguments instead of type parameters of the signature InElementType = 0x00000040, // Writing an array or union element type + UseFullyQualifiedType = 0x00000080, // Write out the fully qualified type name (eg. Module.Type, instead of Type) } export const enum SymbolFormatFlags { @@ -1122,7 +1123,7 @@ module ts { isTopLevelValueImportWithEntityName(node: ImportDeclaration): boolean; getNodeCheckFlags(node: Node): NodeCheckFlags; getEnumMemberValue(node: EnumMember): number; - hasSemanticErrors(sourceFile?: SourceFile): boolean; + hasSemanticDiagnostics(sourceFile?: SourceFile): boolean; isDeclarationVisible(node: Declaration): boolean; isImplementationOfOverload(node: FunctionLikeDeclaration): boolean; writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; @@ -1417,7 +1418,6 @@ module ts { key: string; category: DiagnosticCategory; code: number; - isEarly?: boolean; } // A linked list of formatted diagnostic messages to be used as part of a multiline message. @@ -1438,10 +1438,6 @@ module ts { messageText: string; category: DiagnosticCategory; code: number; - /** - * Early error - any error (can be produced at parsing\binding\typechecking step) that blocks emit - */ - isEarly?: boolean; } export enum DiagnosticCategory { diff --git a/src/harness/harness.ts b/src/harness/harness.ts index df73e52a605..85bd02c1179 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -107,7 +107,7 @@ module Utils { export function memoize(f: T): T { var cache: { [idx: string]: any } = {}; - return (() => { + return (function () { var key = Array.prototype.join.call(arguments); var cachedResult = cache[key]; if (cachedResult) { @@ -308,7 +308,6 @@ module Utils { assert.equal(d1.messageText, d2.messageText, "d1.messageText !== d2.messageText"); assert.equal(d1.category, d2.category, "d1.category !== d2.category"); assert.equal(d1.code, d2.code, "d1.code !== d2.code"); - assert.equal(d1.isEarly, d2.isEarly, "d1.isEarly !== d2.isEarly"); } } diff --git a/src/harness/loggedIO.ts b/src/harness/loggedIO.ts index c6d15c34a84..57035262581 100644 --- a/src/harness/loggedIO.ts +++ b/src/harness/loggedIO.ts @@ -138,7 +138,7 @@ module Playback { function recordReplay(original: T, underlying: any) { function createWrapper(record: T, replay: T): T { - return (() => { + return (function () { if (replayLog !== undefined) { return replay.apply(undefined, arguments); } else if (recordLog !== undefined) { diff --git a/src/harness/projectsRunner.ts b/src/harness/projectsRunner.ts index 52467fdffd6..9b16e93d8eb 100644 --- a/src/harness/projectsRunner.ts +++ b/src/harness/projectsRunner.ts @@ -186,7 +186,7 @@ class ProjectRunner extends RunnerBase { function createCompilerHost(): ts.CompilerHost { return { getSourceFile, - getDefaultLibFilename: options => options.target === ts.ScriptTarget.ES6 ? "lib.es6.d.ts" : "lib.d.ts", + getDefaultLibFilename: options => Harness.Compiler.defaultLibFileName, writeFile, getCurrentDirectory, getCanonicalFileName: Harness.Compiler.getCanonicalFileName, diff --git a/src/services/services.ts b/src/services/services.ts index 1c6f9859c7e..0d6dc073d38 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -9,7 +9,7 @@ /// module ts { - export var servicesVersion = "0.4" + export var servicesVersion = "0.5" export interface Node { getSourceFile(): SourceFile; diff --git a/tests/baselines/reference/ArrowFunction1.js b/tests/baselines/reference/ArrowFunction1.js new file mode 100644 index 00000000000..1923c3a1d8e --- /dev/null +++ b/tests/baselines/reference/ArrowFunction1.js @@ -0,0 +1,8 @@ +//// [ArrowFunction1.ts] +var v = (a: ) => { + +}; + +//// [ArrowFunction1.js] +var v = function (a) { +}; diff --git a/tests/baselines/reference/ArrowFunction2.js b/tests/baselines/reference/ArrowFunction2.js new file mode 100644 index 00000000000..fa6b8bf3b9e --- /dev/null +++ b/tests/baselines/reference/ArrowFunction2.js @@ -0,0 +1,8 @@ +//// [ArrowFunction2.ts] +var v = (a: b,) => { + +}; + +//// [ArrowFunction2.js] +var v = function (a) { +}; diff --git a/tests/baselines/reference/ArrowFunction3.js b/tests/baselines/reference/ArrowFunction3.js new file mode 100644 index 00000000000..8ce76f7da3b --- /dev/null +++ b/tests/baselines/reference/ArrowFunction3.js @@ -0,0 +1,8 @@ +//// [ArrowFunction3.ts] +var v = (a): => { + +}; + +//// [ArrowFunction3.js] +var v = function (a) { +}; diff --git a/tests/baselines/reference/ExportAssignment7.js b/tests/baselines/reference/ExportAssignment7.js new file mode 100644 index 00000000000..ce4f5d7bf09 --- /dev/null +++ b/tests/baselines/reference/ExportAssignment7.js @@ -0,0 +1,13 @@ +//// [ExportAssignment7.ts] +export class C { +} + +export = B; + +//// [ExportAssignment7.js] +var C = (function () { + function C() { + } + return C; +})(); +exports.C = C; diff --git a/tests/baselines/reference/ExportAssignment8.js b/tests/baselines/reference/ExportAssignment8.js new file mode 100644 index 00000000000..2f7ac9ee69f --- /dev/null +++ b/tests/baselines/reference/ExportAssignment8.js @@ -0,0 +1,13 @@ +//// [ExportAssignment8.ts] +export = B; + +export class C { +} + +//// [ExportAssignment8.js] +var C = (function () { + function C() { + } + return C; +})(); +exports.C = C; diff --git a/tests/baselines/reference/ExportObjectLiteralAndObjectTypeLiteralWithAccessibleTypesInNestedMemberTypeAnnotations.js b/tests/baselines/reference/ExportObjectLiteralAndObjectTypeLiteralWithAccessibleTypesInNestedMemberTypeAnnotations.js new file mode 100644 index 00000000000..44c19685743 --- /dev/null +++ b/tests/baselines/reference/ExportObjectLiteralAndObjectTypeLiteralWithAccessibleTypesInNestedMemberTypeAnnotations.js @@ -0,0 +1,25 @@ +//// [ExportObjectLiteralAndObjectTypeLiteralWithAccessibleTypesInNestedMemberTypeAnnotations.ts] +module A { + + class Point { + constructor(public x: number, public y: number) { } + } + + export var UnitSquare : { + top: { left: Point, right: Point }, + bottom: { left: Point, right: Point } + } = null; +} + +//// [ExportObjectLiteralAndObjectTypeLiteralWithAccessibleTypesInNestedMemberTypeAnnotations.js] +var A; +(function (A) { + var Point = (function () { + function Point(x, y) { + this.x = x; + this.y = y; + } + return Point; + })(); + A.UnitSquare = null; +})(A || (A = {})); diff --git a/tests/baselines/reference/FunctionDeclaration10_es6.js b/tests/baselines/reference/FunctionDeclaration10_es6.js new file mode 100644 index 00000000000..51694533964 --- /dev/null +++ b/tests/baselines/reference/FunctionDeclaration10_es6.js @@ -0,0 +1,8 @@ +//// [FunctionDeclaration10_es6.ts] +function * foo(a = yield => yield) { +} + +//// [FunctionDeclaration10_es6.js] +function foo(a) { + if (a === void 0) { a = function (yield) { return yield; }; } +} diff --git a/tests/baselines/reference/FunctionDeclaration11_es6.js b/tests/baselines/reference/FunctionDeclaration11_es6.js new file mode 100644 index 00000000000..ba497b3e529 --- /dev/null +++ b/tests/baselines/reference/FunctionDeclaration11_es6.js @@ -0,0 +1,7 @@ +//// [FunctionDeclaration11_es6.ts] +function * yield() { +} + +//// [FunctionDeclaration11_es6.js] +function yield() { +} diff --git a/tests/baselines/reference/FunctionDeclaration12_es6.js b/tests/baselines/reference/FunctionDeclaration12_es6.js new file mode 100644 index 00000000000..da9cea3f9c6 --- /dev/null +++ b/tests/baselines/reference/FunctionDeclaration12_es6.js @@ -0,0 +1,6 @@ +//// [FunctionDeclaration12_es6.ts] +var v = function * yield() { } + +//// [FunctionDeclaration12_es6.js] +var v = , yield = function () { +}; diff --git a/tests/baselines/reference/FunctionDeclaration13_es6.js b/tests/baselines/reference/FunctionDeclaration13_es6.js new file mode 100644 index 00000000000..4c82b037569 --- /dev/null +++ b/tests/baselines/reference/FunctionDeclaration13_es6.js @@ -0,0 +1,12 @@ +//// [FunctionDeclaration13_es6.ts] +function * foo() { + // Legal to use 'yield' in a type context. + var v: yield; +} + + +//// [FunctionDeclaration13_es6.js] +function foo() { + // Legal to use 'yield' in a type context. + var v; +} diff --git a/tests/baselines/reference/FunctionDeclaration1_es6.js b/tests/baselines/reference/FunctionDeclaration1_es6.js new file mode 100644 index 00000000000..262c7ea02fb --- /dev/null +++ b/tests/baselines/reference/FunctionDeclaration1_es6.js @@ -0,0 +1,7 @@ +//// [FunctionDeclaration1_es6.ts] +function * foo() { +} + +//// [FunctionDeclaration1_es6.js] +function foo() { +} diff --git a/tests/baselines/reference/FunctionDeclaration5_es6.js b/tests/baselines/reference/FunctionDeclaration5_es6.js new file mode 100644 index 00000000000..2530baa220c --- /dev/null +++ b/tests/baselines/reference/FunctionDeclaration5_es6.js @@ -0,0 +1,8 @@ +//// [FunctionDeclaration5_es6.ts] +function*foo(yield) { +} + +//// [FunctionDeclaration5_es6.js] +yield; +{ +} diff --git a/tests/baselines/reference/FunctionDeclaration6_es6.js b/tests/baselines/reference/FunctionDeclaration6_es6.js new file mode 100644 index 00000000000..07b3ff52212 --- /dev/null +++ b/tests/baselines/reference/FunctionDeclaration6_es6.js @@ -0,0 +1,8 @@ +//// [FunctionDeclaration6_es6.ts] +function*foo(a = yield) { +} + +//// [FunctionDeclaration6_es6.js] +function foo(a) { + if (a === void 0) { a = yield; } +} diff --git a/tests/baselines/reference/FunctionDeclaration7_es6.js b/tests/baselines/reference/FunctionDeclaration7_es6.js new file mode 100644 index 00000000000..661e1668e0f --- /dev/null +++ b/tests/baselines/reference/FunctionDeclaration7_es6.js @@ -0,0 +1,14 @@ +//// [FunctionDeclaration7_es6.ts] +function*bar() { + // 'yield' here is an identifier, and not a yield expression. + function*foo(a = yield) { + } +} + +//// [FunctionDeclaration7_es6.js] +function bar() { + // 'yield' here is an identifier, and not a yield expression. + function foo(a) { + if (a === void 0) { a = yield; } + } +} diff --git a/tests/baselines/reference/FunctionDeclaration8_es6.js b/tests/baselines/reference/FunctionDeclaration8_es6.js new file mode 100644 index 00000000000..5f9f0a2a49e --- /dev/null +++ b/tests/baselines/reference/FunctionDeclaration8_es6.js @@ -0,0 +1,5 @@ +//// [FunctionDeclaration8_es6.ts] +var v = { [yield]: foo } + +//// [FunctionDeclaration8_es6.js] +var v = { [yield]: foo }; diff --git a/tests/baselines/reference/FunctionDeclaration9_es6.js b/tests/baselines/reference/FunctionDeclaration9_es6.js new file mode 100644 index 00000000000..388275ed4fa --- /dev/null +++ b/tests/baselines/reference/FunctionDeclaration9_es6.js @@ -0,0 +1,9 @@ +//// [FunctionDeclaration9_es6.ts] +function * foo() { + var v = { [yield]: foo } +} + +//// [FunctionDeclaration9_es6.js] +function foo() { + var v = { []: foo }; +} diff --git a/tests/baselines/reference/FunctionExpression1_es6.js b/tests/baselines/reference/FunctionExpression1_es6.js new file mode 100644 index 00000000000..7c8d82f4ca8 --- /dev/null +++ b/tests/baselines/reference/FunctionExpression1_es6.js @@ -0,0 +1,6 @@ +//// [FunctionExpression1_es6.ts] +var v = function * () { } + +//// [FunctionExpression1_es6.js] +var v = function () { +}; diff --git a/tests/baselines/reference/FunctionExpression2_es6.js b/tests/baselines/reference/FunctionExpression2_es6.js new file mode 100644 index 00000000000..0a2468bcb8c --- /dev/null +++ b/tests/baselines/reference/FunctionExpression2_es6.js @@ -0,0 +1,6 @@ +//// [FunctionExpression2_es6.ts] +var v = function * foo() { } + +//// [FunctionExpression2_es6.js] +var v = function foo() { +}; diff --git a/tests/baselines/reference/FunctionPropertyAssignments1_es6.js b/tests/baselines/reference/FunctionPropertyAssignments1_es6.js new file mode 100644 index 00000000000..a451dcfb363 --- /dev/null +++ b/tests/baselines/reference/FunctionPropertyAssignments1_es6.js @@ -0,0 +1,6 @@ +//// [FunctionPropertyAssignments1_es6.ts] +var v = { *foo() { } } + +//// [FunctionPropertyAssignments1_es6.js] +var v = { foo: function () { +} }; diff --git a/tests/baselines/reference/FunctionPropertyAssignments2_es6.js b/tests/baselines/reference/FunctionPropertyAssignments2_es6.js new file mode 100644 index 00000000000..5338afeef39 --- /dev/null +++ b/tests/baselines/reference/FunctionPropertyAssignments2_es6.js @@ -0,0 +1,6 @@ +//// [FunctionPropertyAssignments2_es6.ts] +var v = { *() { } } + +//// [FunctionPropertyAssignments2_es6.js] +var v = { : function () { +} }; diff --git a/tests/baselines/reference/FunctionPropertyAssignments3_es6.js b/tests/baselines/reference/FunctionPropertyAssignments3_es6.js new file mode 100644 index 00000000000..7b3adb771f3 --- /dev/null +++ b/tests/baselines/reference/FunctionPropertyAssignments3_es6.js @@ -0,0 +1,6 @@ +//// [FunctionPropertyAssignments3_es6.ts] +var v = { *{ } } + +//// [FunctionPropertyAssignments3_es6.js] +var v = { : function () { +} }; diff --git a/tests/baselines/reference/FunctionPropertyAssignments4_es6.js b/tests/baselines/reference/FunctionPropertyAssignments4_es6.js new file mode 100644 index 00000000000..595f7fc9124 --- /dev/null +++ b/tests/baselines/reference/FunctionPropertyAssignments4_es6.js @@ -0,0 +1,6 @@ +//// [FunctionPropertyAssignments4_es6.ts] +var v = { * } + +//// [FunctionPropertyAssignments4_es6.js] +var v = { : function () { +} }; diff --git a/tests/baselines/reference/FunctionPropertyAssignments5_es6.js b/tests/baselines/reference/FunctionPropertyAssignments5_es6.js new file mode 100644 index 00000000000..2bfc675acff --- /dev/null +++ b/tests/baselines/reference/FunctionPropertyAssignments5_es6.js @@ -0,0 +1,6 @@ +//// [FunctionPropertyAssignments5_es6.ts] +var v = { *[foo()]() { } } + +//// [FunctionPropertyAssignments5_es6.js] +var v = { [foo()]: function () { +} }; diff --git a/tests/baselines/reference/FunctionPropertyAssignments6_es6.js b/tests/baselines/reference/FunctionPropertyAssignments6_es6.js new file mode 100644 index 00000000000..6bd636be73a --- /dev/null +++ b/tests/baselines/reference/FunctionPropertyAssignments6_es6.js @@ -0,0 +1,6 @@ +//// [FunctionPropertyAssignments6_es6.ts] +var v = { *() { } } + +//// [FunctionPropertyAssignments6_es6.js] +var v = { : function () { +} }; diff --git a/tests/baselines/reference/MemberAccessorDeclaration15.js b/tests/baselines/reference/MemberAccessorDeclaration15.js new file mode 100644 index 00000000000..41ed265a878 --- /dev/null +++ b/tests/baselines/reference/MemberAccessorDeclaration15.js @@ -0,0 +1,17 @@ +//// [MemberAccessorDeclaration15.ts] +class C { + set Foo(public a: number) { } +} + +//// [MemberAccessorDeclaration15.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "Foo", { + set: function (a) { + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/MemberFunctionDeclaration1_es6.js b/tests/baselines/reference/MemberFunctionDeclaration1_es6.js new file mode 100644 index 00000000000..86e7c9d418a --- /dev/null +++ b/tests/baselines/reference/MemberFunctionDeclaration1_es6.js @@ -0,0 +1,13 @@ +//// [MemberFunctionDeclaration1_es6.ts] +class C { + *foo() { } +} + +//// [MemberFunctionDeclaration1_es6.js] +var C = (function () { + function C() { + } + C.prototype.foo = function () { + }; + return C; +})(); diff --git a/tests/baselines/reference/MemberFunctionDeclaration2_es6.js b/tests/baselines/reference/MemberFunctionDeclaration2_es6.js new file mode 100644 index 00000000000..efd60844dc7 --- /dev/null +++ b/tests/baselines/reference/MemberFunctionDeclaration2_es6.js @@ -0,0 +1,13 @@ +//// [MemberFunctionDeclaration2_es6.ts] +class C { + public * foo() { } +} + +//// [MemberFunctionDeclaration2_es6.js] +var C = (function () { + function C() { + } + C.prototype.foo = function () { + }; + return C; +})(); diff --git a/tests/baselines/reference/MemberFunctionDeclaration3_es6.js b/tests/baselines/reference/MemberFunctionDeclaration3_es6.js new file mode 100644 index 00000000000..357f9175b42 --- /dev/null +++ b/tests/baselines/reference/MemberFunctionDeclaration3_es6.js @@ -0,0 +1,13 @@ +//// [MemberFunctionDeclaration3_es6.ts] +class C { + *[foo]() { } +} + +//// [MemberFunctionDeclaration3_es6.js] +var C = (function () { + function C() { + } + C.prototype[foo] = function () { + }; + return C; +})(); diff --git a/tests/baselines/reference/MemberFunctionDeclaration4_es6.js b/tests/baselines/reference/MemberFunctionDeclaration4_es6.js new file mode 100644 index 00000000000..9c6d76bfca5 --- /dev/null +++ b/tests/baselines/reference/MemberFunctionDeclaration4_es6.js @@ -0,0 +1,13 @@ +//// [MemberFunctionDeclaration4_es6.ts] +class C { + *() { } +} + +//// [MemberFunctionDeclaration4_es6.js] +var C = (function () { + function C() { + } + C.prototype. = function () { + }; + return C; +})(); diff --git a/tests/baselines/reference/MemberFunctionDeclaration5_es6.js b/tests/baselines/reference/MemberFunctionDeclaration5_es6.js new file mode 100644 index 00000000000..6b43b18fe39 --- /dev/null +++ b/tests/baselines/reference/MemberFunctionDeclaration5_es6.js @@ -0,0 +1,11 @@ +//// [MemberFunctionDeclaration5_es6.ts] +class C { + * +} + +//// [MemberFunctionDeclaration5_es6.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/MemberFunctionDeclaration6_es6.js b/tests/baselines/reference/MemberFunctionDeclaration6_es6.js new file mode 100644 index 00000000000..ef9c9248763 --- /dev/null +++ b/tests/baselines/reference/MemberFunctionDeclaration6_es6.js @@ -0,0 +1,11 @@ +//// [MemberFunctionDeclaration6_es6.ts] +class C { + *foo +} + +//// [MemberFunctionDeclaration6_es6.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/MemberFunctionDeclaration7_es6.js b/tests/baselines/reference/MemberFunctionDeclaration7_es6.js new file mode 100644 index 00000000000..211713c6e14 --- /dev/null +++ b/tests/baselines/reference/MemberFunctionDeclaration7_es6.js @@ -0,0 +1,13 @@ +//// [MemberFunctionDeclaration7_es6.ts] +class C { + *foo() { } +} + +//// [MemberFunctionDeclaration7_es6.js] +var C = (function () { + function C() { + } + C.prototype.foo = function () { + }; + return C; +})(); diff --git a/tests/baselines/reference/MemberFunctionDeclaration8_es6.js b/tests/baselines/reference/MemberFunctionDeclaration8_es6.js new file mode 100644 index 00000000000..8e23a5ec995 --- /dev/null +++ b/tests/baselines/reference/MemberFunctionDeclaration8_es6.js @@ -0,0 +1,22 @@ +//// [MemberFunctionDeclaration8_es6.ts] +class C { + foo() { + // Make sure we don't think of *bar as the start of a generator method. + if (a) # * bar; + return bar; + } +} + +//// [MemberFunctionDeclaration8_es6.js] +var C = (function () { + function C() { + } + C.prototype.foo = function () { + // Make sure we don't think of *bar as the start of a generator method. + if (a) + ; + * bar; + return bar; + }; + return C; +})(); diff --git a/tests/baselines/reference/Protected1.js b/tests/baselines/reference/Protected1.js new file mode 100644 index 00000000000..eebce2f4ecc --- /dev/null +++ b/tests/baselines/reference/Protected1.js @@ -0,0 +1,10 @@ +//// [Protected1.ts] +protected class C { +} + +//// [Protected1.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/Protected2.js b/tests/baselines/reference/Protected2.js new file mode 100644 index 00000000000..6675d9d50fb --- /dev/null +++ b/tests/baselines/reference/Protected2.js @@ -0,0 +1,5 @@ +//// [Protected2.ts] +protected module M { +} + +//// [Protected2.js] diff --git a/tests/baselines/reference/Protected3.js b/tests/baselines/reference/Protected3.js new file mode 100644 index 00000000000..4c4d5e2a12c --- /dev/null +++ b/tests/baselines/reference/Protected3.js @@ -0,0 +1,11 @@ +//// [Protected3.ts] +class C { + protected constructor() { } +} + +//// [Protected3.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/Protected4.js b/tests/baselines/reference/Protected4.js new file mode 100644 index 00000000000..665a182ef33 --- /dev/null +++ b/tests/baselines/reference/Protected4.js @@ -0,0 +1,13 @@ +//// [Protected4.ts] +class C { + protected public m() { } +} + +//// [Protected4.js] +var C = (function () { + function C() { + } + C.prototype.m = function () { + }; + return C; +})(); diff --git a/tests/baselines/reference/Protected6.js b/tests/baselines/reference/Protected6.js new file mode 100644 index 00000000000..004f30b27f8 --- /dev/null +++ b/tests/baselines/reference/Protected6.js @@ -0,0 +1,13 @@ +//// [Protected6.ts] +class C { + static protected m() { } +} + +//// [Protected6.js] +var C = (function () { + function C() { + } + C.m = function () { + }; + return C; +})(); diff --git a/tests/baselines/reference/Protected7.js b/tests/baselines/reference/Protected7.js new file mode 100644 index 00000000000..466f6909d67 --- /dev/null +++ b/tests/baselines/reference/Protected7.js @@ -0,0 +1,13 @@ +//// [Protected7.ts] +class C { + protected private m() { } +} + +//// [Protected7.js] +var C = (function () { + function C() { + } + C.prototype.m = function () { + }; + return C; +})(); diff --git a/tests/baselines/reference/TemplateExpression1.js b/tests/baselines/reference/TemplateExpression1.js new file mode 100644 index 00000000000..c4437260084 --- /dev/null +++ b/tests/baselines/reference/TemplateExpression1.js @@ -0,0 +1,5 @@ +//// [TemplateExpression1.ts] +var v = `foo ${ a + +//// [TemplateExpression1.js] +var v = "foo " + a; diff --git a/tests/baselines/reference/TupleType3.js b/tests/baselines/reference/TupleType3.js new file mode 100644 index 00000000000..8d357a77be7 --- /dev/null +++ b/tests/baselines/reference/TupleType3.js @@ -0,0 +1,5 @@ +//// [TupleType3.ts] +var v: [] + +//// [TupleType3.js] +var v; diff --git a/tests/baselines/reference/TupleType4.js b/tests/baselines/reference/TupleType4.js new file mode 100644 index 00000000000..aaa660f95d9 --- /dev/null +++ b/tests/baselines/reference/TupleType4.js @@ -0,0 +1,5 @@ +//// [TupleType4.ts] +var v: [ + +//// [TupleType4.js] +var v; diff --git a/tests/baselines/reference/TupleType5.js b/tests/baselines/reference/TupleType5.js new file mode 100644 index 00000000000..5e9a0a580be --- /dev/null +++ b/tests/baselines/reference/TupleType5.js @@ -0,0 +1,5 @@ +//// [TupleType5.ts] +var v: [number,] + +//// [TupleType5.js] +var v; diff --git a/tests/baselines/reference/TwoInternalModulesThatMergeEachWithExportedLocalVarsOfTheSameName.js b/tests/baselines/reference/TwoInternalModulesThatMergeEachWithExportedLocalVarsOfTheSameName.js new file mode 100644 index 00000000000..c7f55d0a2df --- /dev/null +++ b/tests/baselines/reference/TwoInternalModulesThatMergeEachWithExportedLocalVarsOfTheSameName.js @@ -0,0 +1,60 @@ +//// [tests/cases/conformance/internalModules/DeclarationMerging/TwoInternalModulesThatMergeEachWithExportedLocalVarsOfTheSameName.ts] //// + +//// [part1.ts] +export module A { + export interface Point { + x: number; + y: number; + } + + export module Utils { + export function mirror(p: T) { + return { x: p.y, y: p.x }; + } + } + + export var Origin: Point = { x: 0, y: 0 }; +} + +//// [part2.ts] +export module A { + // collision with 'Origin' var in other part of merged module + export var Origin: Point = { x: 0, y: 0 }; + + export module Utils { + export class Plane { + constructor(public tl: Point, public br: Point) { } + } + } +} + + +//// [part1.js] +var A; +(function (A) { + var Utils; + (function (Utils) { + function mirror(p) { + return { x: p.y, y: p.x }; + } + Utils.mirror = mirror; + })(Utils = A.Utils || (A.Utils = {})); + A.Origin = { x: 0, y: 0 }; +})(A = exports.A || (exports.A = {})); +//// [part2.js] +var A; +(function (A) { + // collision with 'Origin' var in other part of merged module + A.Origin = { x: 0, y: 0 }; + var Utils; + (function (Utils) { + var Plane = (function () { + function Plane(tl, br) { + this.tl = tl; + this.br = br; + } + return Plane; + })(); + Utils.Plane = Plane; + })(Utils = A.Utils || (A.Utils = {})); +})(A = exports.A || (exports.A = {})); diff --git a/tests/baselines/reference/TypeArgumentList1.js b/tests/baselines/reference/TypeArgumentList1.js new file mode 100644 index 00000000000..b87b310a9af --- /dev/null +++ b/tests/baselines/reference/TypeArgumentList1.js @@ -0,0 +1,5 @@ +//// [TypeArgumentList1.ts] +Foo(4, 5, 6); + +//// [TypeArgumentList1.js] +Foo(4, 5, 6); diff --git a/tests/baselines/reference/VariableDeclaration10_es6.js b/tests/baselines/reference/VariableDeclaration10_es6.js new file mode 100644 index 00000000000..14f47cea04d --- /dev/null +++ b/tests/baselines/reference/VariableDeclaration10_es6.js @@ -0,0 +1,5 @@ +//// [VariableDeclaration10_es6.ts] +let a: number = 1 + +//// [VariableDeclaration10_es6.js] +let a = 1; diff --git a/tests/baselines/reference/VariableDeclaration11_es6.js b/tests/baselines/reference/VariableDeclaration11_es6.js new file mode 100644 index 00000000000..83eec6d9a13 --- /dev/null +++ b/tests/baselines/reference/VariableDeclaration11_es6.js @@ -0,0 +1,7 @@ +//// [VariableDeclaration11_es6.ts] +"use strict"; +let + +//// [VariableDeclaration11_es6.js] +"use strict"; +let ; diff --git a/tests/baselines/reference/VariableDeclaration1_es6.js b/tests/baselines/reference/VariableDeclaration1_es6.js new file mode 100644 index 00000000000..26433bd88c3 --- /dev/null +++ b/tests/baselines/reference/VariableDeclaration1_es6.js @@ -0,0 +1,5 @@ +//// [VariableDeclaration1_es6.ts] +const + +//// [VariableDeclaration1_es6.js] +const ; diff --git a/tests/baselines/reference/VariableDeclaration2_es6.js b/tests/baselines/reference/VariableDeclaration2_es6.js new file mode 100644 index 00000000000..a955315a2f0 --- /dev/null +++ b/tests/baselines/reference/VariableDeclaration2_es6.js @@ -0,0 +1,5 @@ +//// [VariableDeclaration2_es6.ts] +const a + +//// [VariableDeclaration2_es6.js] +const a; diff --git a/tests/baselines/reference/VariableDeclaration3_es6.js b/tests/baselines/reference/VariableDeclaration3_es6.js new file mode 100644 index 00000000000..4be8a3daf38 --- /dev/null +++ b/tests/baselines/reference/VariableDeclaration3_es6.js @@ -0,0 +1,5 @@ +//// [VariableDeclaration3_es6.ts] +const a = 1 + +//// [VariableDeclaration3_es6.js] +const a = 1; diff --git a/tests/baselines/reference/VariableDeclaration4_es6.js b/tests/baselines/reference/VariableDeclaration4_es6.js new file mode 100644 index 00000000000..7a9934e052b --- /dev/null +++ b/tests/baselines/reference/VariableDeclaration4_es6.js @@ -0,0 +1,5 @@ +//// [VariableDeclaration4_es6.ts] +const a: number + +//// [VariableDeclaration4_es6.js] +const a; diff --git a/tests/baselines/reference/VariableDeclaration5_es6.js b/tests/baselines/reference/VariableDeclaration5_es6.js new file mode 100644 index 00000000000..e6a3c175651 --- /dev/null +++ b/tests/baselines/reference/VariableDeclaration5_es6.js @@ -0,0 +1,5 @@ +//// [VariableDeclaration5_es6.ts] +const a: number = 1 + +//// [VariableDeclaration5_es6.js] +const a = 1; diff --git a/tests/baselines/reference/VariableDeclaration7_es6.js b/tests/baselines/reference/VariableDeclaration7_es6.js new file mode 100644 index 00000000000..00ab95503a6 --- /dev/null +++ b/tests/baselines/reference/VariableDeclaration7_es6.js @@ -0,0 +1,5 @@ +//// [VariableDeclaration7_es6.ts] +let a + +//// [VariableDeclaration7_es6.js] +let a; diff --git a/tests/baselines/reference/VariableDeclaration8_es6.js b/tests/baselines/reference/VariableDeclaration8_es6.js new file mode 100644 index 00000000000..9178871ef65 --- /dev/null +++ b/tests/baselines/reference/VariableDeclaration8_es6.js @@ -0,0 +1,5 @@ +//// [VariableDeclaration8_es6.ts] +let a = 1 + +//// [VariableDeclaration8_es6.js] +let a = 1; diff --git a/tests/baselines/reference/VariableDeclaration9_es6.js b/tests/baselines/reference/VariableDeclaration9_es6.js new file mode 100644 index 00000000000..b22c5691eb2 --- /dev/null +++ b/tests/baselines/reference/VariableDeclaration9_es6.js @@ -0,0 +1,5 @@ +//// [VariableDeclaration9_es6.ts] +let a: number + +//// [VariableDeclaration9_es6.js] +let a; diff --git a/tests/baselines/reference/YieldExpression10_es6.js b/tests/baselines/reference/YieldExpression10_es6.js new file mode 100644 index 00000000000..f111e6e1bdf --- /dev/null +++ b/tests/baselines/reference/YieldExpression10_es6.js @@ -0,0 +1,11 @@ +//// [YieldExpression10_es6.ts] +var v = { * foo() { + yield(foo); + } +} + + +//// [YieldExpression10_es6.js] +var v = { foo: function () { + ; +} }; diff --git a/tests/baselines/reference/YieldExpression11_es6.js b/tests/baselines/reference/YieldExpression11_es6.js new file mode 100644 index 00000000000..306cef3051e --- /dev/null +++ b/tests/baselines/reference/YieldExpression11_es6.js @@ -0,0 +1,16 @@ +//// [YieldExpression11_es6.ts] +class C { + *foo() { + yield(foo); + } +} + +//// [YieldExpression11_es6.js] +var C = (function () { + function C() { + } + C.prototype.foo = function () { + ; + }; + return C; +})(); diff --git a/tests/baselines/reference/YieldExpression12_es6.js b/tests/baselines/reference/YieldExpression12_es6.js new file mode 100644 index 00000000000..020340fc4a3 --- /dev/null +++ b/tests/baselines/reference/YieldExpression12_es6.js @@ -0,0 +1,14 @@ +//// [YieldExpression12_es6.ts] +class C { + constructor() { + yield foo + } +} + +//// [YieldExpression12_es6.js] +var C = (function () { + function C() { + ; + } + return C; +})(); diff --git a/tests/baselines/reference/YieldExpression13_es6.js b/tests/baselines/reference/YieldExpression13_es6.js new file mode 100644 index 00000000000..328fc80dbdd --- /dev/null +++ b/tests/baselines/reference/YieldExpression13_es6.js @@ -0,0 +1,7 @@ +//// [YieldExpression13_es6.ts] +function* foo() { yield } + +//// [YieldExpression13_es6.js] +function foo() { + ; +} diff --git a/tests/baselines/reference/YieldExpression14_es6.js b/tests/baselines/reference/YieldExpression14_es6.js new file mode 100644 index 00000000000..132890b1b6a --- /dev/null +++ b/tests/baselines/reference/YieldExpression14_es6.js @@ -0,0 +1,16 @@ +//// [YieldExpression14_es6.ts] +class C { + foo() { + yield foo + } +} + +//// [YieldExpression14_es6.js] +var C = (function () { + function C() { + } + C.prototype.foo = function () { + ; + }; + return C; +})(); diff --git a/tests/baselines/reference/YieldExpression15_es6.js b/tests/baselines/reference/YieldExpression15_es6.js new file mode 100644 index 00000000000..13e6b92a577 --- /dev/null +++ b/tests/baselines/reference/YieldExpression15_es6.js @@ -0,0 +1,9 @@ +//// [YieldExpression15_es6.ts] +var v = () => { + yield foo + } + +//// [YieldExpression15_es6.js] +var v = function () { + ; +}; diff --git a/tests/baselines/reference/YieldExpression16_es6.js b/tests/baselines/reference/YieldExpression16_es6.js new file mode 100644 index 00000000000..ee73439a2d5 --- /dev/null +++ b/tests/baselines/reference/YieldExpression16_es6.js @@ -0,0 +1,13 @@ +//// [YieldExpression16_es6.ts] +function* foo() { + function bar() { + yield foo; + } +} + +//// [YieldExpression16_es6.js] +function foo() { + function bar() { + ; + } +} diff --git a/tests/baselines/reference/YieldExpression17_es6.js b/tests/baselines/reference/YieldExpression17_es6.js new file mode 100644 index 00000000000..6fd39844d80 --- /dev/null +++ b/tests/baselines/reference/YieldExpression17_es6.js @@ -0,0 +1,7 @@ +//// [YieldExpression17_es6.ts] +var v = { get foo() { yield foo; } } + +//// [YieldExpression17_es6.js] +var v = { get foo() { + ; +} }; diff --git a/tests/baselines/reference/YieldExpression18_es6.js b/tests/baselines/reference/YieldExpression18_es6.js new file mode 100644 index 00000000000..7fb630b9c08 --- /dev/null +++ b/tests/baselines/reference/YieldExpression18_es6.js @@ -0,0 +1,7 @@ +//// [YieldExpression18_es6.ts] +"use strict"; +yield(foo); + +//// [YieldExpression18_es6.js] +"use strict"; +; diff --git a/tests/baselines/reference/YieldExpression19_es6.js b/tests/baselines/reference/YieldExpression19_es6.js new file mode 100644 index 00000000000..91643e09b0e --- /dev/null +++ b/tests/baselines/reference/YieldExpression19_es6.js @@ -0,0 +1,17 @@ +//// [YieldExpression19_es6.ts] +function*foo() { + function bar() { + function* quux() { + yield(foo); + } + } +} + +//// [YieldExpression19_es6.js] +function foo() { + function bar() { + function quux() { + ; + } + } +} diff --git a/tests/baselines/reference/YieldExpression2_es6.js b/tests/baselines/reference/YieldExpression2_es6.js new file mode 100644 index 00000000000..0207b8afca0 --- /dev/null +++ b/tests/baselines/reference/YieldExpression2_es6.js @@ -0,0 +1,5 @@ +//// [YieldExpression2_es6.ts] +yield foo; + +//// [YieldExpression2_es6.js] +; diff --git a/tests/baselines/reference/YieldExpression3_es6.js b/tests/baselines/reference/YieldExpression3_es6.js new file mode 100644 index 00000000000..cc3716587ea --- /dev/null +++ b/tests/baselines/reference/YieldExpression3_es6.js @@ -0,0 +1,11 @@ +//// [YieldExpression3_es6.ts] +function* foo() { + yield + yield +} + +//// [YieldExpression3_es6.js] +function foo() { + ; + ; +} diff --git a/tests/baselines/reference/YieldExpression4_es6.js b/tests/baselines/reference/YieldExpression4_es6.js new file mode 100644 index 00000000000..84b11a03a2c --- /dev/null +++ b/tests/baselines/reference/YieldExpression4_es6.js @@ -0,0 +1,11 @@ +//// [YieldExpression4_es6.ts] +function* foo() { + yield; + yield; +} + +//// [YieldExpression4_es6.js] +function foo() { + ; + ; +} diff --git a/tests/baselines/reference/YieldExpression5_es6.js b/tests/baselines/reference/YieldExpression5_es6.js new file mode 100644 index 00000000000..5e0e9f811fa --- /dev/null +++ b/tests/baselines/reference/YieldExpression5_es6.js @@ -0,0 +1,9 @@ +//// [YieldExpression5_es6.ts] +function* foo() { + yield* +} + +//// [YieldExpression5_es6.js] +function foo() { + ; +} diff --git a/tests/baselines/reference/YieldExpression6_es6.js b/tests/baselines/reference/YieldExpression6_es6.js new file mode 100644 index 00000000000..5024e9bbd40 --- /dev/null +++ b/tests/baselines/reference/YieldExpression6_es6.js @@ -0,0 +1,9 @@ +//// [YieldExpression6_es6.ts] +function* foo() { + yield*foo +} + +//// [YieldExpression6_es6.js] +function foo() { + ; +} diff --git a/tests/baselines/reference/YieldExpression7_es6.js b/tests/baselines/reference/YieldExpression7_es6.js new file mode 100644 index 00000000000..96ef5af107e --- /dev/null +++ b/tests/baselines/reference/YieldExpression7_es6.js @@ -0,0 +1,9 @@ +//// [YieldExpression7_es6.ts] +function* foo() { + yield foo +} + +//// [YieldExpression7_es6.js] +function foo() { + ; +} diff --git a/tests/baselines/reference/YieldExpression8_es6.js b/tests/baselines/reference/YieldExpression8_es6.js new file mode 100644 index 00000000000..190c2cc3da5 --- /dev/null +++ b/tests/baselines/reference/YieldExpression8_es6.js @@ -0,0 +1,11 @@ +//// [YieldExpression8_es6.ts] +yield(foo); +function* foo() { + yield(foo); +} + +//// [YieldExpression8_es6.js] +yield(foo); +function foo() { + ; +} diff --git a/tests/baselines/reference/YieldExpression9_es6.js b/tests/baselines/reference/YieldExpression9_es6.js new file mode 100644 index 00000000000..978e0d455bd --- /dev/null +++ b/tests/baselines/reference/YieldExpression9_es6.js @@ -0,0 +1,9 @@ +//// [YieldExpression9_es6.ts] +var v = function*() { + yield(foo); +} + +//// [YieldExpression9_es6.js] +var v = function () { + ; +}; diff --git a/tests/baselines/reference/accessibilityModifiers.js b/tests/baselines/reference/accessibilityModifiers.js new file mode 100644 index 00000000000..901b3a29c2e --- /dev/null +++ b/tests/baselines/reference/accessibilityModifiers.js @@ -0,0 +1,171 @@ +//// [accessibilityModifiers.ts] + +// No errors +class C { + private static privateProperty; + private static privateMethod() { } + private static get privateGetter() { return 0; } + private static set privateSetter(a: number) { } + + protected static protectedProperty; + protected static protectedMethod() { } + protected static get protectedGetter() { return 0; } + protected static set protectedSetter(a: number) { } + + public static publicProperty; + public static publicMethod() { } + public static get publicGetter() { return 0; } + public static set publicSetter(a: number) { } +} + +// Errors, accessibility modifiers must precede static +class D { + static private privateProperty; + static private privateMethod() { } + static private get privateGetter() { return 0; } + static private set privateSetter(a: number) { } + + static protected protectedProperty; + static protected protectedMethod() { } + static protected get protectedGetter() { return 0; } + static protected set protectedSetter(a: number) { } + + static public publicProperty; + static public publicMethod() { } + static public get publicGetter() { return 0; } + static public set publicSetter(a: number) { } +} + +// Errors, multiple accessibility modifier +class E { + private public protected property; + public protected method() { } + private protected get getter() { return 0; } + public public set setter(a: number) { } +} + + +//// [accessibilityModifiers.js] +// No errors +var C = (function () { + function C() { + } + C.privateMethod = function () { + }; + Object.defineProperty(C, "privateGetter", { + get: function () { + return 0; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(C, "privateSetter", { + set: function (a) { + }, + enumerable: true, + configurable: true + }); + C.protectedMethod = function () { + }; + Object.defineProperty(C, "protectedGetter", { + get: function () { + return 0; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(C, "protectedSetter", { + set: function (a) { + }, + enumerable: true, + configurable: true + }); + C.publicMethod = function () { + }; + Object.defineProperty(C, "publicGetter", { + get: function () { + return 0; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(C, "publicSetter", { + set: function (a) { + }, + enumerable: true, + configurable: true + }); + return C; +})(); +// Errors, accessibility modifiers must precede static +var D = (function () { + function D() { + } + D.privateMethod = function () { + }; + Object.defineProperty(D, "privateGetter", { + get: function () { + return 0; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(D, "privateSetter", { + set: function (a) { + }, + enumerable: true, + configurable: true + }); + D.protectedMethod = function () { + }; + Object.defineProperty(D, "protectedGetter", { + get: function () { + return 0; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(D, "protectedSetter", { + set: function (a) { + }, + enumerable: true, + configurable: true + }); + D.publicMethod = function () { + }; + Object.defineProperty(D, "publicGetter", { + get: function () { + return 0; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(D, "publicSetter", { + set: function (a) { + }, + enumerable: true, + configurable: true + }); + return D; +})(); +// Errors, multiple accessibility modifier +var E = (function () { + function E() { + } + E.prototype.method = function () { + }; + Object.defineProperty(E.prototype, "getter", { + get: function () { + return 0; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(E.prototype, "setter", { + set: function (a) { + }, + enumerable: true, + configurable: true + }); + return E; +})(); diff --git a/tests/baselines/reference/accessorWithES3.js b/tests/baselines/reference/accessorWithES3.js new file mode 100644 index 00000000000..6eba5238a91 --- /dev/null +++ b/tests/baselines/reference/accessorWithES3.js @@ -0,0 +1,57 @@ +//// [accessorWithES3.ts] + +// error to use accessors in ES3 mode + +class C { + get x() { + return 1; + } +} + +class D { + set x(v) { + } +} + +var x = { + get a() { return 1 } +} + +var y = { + set b(v) { } +} + +//// [accessorWithES3.js] +// error to use accessors in ES3 mode +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "x", { + get: function () { + return 1; + }, + enumerable: true, + configurable: true + }); + return C; +})(); +var D = (function () { + function D() { + } + Object.defineProperty(D.prototype, "x", { + set: function (v) { + }, + enumerable: true, + configurable: true + }); + return D; +})(); +var x = { + get a() { + return 1; + } +}; +var y = { + set b(v) { + } +}; diff --git a/tests/baselines/reference/accessorWithInitializer.js b/tests/baselines/reference/accessorWithInitializer.js new file mode 100644 index 00000000000..26e72fe7d7d --- /dev/null +++ b/tests/baselines/reference/accessorWithInitializer.js @@ -0,0 +1,27 @@ +//// [accessorWithInitializer.ts] + +class C { + set X(v = 0) { } + static set X(v2 = 0) { } +} + +//// [accessorWithInitializer.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "X", { + set: function (v) { + if (v === void 0) { v = 0; } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(C, "X", { + set: function (v2) { + if (v2 === void 0) { v2 = 0; } + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/accessorWithRestParam.js b/tests/baselines/reference/accessorWithRestParam.js new file mode 100644 index 00000000000..9feafe1904d --- /dev/null +++ b/tests/baselines/reference/accessorWithRestParam.js @@ -0,0 +1,33 @@ +//// [accessorWithRestParam.ts] + +class C { + set X(...v) { } + static set X(...v2) { } +} + +//// [accessorWithRestParam.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "X", { + set: function () { + var v = []; + for (var _i = 0; _i < arguments.length; _i++) { + v[_i - 0] = arguments[_i]; + } + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(C, "X", { + set: function () { + var v2 = []; + for (var _i = 0; _i < arguments.length; _i++) { + v2[_i - 0] = arguments[_i]; + } + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/accessorWithoutBody1.js b/tests/baselines/reference/accessorWithoutBody1.js new file mode 100644 index 00000000000..37f0ecbcfee --- /dev/null +++ b/tests/baselines/reference/accessorWithoutBody1.js @@ -0,0 +1,6 @@ +//// [accessorWithoutBody1.ts] +var v = { get foo() } + +//// [accessorWithoutBody1.js] +var v = { get foo() { +} }; diff --git a/tests/baselines/reference/accessorWithoutBody2.js b/tests/baselines/reference/accessorWithoutBody2.js new file mode 100644 index 00000000000..9dc34c1e744 --- /dev/null +++ b/tests/baselines/reference/accessorWithoutBody2.js @@ -0,0 +1,6 @@ +//// [accessorWithoutBody2.ts] +var v = { set foo(a) } + +//// [accessorWithoutBody2.js] +var v = { set foo(a) { +} }; diff --git a/tests/baselines/reference/accessorsAreNotContextuallyTyped.js b/tests/baselines/reference/accessorsAreNotContextuallyTyped.js new file mode 100644 index 00000000000..8c01173a13c --- /dev/null +++ b/tests/baselines/reference/accessorsAreNotContextuallyTyped.js @@ -0,0 +1,33 @@ +//// [accessorsAreNotContextuallyTyped.ts] +// accessors are not contextually typed + +class C { + set x(v: (a: string) => string) { + } + + get x() { + return (x: string) => ""; + } +} + +var c: C; +var r = c.x(''); // string + +//// [accessorsAreNotContextuallyTyped.js] +// accessors are not contextually typed +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "x", { + get: function () { + return function (x) { return ""; }; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + return C; +})(); +var c; +var r = c.x(''); // string diff --git a/tests/baselines/reference/accessorsEmit.js b/tests/baselines/reference/accessorsEmit.js new file mode 100644 index 00000000000..e2c097e263f --- /dev/null +++ b/tests/baselines/reference/accessorsEmit.js @@ -0,0 +1,49 @@ +//// [accessorsEmit.ts] +class Result { } + +class Test { + get Property(): Result { + var x = 1; + return null; + } +} + +class Test2 { + get Property() { + var x = 1; + return null; + } +} + +//// [accessorsEmit.js] +var Result = (function () { + function Result() { + } + return Result; +})(); +var Test = (function () { + function Test() { + } + Object.defineProperty(Test.prototype, "Property", { + get: function () { + var x = 1; + return null; + }, + enumerable: true, + configurable: true + }); + return Test; +})(); +var Test2 = (function () { + function Test2() { + } + Object.defineProperty(Test2.prototype, "Property", { + get: function () { + var x = 1; + return null; + }, + enumerable: true, + configurable: true + }); + return Test2; +})(); diff --git a/tests/baselines/reference/accessorsInAmbientContext.js b/tests/baselines/reference/accessorsInAmbientContext.js new file mode 100644 index 00000000000..e60831ede5b --- /dev/null +++ b/tests/baselines/reference/accessorsInAmbientContext.js @@ -0,0 +1,21 @@ +//// [accessorsInAmbientContext.ts] + +declare module M { + class C { + get X() { return 1; } + set X(v) { } + + static get Y() { return 1; } + static set Y(v) { } + } +} + +declare class C { + get X() { return 1; } + set X(v) { } + + static get Y() { return 1; } + static set Y(v) { } +} + +//// [accessorsInAmbientContext.js] diff --git a/tests/baselines/reference/accessorsNotAllowedInES3.js b/tests/baselines/reference/accessorsNotAllowedInES3.js new file mode 100644 index 00000000000..5cb5a5dc47a --- /dev/null +++ b/tests/baselines/reference/accessorsNotAllowedInES3.js @@ -0,0 +1,24 @@ +//// [accessorsNotAllowedInES3.ts] + +class C { + get x(): number { return 1; } +} +var y = { get foo() { return 3; } }; + + +//// [accessorsNotAllowedInES3.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "x", { + get: function () { + return 1; + }, + enumerable: true, + configurable: true + }); + return C; +})(); +var y = { get foo() { + return 3; +} }; diff --git a/tests/baselines/reference/accessors_spec_section-4.5_error-cases.js b/tests/baselines/reference/accessors_spec_section-4.5_error-cases.js new file mode 100644 index 00000000000..6a3b3773aa6 --- /dev/null +++ b/tests/baselines/reference/accessors_spec_section-4.5_error-cases.js @@ -0,0 +1,59 @@ +//// [accessors_spec_section-4.5_error-cases.ts] +class LanguageSpec_section_4_5_error_cases { + public set AnnotatedSetter_SetterFirst(a: number) { } + public get AnnotatedSetter_SetterFirst() { return ""; } + + public get AnnotatedSetter_SetterLast() { return ""; } + public set AnnotatedSetter_SetterLast(a: number) { } + + public get AnnotatedGetter_GetterFirst(): string { return ""; } + public set AnnotatedGetter_GetterFirst(aStr) { aStr = 0; } + + public set AnnotatedGetter_GetterLast(aStr) { aStr = 0; } + public get AnnotatedGetter_GetterLast(): string { return ""; } +} + +//// [accessors_spec_section-4.5_error-cases.js] +var LanguageSpec_section_4_5_error_cases = (function () { + function LanguageSpec_section_4_5_error_cases() { + } + Object.defineProperty(LanguageSpec_section_4_5_error_cases.prototype, "AnnotatedSetter_SetterFirst", { + get: function () { + return ""; + }, + set: function (a) { + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(LanguageSpec_section_4_5_error_cases.prototype, "AnnotatedSetter_SetterLast", { + get: function () { + return ""; + }, + set: function (a) { + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(LanguageSpec_section_4_5_error_cases.prototype, "AnnotatedGetter_GetterFirst", { + get: function () { + return ""; + }, + set: function (aStr) { + aStr = 0; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(LanguageSpec_section_4_5_error_cases.prototype, "AnnotatedGetter_GetterLast", { + get: function () { + return ""; + }, + set: function (aStr) { + aStr = 0; + }, + enumerable: true, + configurable: true + }); + return LanguageSpec_section_4_5_error_cases; +})(); diff --git a/tests/baselines/reference/accessors_spec_section-4.5_inference.js b/tests/baselines/reference/accessors_spec_section-4.5_inference.js new file mode 100644 index 00000000000..b140e565b29 --- /dev/null +++ b/tests/baselines/reference/accessors_spec_section-4.5_inference.js @@ -0,0 +1,104 @@ +//// [accessors_spec_section-4.5_inference.ts] +class A { } +class B extends A { } + +class LanguageSpec_section_4_5_inference { + + public set InferredGetterFromSetterAnnotation(a: A) { } + public get InferredGetterFromSetterAnnotation() { return new B(); } + + public get InferredGetterFromSetterAnnotation_GetterFirst() { return new B(); } + public set InferredGetterFromSetterAnnotation_GetterFirst(a: A) { } + + + public get InferredFromGetter() { return new B(); } + public set InferredFromGetter(a) { } + + public set InferredFromGetter_SetterFirst(a) { } + public get InferredFromGetter_SetterFirst() { return new B(); } + + public set InferredSetterFromGetterAnnotation(a) { } + public get InferredSetterFromGetterAnnotation() : A { return new B(); } + + public get InferredSetterFromGetterAnnotation_GetterFirst() : A { return new B(); } + public set InferredSetterFromGetterAnnotation_GetterFirst(a) { } +} + +//// [accessors_spec_section-4.5_inference.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var A = (function () { + function A() { + } + return A; +})(); +var B = (function (_super) { + __extends(B, _super); + function B() { + _super.apply(this, arguments); + } + return B; +})(A); +var LanguageSpec_section_4_5_inference = (function () { + function LanguageSpec_section_4_5_inference() { + } + Object.defineProperty(LanguageSpec_section_4_5_inference.prototype, "InferredGetterFromSetterAnnotation", { + get: function () { + return new B(); + }, + set: function (a) { + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(LanguageSpec_section_4_5_inference.prototype, "InferredGetterFromSetterAnnotation_GetterFirst", { + get: function () { + return new B(); + }, + set: function (a) { + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(LanguageSpec_section_4_5_inference.prototype, "InferredFromGetter", { + get: function () { + return new B(); + }, + set: function (a) { + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(LanguageSpec_section_4_5_inference.prototype, "InferredFromGetter_SetterFirst", { + get: function () { + return new B(); + }, + set: function (a) { + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(LanguageSpec_section_4_5_inference.prototype, "InferredSetterFromGetterAnnotation", { + get: function () { + return new B(); + }, + set: function (a) { + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(LanguageSpec_section_4_5_inference.prototype, "InferredSetterFromGetterAnnotation_GetterFirst", { + get: function () { + return new B(); + }, + set: function (a) { + }, + enumerable: true, + configurable: true + }); + return LanguageSpec_section_4_5_inference; +})(); diff --git a/tests/baselines/reference/aliasErrors.js b/tests/baselines/reference/aliasErrors.js new file mode 100644 index 00000000000..e61ca167661 --- /dev/null +++ b/tests/baselines/reference/aliasErrors.js @@ -0,0 +1,68 @@ +//// [aliasErrors.ts] +module foo { + export class Provide { + } + export module bar { export module baz {export class boo {}}} +} + +import provide = foo; +import booz = foo.bar.baz; +import beez = foo.bar; + +import m = no; +import m2 = no.mod; +import n = 5; +import o = "s"; +import q = null; +import r = undefined; + + +var p = new provide.Provide(); + +function use() { + + beez.baz.boo; + var p1: provide.Provide; + var p2: foo.Provide; + var p3:booz.bar; + var p22 = new provide.Provide(); +} + + + +//// [aliasErrors.js] +var foo; +(function (foo) { + var Provide = (function () { + function Provide() { + } + return Provide; + })(); + foo.Provide = Provide; + var bar; + (function (bar) { + var baz; + (function (baz) { + var boo = (function () { + function boo() { + } + return boo; + })(); + baz.boo = boo; + })(baz = bar.baz || (bar.baz = {})); + })(bar = foo.bar || (foo.bar = {})); +})(foo || (foo = {})); +var provide = foo; +var booz = foo.bar.baz; +var beez = foo.bar; +5; +"s"; +null; +var p = new provide.Provide(); +function use() { + beez.baz.boo; + var p1; + var p2; + var p3; + var p22 = new provide.Provide(); +} diff --git a/tests/baselines/reference/ambientDeclarationsExternal.js b/tests/baselines/reference/ambientDeclarationsExternal.js new file mode 100644 index 00000000000..7d8491e0062 --- /dev/null +++ b/tests/baselines/reference/ambientDeclarationsExternal.js @@ -0,0 +1,33 @@ +//// [tests/cases/conformance/ambient/ambientDeclarationsExternal.ts] //// + +//// [decls.ts] + +// Ambient external module with export assignment +declare module 'equ' { + var x; + export = x; +} + +declare module 'equ2' { + var x: number; +} + +// Ambient external import declaration referencing ambient external module using top level module name +//// [consumer.ts] +/// +import imp1 = require('equ'); + + +// Ambient external module members are always exported with or without export keyword when module lacks export assignment +import imp3 = require('equ2'); +var n = imp3.x; +var n: number; + + +//// [decls.js] +// Ambient external import declaration referencing ambient external module using top level module name +//// [consumer.js] +// Ambient external module members are always exported with or without export keyword when module lacks export assignment +var imp3 = require('equ2'); +var n = imp3.x; +var n; diff --git a/tests/baselines/reference/ambientEnum1.js b/tests/baselines/reference/ambientEnum1.js new file mode 100644 index 00000000000..8a477ab99fa --- /dev/null +++ b/tests/baselines/reference/ambientEnum1.js @@ -0,0 +1,11 @@ +//// [ambientEnum1.ts] + declare enum E1 { + y = 4.23 + } + + // Ambient enum with computer member + declare enum E2 { + x = 'foo'.length + } + +//// [ambientEnum1.js] diff --git a/tests/baselines/reference/ambientEnumElementInitializer3.js b/tests/baselines/reference/ambientEnumElementInitializer3.js new file mode 100644 index 00000000000..7a7a077ff8f --- /dev/null +++ b/tests/baselines/reference/ambientEnumElementInitializer3.js @@ -0,0 +1,6 @@ +//// [ambientEnumElementInitializer3.ts] +declare enum E { + e = 3.3 // Decimal +} + +//// [ambientEnumElementInitializer3.js] diff --git a/tests/baselines/reference/ambientErrors.js b/tests/baselines/reference/ambientErrors.js new file mode 100644 index 00000000000..c524a6cfe72 --- /dev/null +++ b/tests/baselines/reference/ambientErrors.js @@ -0,0 +1,63 @@ +//// [ambientErrors.ts] +// Ambient variable with an initializer +declare var x = 4; + +// Ambient functions with invalid overloads +declare function fn(x: number): string; +declare function fn(x: 'foo'): number; + +// Ambient functions with duplicate signatures +declare function fn1(x: number): string; +declare function fn1(x: number): string; + +// Ambient function overloads that differ only by return type +declare function fn2(x: number): string; +declare function fn2(x: number): number; + +// Ambient function with default parameter values +declare function fn3(x = 3); + +// Ambient function with function body +declare function fn4() { }; + +// Ambient enum with non - integer literal constant member +declare enum E1 { + y = 4.23 +} + +// Ambient enum with computer member +declare enum E2 { + x = 'foo'.length +} + +// Ambient module with initializers for values, bodies for functions / classes +declare module M1 { + var x = 3; + function fn() { } + class C { + static x = 3; + y = 4; + constructor() { } + fn() { } + static sfn() { } + } +} + +// Ambient external module not in the global module +module M2 { + declare module 'nope' { } +} + +// Ambient external module with a string literal name that isn't a top level external module name +declare module '../foo' { } + +// Ambient external module with export assignment and other exported members +declare module 'bar' { + var n; + export var q; + export = n; +} + + +//// [ambientErrors.js] +; diff --git a/tests/baselines/reference/ambientErrors1.js b/tests/baselines/reference/ambientErrors1.js new file mode 100644 index 00000000000..8605489d3df --- /dev/null +++ b/tests/baselines/reference/ambientErrors1.js @@ -0,0 +1,4 @@ +//// [ambientErrors1.ts] +declare var x = 4; + +//// [ambientErrors1.js] diff --git a/tests/baselines/reference/ambientGetters.js b/tests/baselines/reference/ambientGetters.js new file mode 100644 index 00000000000..9e267a1dddb --- /dev/null +++ b/tests/baselines/reference/ambientGetters.js @@ -0,0 +1,11 @@ +//// [ambientGetters.ts] + +declare class A { + get length() : number; +} + +declare class B { + get length() { return 0; } +} + +//// [ambientGetters.js] diff --git a/tests/baselines/reference/ambientStatement1.js b/tests/baselines/reference/ambientStatement1.js new file mode 100644 index 00000000000..f986f9717ad --- /dev/null +++ b/tests/baselines/reference/ambientStatement1.js @@ -0,0 +1,8 @@ +//// [ambientStatement1.ts] + declare module M1 { + while(true); + + export var v1 = () => false; + } + +//// [ambientStatement1.js] diff --git a/tests/baselines/reference/ambientWithStatements.js b/tests/baselines/reference/ambientWithStatements.js new file mode 100644 index 00000000000..997916d0bf7 --- /dev/null +++ b/tests/baselines/reference/ambientWithStatements.js @@ -0,0 +1,30 @@ +//// [ambientWithStatements.ts] +declare module M { + break; + continue; + debugger; + do { } while (true); + var x; + for (x in null) { } + if (true) { } else { } + 1; + L: var y; + return; + switch (x) { + case 1: + break; + default: + break; + } + throw "nooo"; + try { + } + catch (e) { + } + finally { + } + with (x) { + } +} + +//// [ambientWithStatements.js] diff --git a/tests/baselines/reference/ambiguousGenericAssertion1.js b/tests/baselines/reference/ambiguousGenericAssertion1.js new file mode 100644 index 00000000000..40bbbee6dd2 --- /dev/null +++ b/tests/baselines/reference/ambiguousGenericAssertion1.js @@ -0,0 +1,15 @@ +//// [ambiguousGenericAssertion1.ts] +function f(x: T): T { return null; } +var r = (x: T) => x; +var r2 = < (x: T) => T>f; // valid +var r3 = <(x: T) => T>f; // ambiguous, appears to the parser as a << operation + + +//// [ambiguousGenericAssertion1.js] +function f(x) { + return null; +} +var r = function (x) { return x; }; +var r2 = f; // valid +var r3 = << T > (x), T; +T > f; // ambiguous, appears to the parser as a << operation diff --git a/tests/baselines/reference/amdModuleName2.js b/tests/baselines/reference/amdModuleName2.js new file mode 100644 index 00000000000..90e50ce1e48 --- /dev/null +++ b/tests/baselines/reference/amdModuleName2.js @@ -0,0 +1,24 @@ +//// [amdModuleName2.ts] +/// +/// +class Foo { + x: number; + constructor() { + this.x = 5; + } +} +export = Foo; + + +//// [amdModuleName2.js] +define("SecondModuleName", ["require", "exports"], function (require, exports) { + /// + /// + var Foo = (function () { + function Foo() { + this.x = 5; + } + return Foo; + })(); + return Foo; +}); diff --git a/tests/baselines/reference/anonymousModules.js b/tests/baselines/reference/anonymousModules.js new file mode 100644 index 00000000000..39b21f6990a --- /dev/null +++ b/tests/baselines/reference/anonymousModules.js @@ -0,0 +1,29 @@ +//// [anonymousModules.ts] +module { + export var foo = 1; + + module { + export var bar = 1; + } + + var bar = 2; + + module { + var x = bar; + } +} + +//// [anonymousModules.js] +module; +{ + exports.foo = 1; + module; + { + exports.bar = 1; + } + var bar = 2; + module; + { + var x = bar; + } +} diff --git a/tests/baselines/reference/anyIdenticalToItself.js b/tests/baselines/reference/anyIdenticalToItself.js new file mode 100644 index 00000000000..dc221b69aa7 --- /dev/null +++ b/tests/baselines/reference/anyIdenticalToItself.js @@ -0,0 +1,32 @@ +//// [anyIdenticalToItself.ts] +function foo(x: any); +function foo(x: any); +function foo(x: any, y: number) { } + +class C { + get X(): any { + var y: any; + return y; + } + set X(v: any) { + } +} + +//// [anyIdenticalToItself.js] +function foo(x, y) { +} +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "X", { + get: function () { + var y; + return y; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/arraySigChecking.js b/tests/baselines/reference/arraySigChecking.js new file mode 100644 index 00000000000..16189305ead --- /dev/null +++ b/tests/baselines/reference/arraySigChecking.js @@ -0,0 +1,46 @@ +//// [arraySigChecking.ts] +declare module M { + interface iBar { t: any; } + interface iFoo extends iBar { + s: any; + } + + class cFoo { + t: any; + } + + var foo: { [index: any]; }; // expect an error here +} + +interface myInt { + voidFn(): void; +} +var myVar: myInt; +var strArray: string[] = [myVar.voidFn()]; + + +var myArray: number[][][]; +myArray = [[1, 2]]; + +function isEmpty(l: { length: number }) { + return l.length === 0; +} + +isEmpty([]); +isEmpty(new Array(3)); +isEmpty(new Array(3)); +isEmpty(['a']); + + +//// [arraySigChecking.js] +var myVar; +var strArray = [myVar.voidFn()]; +var myArray; +myArray = [[1, 2]]; +function isEmpty(l) { + return l.length === 0; +} +isEmpty([]); +isEmpty(new Array(3)); +isEmpty(new Array(3)); +isEmpty(['a']); diff --git a/tests/baselines/reference/arrayTypeOfTypeOf.js b/tests/baselines/reference/arrayTypeOfTypeOf.js new file mode 100644 index 00000000000..f3653346be4 --- /dev/null +++ b/tests/baselines/reference/arrayTypeOfTypeOf.js @@ -0,0 +1,16 @@ +//// [arrayTypeOfTypeOf.ts] +// array type cannot use typeof. + +var x = 1; +var xs: typeof x[]; // Not an error. This is equivalent to Array +var xs2: typeof Array; +var xs3: typeof Array; +var xs4: typeof Array; + +//// [arrayTypeOfTypeOf.js] +// array type cannot use typeof. +var x = 1; +var xs; // Not an error. This is equivalent to Array +var xs2; +var xs3 = ; +var xs4 = ; diff --git a/tests/baselines/reference/arrowFunctionMissingCurlyWithSemicolon.js b/tests/baselines/reference/arrowFunctionMissingCurlyWithSemicolon.js new file mode 100644 index 00000000000..931520294e9 --- /dev/null +++ b/tests/baselines/reference/arrowFunctionMissingCurlyWithSemicolon.js @@ -0,0 +1,11 @@ +//// [arrowFunctionMissingCurlyWithSemicolon.ts] +// Should error at semicolon. +var f = () => ; +var b = 1 * 2 * 3 * 4; +var square = (x: number) => x * x; + +//// [arrowFunctionMissingCurlyWithSemicolon.js] +// Should error at semicolon. +var f = ; +var b = 1 * 2 * 3 * 4; +var square = function (x) { return x * x; }; diff --git a/tests/baselines/reference/arrowFunctionsMissingTokens.js b/tests/baselines/reference/arrowFunctionsMissingTokens.js new file mode 100644 index 00000000000..7bd24f07577 --- /dev/null +++ b/tests/baselines/reference/arrowFunctionsMissingTokens.js @@ -0,0 +1,140 @@ +//// [arrowFunctionsMissingTokens.ts] + +module missingArrowsWithCurly { + var a = () { }; + + var b = (): void { } + + var c = (x) { }; + + var d = (x: number, y: string) { }; + + var e = (x: number, y: string): void { }; +} + +module missingCurliesWithArrow { + module withStatement { + var a = () => var k = 10;}; + + var b = (): void => var k = 10;} + + var c = (x) => var k = 10;}; + + var d = (x: number, y: string) => var k = 10;}; + + var e = (x: number, y: string): void => var k = 10;}; + + var f = () => var k = 10;} + } + + module withoutStatement { + var a = () => }; + + var b = (): void => } + + var c = (x) => }; + + var d = (x: number, y: string) => }; + + var e = (x: number, y: string): void => }; + + var f = () => } + } +} + +module ce_nEst_pas_une_arrow_function { + var a = (); + + var b = (): void; + + var c = (x); + + var d = (x: number, y: string); + + var e = (x: number, y: string): void; +} + +module okay { + var a = () => { }; + + var b = (): void => { } + + var c = (x) => { }; + + var d = (x: number, y: string) => { }; + + var e = (x: number, y: string): void => { }; +} + +//// [arrowFunctionsMissingTokens.js] +var missingArrowsWithCurly; +(function (missingArrowsWithCurly) { + var a = function () { + }; + var b = function () { + }; + var c = function (x) { + }; + var d = function (x, y) { + }; + var e = function (x, y) { + }; +})(missingArrowsWithCurly || (missingArrowsWithCurly = {})); +var missingCurliesWithArrow; +(function (missingCurliesWithArrow) { + var withStatement; + (function (withStatement) { + var a = function () { + var k = 10; + }; + var b = function () { + var k = 10; + }; + var c = function (x) { + var k = 10; + }; + var d = function (x, y) { + var k = 10; + }; + var e = function (x, y) { + var k = 10; + }; + var f = function () { + var k = 10; + }; + })(withStatement || (withStatement = {})); + var withoutStatement; + (function (withoutStatement) { + var a = ; + })(withoutStatement || (withoutStatement = {})); + ; + var b = ; +})(missingCurliesWithArrow || (missingCurliesWithArrow = {})); +var c = ; +; +var d = ; +; +var e = ; +; +var f = ; +var ce_nEst_pas_une_arrow_function; +(function (ce_nEst_pas_une_arrow_function) { + var a = (); + var b = ; + var c = (x); + var d = ; + var e = ; +})(ce_nEst_pas_une_arrow_function || (ce_nEst_pas_une_arrow_function = {})); +var okay; +(function (okay) { + var a = function () { + }; + var b = function () { + }; + var c = function (x) { + }; + var d = function (x, y) { + }; + var e = function (x, y) { + }; +})(okay || (okay = {})); diff --git a/tests/baselines/reference/asiReturn.js b/tests/baselines/reference/asiReturn.js new file mode 100644 index 00000000000..ef2aada682c --- /dev/null +++ b/tests/baselines/reference/asiReturn.js @@ -0,0 +1,7 @@ +//// [asiReturn.ts] +// This should be an error for using a return outside a function, but ASI should work properly +return + +//// [asiReturn.js] +// This should be an error for using a return outside a function, but ASI should work properly +return; diff --git a/tests/baselines/reference/assertInWrapSomeTypeParameter.js b/tests/baselines/reference/assertInWrapSomeTypeParameter.js new file mode 100644 index 00000000000..efb7d31a86a --- /dev/null +++ b/tests/baselines/reference/assertInWrapSomeTypeParameter.js @@ -0,0 +1,16 @@ +//// [assertInWrapSomeTypeParameter.ts] +class C> { + foo>(x: U) { + return null; + } +} + +//// [assertInWrapSomeTypeParameter.js] +var C = (function () { + function C() { + } + C.prototype.foo = function (x) { + return null; + }; + return C; +})(); diff --git a/tests/baselines/reference/assignmentCompatBug3.js b/tests/baselines/reference/assignmentCompatBug3.js new file mode 100644 index 00000000000..6d3deedc5b8 --- /dev/null +++ b/tests/baselines/reference/assignmentCompatBug3.js @@ -0,0 +1,61 @@ +//// [assignmentCompatBug3.ts] +function makePoint(x: number, y: number) { + return { + get x() { return x;}, // shouldn't be "void" + get y() { return y;}, // shouldn't be "void" + //x: "yo", + //y: "boo", + dist: function () { + return Math.sqrt(x*x+y*y); // shouldn't be picking up "x" and "y" from the object lit + } + } +} + +class C { + get x() { + return 0; + } +} + +function foo(test: string) { } + +var x: any; +var y: any; + +foo(x); +foo(x + y); + +//// [assignmentCompatBug3.js] +function makePoint(x, y) { + return { + get x() { + return x; + }, + get y() { + return y; + }, + //x: "yo", + //y: "boo", + dist: function () { + return Math.sqrt(x * x + y * y); // shouldn't be picking up "x" and "y" from the object lit + } + }; +} +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "x", { + get: function () { + return 0; + }, + enumerable: true, + configurable: true + }); + return C; +})(); +function foo(test) { +} +var x; +var y; +foo(x); +foo(x + y); diff --git a/tests/baselines/reference/assignmentLHSIsValue.js b/tests/baselines/reference/assignmentLHSIsValue.js new file mode 100644 index 00000000000..e6975e70146 --- /dev/null +++ b/tests/baselines/reference/assignmentLHSIsValue.js @@ -0,0 +1,164 @@ +//// [assignmentLHSIsValue.ts] +// expected error for all the LHS of assignments +var value; + +// this +class C { + constructor() { this = value; } + foo() { this = value; } + static sfoo() { this = value; } +} + +function foo() { this = value; } + +this = value; + +// identifiers: module, class, enum, function +module M { export var a; } +M = value; + +C = value; + +enum E { } +E = value; + +foo = value; + +// literals +null = value; +true = value; +false = value; +0 = value; +'' = value; +/d+/ = value; + +// object literals +{ a: 0} = value; + +// array literals +['', ''] = value; + +// super +class Derived extends C { + constructor() { super(); super = value; } + + foo() { super = value } + + static sfoo() { super = value; } +} + +// function expression +function bar() { } = value; +() => { } = value; + +// function calls +foo() = value; + +// parentheses, the containted expression is value +(this) = value; +(M) = value; +(C) = value; +(E) = value; +(foo) = value; +(null) = value; +(true) = value; +(0) = value; +('') = value; +(/d+/) = value; +({}) = value; +([]) = value; +(function baz() { }) = value; +(foo()) = value; + +//// [assignmentLHSIsValue.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +// expected error for all the LHS of assignments +var value; +// this +var C = (function () { + function C() { + this = value; + } + C.prototype.foo = function () { + this = value; + }; + C.sfoo = function () { + this = value; + }; + return C; +})(); +function foo() { + this = value; +} +this = value; +// identifiers: module, class, enum, function +var M; +(function (M) { + M.a; +})(M || (M = {})); +M = value; +C = value; +var E; +(function (E) { +})(E || (E = {})); +E = value; +foo = value; +// literals +null = value; +true = value; +false = value; +0 = value; +'' = value; +/d+/ = value; +// object literals +{ + a: 0; +} +value; +// array literals +'' = value[0], '' = value[1]; +// super +var Derived = (function (_super) { + __extends(Derived, _super); + function Derived() { + _super.call(this); + _super.prototype. = value; + } + Derived.prototype.foo = function () { + _super.prototype. = value; + }; + Derived.sfoo = function () { + _super. = value; + }; + return Derived; +})(C); +// function expression +function bar() { +} +value; +(function () { +}); +value; +// function calls +foo() = value; +// parentheses, the containted expression is value +(this) = value; +(M) = value; +(C) = value; +(E) = value; +(foo) = value; +(null) = value; +(true) = value; +(0) = value; +('') = value; +(/d+/) = value; +({}) = value; +([]) = value; +(function baz() { +}) = value; +(foo()) = value; diff --git a/tests/baselines/reference/autoLift2.js b/tests/baselines/reference/autoLift2.js new file mode 100644 index 00000000000..cf840277d70 --- /dev/null +++ b/tests/baselines/reference/autoLift2.js @@ -0,0 +1,52 @@ +//// [autoLift2.ts] +class A + +{ + constructor() { + this.foo: any; + this.bar: any; + } + + + baz() { + + this.foo = "foo"; + + this.bar = "bar"; + + [1, 2].forEach((p) => this.foo); + + [1, 2].forEach((p) => this.bar); + + } + +} + + + +var a = new A(); + +a.baz(); + + + + +//// [autoLift2.js] +var A = (function () { + function A() { + this.foo; + any; + this.bar; + any; + } + A.prototype.baz = function () { + var _this = this; + this.foo = "foo"; + this.bar = "bar"; + [1, 2].forEach(function (p) { return _this.foo; }); + [1, 2].forEach(function (p) { return _this.bar; }); + }; + return A; +})(); +var a = new A(); +a.baz(); diff --git a/tests/baselines/reference/badArrayIndex.js b/tests/baselines/reference/badArrayIndex.js new file mode 100644 index 00000000000..210dd6add8e --- /dev/null +++ b/tests/baselines/reference/badArrayIndex.js @@ -0,0 +1,5 @@ +//// [badArrayIndex.ts] +var results = number[]; + +//// [badArrayIndex.js] +var results = number[]; diff --git a/tests/baselines/reference/badArraySyntax.js b/tests/baselines/reference/badArraySyntax.js new file mode 100644 index 00000000000..f5ca1e0c0ba --- /dev/null +++ b/tests/baselines/reference/badArraySyntax.js @@ -0,0 +1,26 @@ +//// [badArraySyntax.ts] +class Z { + public x = ""; +} + +var a1: Z[] = []; +var a2 = new Z[]; +var a3 = new Z[](); +var a4: Z[] = new Z[]; +var a5: Z[] = new Z[](); +var a6: Z[][] = new Z [ ] [ ]; + + +//// [badArraySyntax.js] +var Z = (function () { + function Z() { + this.x = ""; + } + return Z; +})(); +var a1 = []; +var a2 = new Z[]; +var a3 = new Z[](); +var a4 = new Z[]; +var a5 = new Z[](); +var a6 = new Z[][]; diff --git a/tests/baselines/reference/bases.js b/tests/baselines/reference/bases.js new file mode 100644 index 00000000000..32d65d1a248 --- /dev/null +++ b/tests/baselines/reference/bases.js @@ -0,0 +1,46 @@ +//// [bases.ts] +interface I { + x; +} + +class B { + constructor() { + this.y: any; + } +} + +class C extends B implements I { + constructor() { + this.x: any; + } +} + +new C().x; +new C().y; + + + +//// [bases.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var B = (function () { + function B() { + this.y; + any; + } + return B; +})(); +var C = (function (_super) { + __extends(C, _super); + function C() { + this.x; + any; + } + return C; +})(B); +new C().x; +new C().y; diff --git a/tests/baselines/reference/binaryIntegerLiteralError.js b/tests/baselines/reference/binaryIntegerLiteralError.js new file mode 100644 index 00000000000..215514982c0 --- /dev/null +++ b/tests/baselines/reference/binaryIntegerLiteralError.js @@ -0,0 +1,23 @@ +//// [binaryIntegerLiteralError.ts] +// error +var bin1 = 0B1102110; +var bin1 = 0b11023410; + +var obj1 = { + 0b11010: "hi", + 26: "Hello", + "26": "world", +}; + + +//// [binaryIntegerLiteralError.js] +// error +var bin1 = 6; +2110; +var bin1 = 6; +23410; +var obj1 = { + 26: "hi", + 26: "Hello", + "26": "world" +}; diff --git a/tests/baselines/reference/bitwiseNotOperatorInvalidOperations.js b/tests/baselines/reference/bitwiseNotOperatorInvalidOperations.js new file mode 100644 index 00000000000..1b64091c048 --- /dev/null +++ b/tests/baselines/reference/bitwiseNotOperatorInvalidOperations.js @@ -0,0 +1,24 @@ +//// [bitwiseNotOperatorInvalidOperations.ts] +// Unary operator ~ +var q; + +// operand before ~ +var a = q~; //expect error + +// multiple operands after ~ +var mul = ~[1, 2, "abc"], ""; //expect error + +// miss an operand +var b =~; + +//// [bitwiseNotOperatorInvalidOperations.js] +// Unary operator ~ +var q; +// operand before ~ +var a = q; +~; //expect error +// multiple operands after ~ +var mul = ~[1, 2, "abc"]; +""; //expect error +// miss an operand +var b = ~; diff --git a/tests/baselines/reference/breakNotInIterationOrSwitchStatement1.js b/tests/baselines/reference/breakNotInIterationOrSwitchStatement1.js new file mode 100644 index 00000000000..21ca5d4cce4 --- /dev/null +++ b/tests/baselines/reference/breakNotInIterationOrSwitchStatement1.js @@ -0,0 +1,5 @@ +//// [breakNotInIterationOrSwitchStatement1.ts] +break; + +//// [breakNotInIterationOrSwitchStatement1.js] +break; diff --git a/tests/baselines/reference/breakNotInIterationOrSwitchStatement2.js b/tests/baselines/reference/breakNotInIterationOrSwitchStatement2.js new file mode 100644 index 00000000000..531e5b5e5b6 --- /dev/null +++ b/tests/baselines/reference/breakNotInIterationOrSwitchStatement2.js @@ -0,0 +1,13 @@ +//// [breakNotInIterationOrSwitchStatement2.ts] +while (true) { + function f() { + break; + } +} + +//// [breakNotInIterationOrSwitchStatement2.js] +while (true) { + function f() { + break; + } +} diff --git a/tests/baselines/reference/breakTarget5.js b/tests/baselines/reference/breakTarget5.js new file mode 100644 index 00000000000..197e4e147bd --- /dev/null +++ b/tests/baselines/reference/breakTarget5.js @@ -0,0 +1,18 @@ +//// [breakTarget5.ts] +target: +while (true) { + function f() { + while (true) { + break target; + } + } +} + +//// [breakTarget5.js] +target: while (true) { + function f() { + while (true) { + break target; + } + } +} diff --git a/tests/baselines/reference/breakTarget6.js b/tests/baselines/reference/breakTarget6.js new file mode 100644 index 00000000000..9c5bcc3ded1 --- /dev/null +++ b/tests/baselines/reference/breakTarget6.js @@ -0,0 +1,9 @@ +//// [breakTarget6.ts] +while (true) { + break target; +} + +//// [breakTarget6.js] +while (true) { + break target; +} diff --git a/tests/baselines/reference/callExpressionWithMissingTypeArgument1.js b/tests/baselines/reference/callExpressionWithMissingTypeArgument1.js new file mode 100644 index 00000000000..e073758e428 --- /dev/null +++ b/tests/baselines/reference/callExpressionWithMissingTypeArgument1.js @@ -0,0 +1,5 @@ +//// [callExpressionWithMissingTypeArgument1.ts] +Foo(); + +//// [callExpressionWithMissingTypeArgument1.js] +Foo(); diff --git a/tests/baselines/reference/callSignatureWithOptionalParameterAndInitializer.js b/tests/baselines/reference/callSignatureWithOptionalParameterAndInitializer.js new file mode 100644 index 00000000000..0f8a033067d --- /dev/null +++ b/tests/baselines/reference/callSignatureWithOptionalParameterAndInitializer.js @@ -0,0 +1,112 @@ +//// [callSignatureWithOptionalParameterAndInitializer.ts] +// Optional parameters cannot also have initializer expressions, these are all errors + +function foo(x?: number = 1) { } +var f = function foo(x?: number = 1) { } +var f2 = (x: number, y? = 1) => { } + +foo(1); +foo(); +f(1); +f(); +f2(1); +f2(1, 2); + +class C { + foo(x?: number = 1) { } +} + +var c: C; +c.foo(); +c.foo(1); + +interface I { + (x? = 1); + foo(x: number, y?: number = 1); +} + +var i: I; +i(); +i(1); +i.foo(1); +i.foo(1, 2); + +var a: { + (x?: number = 1); + foo(x? = 1); +} + +a(); +a(1); +a.foo(); +a.foo(1); + +var b = { + foo(x?: number = 1) { }, + a: function foo(x: number, y?: number = '') { }, + b: (x?: any = '') => { } +} + +b.foo(); +b.foo(1); +b.a(1); +b.a(1, 2); +b.b(); +b.b(1); + + +//// [callSignatureWithOptionalParameterAndInitializer.js] +// Optional parameters cannot also have initializer expressions, these are all errors +function foo(x) { + if (x === void 0) { x = 1; } +} +var f = function foo(x) { + if (x === void 0) { x = 1; } +}; +var f2 = function (x, y) { + if (y === void 0) { y = 1; } +}; +foo(1); +foo(); +f(1); +f(); +f2(1); +f2(1, 2); +var C = (function () { + function C() { + } + C.prototype.foo = function (x) { + if (x === void 0) { x = 1; } + }; + return C; +})(); +var c; +c.foo(); +c.foo(1); +var i; +i(); +i(1); +i.foo(1); +i.foo(1, 2); +var a; +a(); +a(1); +a.foo(); +a.foo(1); +var b = { + foo: function (x) { + if (x === void 0) { x = 1; } + }, + a: function foo(x, y) { + if (y === void 0) { y = ''; } + }, + b: function (x) { + if (x === void 0) { x = ''; } + } +}; +b.foo(); +b.foo(1); +b.a(1); +b.a(1, 2); +b.b(); +b.b(1); diff --git a/tests/baselines/reference/callSignaturesWithParameterInitializers2.js b/tests/baselines/reference/callSignaturesWithParameterInitializers2.js new file mode 100644 index 00000000000..0524db42f65 --- /dev/null +++ b/tests/baselines/reference/callSignaturesWithParameterInitializers2.js @@ -0,0 +1,56 @@ +//// [callSignaturesWithParameterInitializers2.ts] +// Optional parameters allow initializers only in implementation signatures +// All the below declarations are errors + +function foo(x = 2); +function foo(x = 1) { } + +foo(1); +foo(); + +class C { + foo(x = 2); + foo(x = 1) { } +} + +var c: C; +c.foo(); +c.foo(1); + +var b = { + foo(x = 1), // error + foo(x = 1) { }, // error +} + +b.foo(); +b.foo(1); + +//// [callSignaturesWithParameterInitializers2.js] +// Optional parameters allow initializers only in implementation signatures +// All the below declarations are errors +function foo(x) { + if (x === void 0) { x = 1; } +} +foo(1); +foo(); +var C = (function () { + function C() { + } + C.prototype.foo = function (x) { + if (x === void 0) { x = 1; } + }; + return C; +})(); +var c; +c.foo(); +c.foo(1); +var b = { + foo: function (x) { + if (x === void 0) { x = 1; } + }, + foo: function (x) { + if (x === void 0) { x = 1; } + } +}; +b.foo(); +b.foo(1); diff --git a/tests/baselines/reference/cannotInvokeNewOnErrorExpression.js b/tests/baselines/reference/cannotInvokeNewOnErrorExpression.js new file mode 100644 index 00000000000..2b05f8d3389 --- /dev/null +++ b/tests/baselines/reference/cannotInvokeNewOnErrorExpression.js @@ -0,0 +1,17 @@ +//// [cannotInvokeNewOnErrorExpression.ts] +module M +{ + class ClassA {} +} +var t = new M.ClassA[]; + +//// [cannotInvokeNewOnErrorExpression.js] +var M; +(function (M) { + var ClassA = (function () { + function ClassA() { + } + return ClassA; + })(); +})(M || (M = {})); +var t = new M.ClassA[]; diff --git a/tests/baselines/reference/catchClauseWithTypeAnnotation.js b/tests/baselines/reference/catchClauseWithTypeAnnotation.js new file mode 100644 index 00000000000..097abe0a9ca --- /dev/null +++ b/tests/baselines/reference/catchClauseWithTypeAnnotation.js @@ -0,0 +1,10 @@ +//// [catchClauseWithTypeAnnotation.ts] +try { +} catch (e: any) { +} + +//// [catchClauseWithTypeAnnotation.js] +try { +} +catch (e) { +} diff --git a/tests/baselines/reference/circularReference.js b/tests/baselines/reference/circularReference.js new file mode 100644 index 00000000000..02eef63db06 --- /dev/null +++ b/tests/baselines/reference/circularReference.js @@ -0,0 +1,66 @@ +//// [tests/cases/conformance/externalModules/circularReference.ts] //// + +//// [foo1.ts] +import foo2 = require('./foo2'); +export module M1 { + export class C1 { + m1: foo2.M1.C1; + x: number; + constructor(){ + this.m1 = new foo2.M1.C1(); + this.m1.y = 10; // OK + this.m1.x = 20; // Error + } + } +} + +//// [foo2.ts] +import foo1 = require('./foo1'); +export module M1 { + export class C1 { + m1: foo1.M1.C1; + y: number + constructor(){ + this.m1 = new foo1.M1.C1(); + this.m1.y = 10; // Error + this.m1.x = 20; // OK + + var tmp = new M1.C1(); + tmp.y = 10; // OK + tmp.x = 20; // Error + } + } +} + + +//// [foo1.js] +var foo2 = require('./foo2'); +var M1; +(function (M1) { + var C1 = (function () { + function C1() { + this.m1 = new foo2.M1.C1(); + this.m1.y = 10; // OK + this.m1.x = 20; // Error + } + return C1; + })(); + M1.C1 = C1; +})(M1 = exports.M1 || (exports.M1 = {})); +//// [foo2.js] +var foo1 = require('./foo1'); +var M1; +(function (M1) { + var C1 = (function () { + function C1() { + this.m1 = new foo1.M1.C1(); + this.m1.y = 10; // Error + this.m1.x = 20; // OK + var tmp = new M1.C1(); + tmp.y = 10; // OK + tmp.x = 20; // Error + } + return C1; + })(); + M1.C1 = C1; +})(M1 = exports.M1 || (exports.M1 = {})); diff --git a/tests/baselines/reference/class2.js b/tests/baselines/reference/class2.js new file mode 100644 index 00000000000..03b60ac8dc5 --- /dev/null +++ b/tests/baselines/reference/class2.js @@ -0,0 +1,10 @@ +//// [class2.ts] +class foo { constructor() { static f = 3; } } + +//// [class2.js] +var foo = (function () { + function foo() { + } + foo.f = 3; + return foo; +})(); diff --git a/tests/baselines/reference/classBodyWithStatements.js b/tests/baselines/reference/classBodyWithStatements.js new file mode 100644 index 00000000000..bae4860f722 --- /dev/null +++ b/tests/baselines/reference/classBodyWithStatements.js @@ -0,0 +1,37 @@ +//// [classBodyWithStatements.ts] +class C { + var x = 1; +} + +class C2 { + function foo() {} +} + +var x = 1; +var y = 2; +class C3 { + x: number = y + 1; // ok, need a var in the statement production +} + +//// [classBodyWithStatements.js] +var C = (function () { + function C() { + } + return C; +})(); +var x = 1; +var C2 = (function () { + function C2() { + } + return C2; +})(); +function foo() { +} +var x = 1; +var y = 2; +var C3 = (function () { + function C3() { + this.x = y + 1; // ok, need a var in the statement production + } + return C3; +})(); diff --git a/tests/baselines/reference/classConstructorAccessibility.js b/tests/baselines/reference/classConstructorAccessibility.js new file mode 100644 index 00000000000..15b12190392 --- /dev/null +++ b/tests/baselines/reference/classConstructorAccessibility.js @@ -0,0 +1,82 @@ +//// [classConstructorAccessibility.ts] +class C { + public constructor(public x: number) { } +} + +class D { + private constructor(public x: number) { } // error +} + +class E { + protected constructor(public x: number) { } // error +} + +var c = new C(1); +var d = new D(1); +var e = new E(1); + +module Generic { + class C { + public constructor(public x: T) { } + } + + class D { + private constructor(public x: T) { } // error + } + + class E { + protected constructor(public x: T) { } // error + } + + var c = new C(1); + var d = new D(1); + var e = new E(1); +} + + +//// [classConstructorAccessibility.js] +var C = (function () { + function C(x) { + this.x = x; + } + return C; +})(); +var D = (function () { + function D(x) { + this.x = x; + } // error + return D; +})(); +var E = (function () { + function E(x) { + this.x = x; + } // error + return E; +})(); +var c = new C(1); +var d = new D(1); +var e = new E(1); +var Generic; +(function (Generic) { + var C = (function () { + function C(x) { + this.x = x; + } + return C; + })(); + var D = (function () { + function D(x) { + this.x = x; + } // error + return D; + })(); + var E = (function () { + function E(x) { + this.x = x; + } // error + return E; + })(); + var c = new C(1); + var d = new D(1); + var e = new E(1); +})(Generic || (Generic = {})); diff --git a/tests/baselines/reference/classExpression.js b/tests/baselines/reference/classExpression.js new file mode 100644 index 00000000000..9d902abbf52 --- /dev/null +++ b/tests/baselines/reference/classExpression.js @@ -0,0 +1,34 @@ +//// [classExpression.ts] +var x = class C { +} + +var y = { + foo: class C2 { + } +} + +module M { + var z = class C4 { + } +} + +//// [classExpression.js] +var x = ; +var C = (function () { + function C() { + } + return C; +})(); +var y = { + foo: , + class: C2 +}, _a = void 0; +var M; +(function (M) { + var z = ; + var C4 = (function () { + function C4() { + } + return C4; + })(); +})(M || (M = {})); diff --git a/tests/baselines/reference/classExtendingPrimitive.js b/tests/baselines/reference/classExtendingPrimitive.js new file mode 100644 index 00000000000..b69bc3403f4 --- /dev/null +++ b/tests/baselines/reference/classExtendingPrimitive.js @@ -0,0 +1,98 @@ +//// [classExtendingPrimitive.ts] +// classes cannot extend primitives + +class C extends number { } +class C2 extends string { } +class C3 extends boolean { } +class C4 extends Void { } +class C4a extends void {} +class C5 extends Null { } +class C5a extends null { } +class C6 extends undefined { } +class C7 extends Undefined { } + +enum E { A } +class C8 extends E { } + +//// [classExtendingPrimitive.js] +// classes cannot extend primitives +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function (_super) { + __extends(C, _super); + function C() { + _super.apply(this, arguments); + } + return C; +})(number); +var C2 = (function (_super) { + __extends(C2, _super); + function C2() { + _super.apply(this, arguments); + } + return C2; +})(string); +var C3 = (function (_super) { + __extends(C3, _super); + function C3() { + _super.apply(this, arguments); + } + return C3; +})(boolean); +var C4 = (function (_super) { + __extends(C4, _super); + function C4() { + _super.apply(this, arguments); + } + return C4; +})(Void); +var C4a = (function () { + function C4a() { + } + return C4a; +})(); +void {}; +var C5 = (function (_super) { + __extends(C5, _super); + function C5() { + _super.apply(this, arguments); + } + return C5; +})(Null); +var C5a = (function () { + function C5a() { + } + return C5a; +})(); +null; +{ +} +var C6 = (function (_super) { + __extends(C6, _super); + function C6() { + _super.apply(this, arguments); + } + return C6; +})(undefined); +var C7 = (function (_super) { + __extends(C7, _super); + function C7() { + _super.apply(this, arguments); + } + return C7; +})(Undefined); +var E; +(function (E) { + E[E["A"] = 0] = "A"; +})(E || (E = {})); +var C8 = (function (_super) { + __extends(C8, _super); + function C8() { + _super.apply(this, arguments); + } + return C8; +})(E); diff --git a/tests/baselines/reference/classExtendingPrimitive2.js b/tests/baselines/reference/classExtendingPrimitive2.js new file mode 100644 index 00000000000..9a507934455 --- /dev/null +++ b/tests/baselines/reference/classExtendingPrimitive2.js @@ -0,0 +1,22 @@ +//// [classExtendingPrimitive2.ts] +// classes cannot extend primitives + +class C4a extends void {} +class C5a extends null { } + +//// [classExtendingPrimitive2.js] +// classes cannot extend primitives +var C4a = (function () { + function C4a() { + } + return C4a; +})(); +void {}; +var C5a = (function () { + function C5a() { + } + return C5a; +})(); +null; +{ +} diff --git a/tests/baselines/reference/classExtendsEveryObjectType.js b/tests/baselines/reference/classExtendsEveryObjectType.js new file mode 100644 index 00000000000..2adb974bb28 --- /dev/null +++ b/tests/baselines/reference/classExtendsEveryObjectType.js @@ -0,0 +1,75 @@ +//// [classExtendsEveryObjectType.ts] +interface I { + foo: string; +} +class C extends I { } // error + +class C2 extends { foo: string; } { } // error +var x: { foo: string; } +class C3 extends x { } // error + +module M { export var x = 1; } +class C4 extends M { } // error + +function foo() { } +class C5 extends foo { } // error + +class C6 extends []{ } // error + +//// [classExtendsEveryObjectType.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function (_super) { + __extends(C, _super); + function C() { + _super.apply(this, arguments); + } + return C; +})(I); // error +var C2 = (function () { + function C2() { + } + return C2; +})(); +{ +} // error +var x; +var C3 = (function (_super) { + __extends(C3, _super); + function C3() { + _super.apply(this, arguments); + } + return C3; +})(x); // error +var M; +(function (M) { + M.x = 1; +})(M || (M = {})); +var C4 = (function (_super) { + __extends(C4, _super); + function C4() { + _super.apply(this, arguments); + } + return C4; +})(M); // error +function foo() { +} +var C5 = (function (_super) { + __extends(C5, _super); + function C5() { + _super.apply(this, arguments); + } + return C5; +})(foo); // error +var C6 = (function () { + function C6() { + } + return C6; +})(); +[]; +{ +} // error diff --git a/tests/baselines/reference/classExtendsEveryObjectType2.js b/tests/baselines/reference/classExtendsEveryObjectType2.js new file mode 100644 index 00000000000..f2bcb02fee4 --- /dev/null +++ b/tests/baselines/reference/classExtendsEveryObjectType2.js @@ -0,0 +1,21 @@ +//// [classExtendsEveryObjectType2.ts] +class C2 extends { foo: string; } { } // error + +class C6 extends []{ } // error + +//// [classExtendsEveryObjectType2.js] +var C2 = (function () { + function C2() { + } + return C2; +})(); +{ +} // error +var C6 = (function () { + function C6() { + } + return C6; +})(); +[]; +{ +} // error diff --git a/tests/baselines/reference/classExtendsMultipleBaseClasses.js b/tests/baselines/reference/classExtendsMultipleBaseClasses.js new file mode 100644 index 00000000000..07d6450f405 --- /dev/null +++ b/tests/baselines/reference/classExtendsMultipleBaseClasses.js @@ -0,0 +1,29 @@ +//// [classExtendsMultipleBaseClasses.ts] +class A { } +class B { } +class C extends A,B { } + +//// [classExtendsMultipleBaseClasses.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var A = (function () { + function A() { + } + return A; +})(); +var B = (function () { + function B() { + } + return B; +})(); +var C = (function (_super) { + __extends(C, _super); + function C() { + _super.apply(this, arguments); + } + return C; +})(A); diff --git a/tests/baselines/reference/classHeritageWithTrailingSeparator.js b/tests/baselines/reference/classHeritageWithTrailingSeparator.js new file mode 100644 index 00000000000..5c6470ffdfd --- /dev/null +++ b/tests/baselines/reference/classHeritageWithTrailingSeparator.js @@ -0,0 +1,24 @@ +//// [classHeritageWithTrailingSeparator.ts] +class C { foo: number } +class D extends C, { +} + +//// [classHeritageWithTrailingSeparator.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function () { + function C() { + } + return C; +})(); +var D = (function (_super) { + __extends(D, _super); + function D() { + _super.apply(this, arguments); + } + return D; +})(C); diff --git a/tests/baselines/reference/classMemberInitializerWithLamdaScoping3.js b/tests/baselines/reference/classMemberInitializerWithLamdaScoping3.js new file mode 100644 index 00000000000..bcf4cd60d7d --- /dev/null +++ b/tests/baselines/reference/classMemberInitializerWithLamdaScoping3.js @@ -0,0 +1,34 @@ +//// [tests/cases/compiler/classMemberInitializerWithLamdaScoping3.ts] //// + +//// [classMemberInitializerWithLamdaScoping3_0.ts] +var field1: string; + +//// [classMemberInitializerWithLamdaScoping3_1.ts] +declare var console: { + log(msg?: any): void; +}; +export class Test1 { + constructor(private field1: string) { + } + messageHandler = () => { + console.log(field1); // But this should be error as the field1 will resolve to var field1 + // but since this code would be generated inside constructor, in generated js + // it would resolve to private field1 and thats not what user intended here. + }; +} + +//// [classMemberInitializerWithLamdaScoping3_0.js] +var field1; +//// [classMemberInitializerWithLamdaScoping3_1.js] +var Test1 = (function () { + function Test1(field1) { + this.field1 = field1; + this.messageHandler = function () { + console.log(field1); // But this should be error as the field1 will resolve to var field1 + // but since this code would be generated inside constructor, in generated js + // it would resolve to private field1 and thats not what user intended here. + }; + } + return Test1; +})(); +exports.Test1 = Test1; diff --git a/tests/baselines/reference/classMemberInitializerWithLamdaScoping4.js b/tests/baselines/reference/classMemberInitializerWithLamdaScoping4.js new file mode 100644 index 00000000000..a8e0718f277 --- /dev/null +++ b/tests/baselines/reference/classMemberInitializerWithLamdaScoping4.js @@ -0,0 +1,30 @@ +//// [tests/cases/compiler/classMemberInitializerWithLamdaScoping4.ts] //// + +//// [classMemberInitializerWithLamdaScoping3_0.ts] +export var field1: string; + +//// [classMemberInitializerWithLamdaScoping3_1.ts] +declare var console: { + log(msg?: any): void; +}; +export class Test1 { + constructor(private field1: string) { + } + messageHandler = () => { + console.log(field1); // Should be error that couldnt find symbol field1 + }; +} + +//// [classMemberInitializerWithLamdaScoping3_0.js] +exports.field1; +//// [classMemberInitializerWithLamdaScoping3_1.js] +var Test1 = (function () { + function Test1(field1) { + this.field1 = field1; + this.messageHandler = function () { + console.log(field1); // Should be error that couldnt find symbol field1 + }; + } + return Test1; +})(); +exports.Test1 = Test1; diff --git a/tests/baselines/reference/classPropertyAsPrivate.js b/tests/baselines/reference/classPropertyAsPrivate.js new file mode 100644 index 00000000000..8b59dcde771 --- /dev/null +++ b/tests/baselines/reference/classPropertyAsPrivate.js @@ -0,0 +1,63 @@ +//// [classPropertyAsPrivate.ts] +class C { + private x: string; + private get y() { return null; } + private set y(x) { } + private foo() { } + + private static a: string; + private static get b() { return null; } + private static set b(x) { } + private static foo() { } +} + +var c: C; +// all errors +c.x; +c.y; +c.y = 1; +c.foo(); + +C.a; +C.b(); +C.b = 1; +C.foo(); + +//// [classPropertyAsPrivate.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "y", { + get: function () { + return null; + }, + set: function (x) { + }, + enumerable: true, + configurable: true + }); + C.prototype.foo = function () { + }; + Object.defineProperty(C, "b", { + get: function () { + return null; + }, + set: function (x) { + }, + enumerable: true, + configurable: true + }); + C.foo = function () { + }; + return C; +})(); +var c; +// all errors +c.x; +c.y; +c.y = 1; +c.foo(); +C.a; +C.b(); +C.b = 1; +C.foo(); diff --git a/tests/baselines/reference/classPropertyAsProtected.js b/tests/baselines/reference/classPropertyAsProtected.js new file mode 100644 index 00000000000..ddb193f072a --- /dev/null +++ b/tests/baselines/reference/classPropertyAsProtected.js @@ -0,0 +1,63 @@ +//// [classPropertyAsProtected.ts] +class C { + protected x: string; + protected get y() { return null; } + protected set y(x) { } + protected foo() { } + + protected static a: string; + protected static get b() { return null; } + protected static set b(x) { } + protected static foo() { } +} + +var c: C; +// all errors +c.x; +c.y; +c.y = 1; +c.foo(); + +C.a; +C.b(); +C.b = 1; +C.foo(); + +//// [classPropertyAsProtected.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "y", { + get: function () { + return null; + }, + set: function (x) { + }, + enumerable: true, + configurable: true + }); + C.prototype.foo = function () { + }; + Object.defineProperty(C, "b", { + get: function () { + return null; + }, + set: function (x) { + }, + enumerable: true, + configurable: true + }); + C.foo = function () { + }; + return C; +})(); +var c; +// all errors +c.x; +c.y; +c.y = 1; +c.foo(); +C.a; +C.b(); +C.b = 1; +C.foo(); diff --git a/tests/baselines/reference/classPropertyIsPublicByDefault.js b/tests/baselines/reference/classPropertyIsPublicByDefault.js new file mode 100644 index 00000000000..db1eca56c11 --- /dev/null +++ b/tests/baselines/reference/classPropertyIsPublicByDefault.js @@ -0,0 +1,61 @@ +//// [classPropertyIsPublicByDefault.ts] +class C { + x: string; + get y() { return null; } + set y(x) { } + foo() { } + + static a: string; + static get b() { return null; } + static set b(x) { } + static foo() { } +} + +var c: C; +c.x; +c.y; +c.y = 1; +c.foo(); + +C.a; +C.b(); +C.b = 1; +C.foo(); + +//// [classPropertyIsPublicByDefault.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "y", { + get: function () { + return null; + }, + set: function (x) { + }, + enumerable: true, + configurable: true + }); + C.prototype.foo = function () { + }; + Object.defineProperty(C, "b", { + get: function () { + return null; + }, + set: function (x) { + }, + enumerable: true, + configurable: true + }); + C.foo = function () { + }; + return C; +})(); +var c; +c.x; +c.y; +c.y = 1; +c.foo(); +C.a; +C.b(); +C.b = 1; +C.foo(); diff --git a/tests/baselines/reference/classUpdateTests.js b/tests/baselines/reference/classUpdateTests.js new file mode 100644 index 00000000000..351ddac52e8 --- /dev/null +++ b/tests/baselines/reference/classUpdateTests.js @@ -0,0 +1,264 @@ +//// [classUpdateTests.ts] +// +// test codegen for instance properties +// +class A { + public p1 = 0; + private p2 = 0; + p3; +} + +class B { + public p1 = 0; + private p2 = 0; + p3; + + constructor() {} +} + +class C { + constructor(public p1=0, private p2=0, p3=0) {} +} + +// +// test requirements for super calls +// +class D { // NO ERROR + +} + +class E extends D { // NO ERROR + public p1 = 0; +} + +class F extends E { + constructor() {} // ERROR - super call required +} + +class G extends D { + public p1 = 0; + constructor() { super(); } // NO ERROR +} + +class H { + constructor() { super(); } // ERROR - no super call allowed +} + +class I extends Object { + constructor() { super(); } // ERROR - no super call allowed +} + +class J extends G { + constructor(public p1:number) { + super(); // NO ERROR + } +} + +class K extends G { + constructor(public p1:number) { // ERROR + var i = 0; + super(); + } +} + +class L extends G { + constructor(private p1:number) { + super(); // NO ERROR + } +} + +class M extends G { + constructor(private p1:number) { // ERROR + var i = 0; + super(); + } +} + +// +// test this reference in field initializers +// +class N { + public p1 = 0; + public p2 = this.p1; + + constructor() { + this.p2 = 0; + } +} + +// +// test error on property declarations within class constructors +// +class O { + constructor() { + public p1 = 0; // ERROR + } +} + +class P { + constructor() { + private p1 = 0; // ERROR + } +} + +class Q { + constructor() { + public this.p1 = 0; // ERROR + } +} + +class R { + constructor() { + private this.p1 = 0; // ERROR + } +} + +//// [classUpdateTests.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +// +// test codegen for instance properties +// +var A = (function () { + function A() { + this.p1 = 0; + this.p2 = 0; + } + return A; +})(); +var B = (function () { + function B() { + this.p1 = 0; + this.p2 = 0; + } + return B; +})(); +var C = (function () { + function C(p1, p2, p3) { + if (p1 === void 0) { p1 = 0; } + if (p2 === void 0) { p2 = 0; } + if (p3 === void 0) { p3 = 0; } + this.p1 = p1; + this.p2 = p2; + } + return C; +})(); +// +// test requirements for super calls +// +var D = (function () { + function D() { + } + return D; +})(); +var E = (function (_super) { + __extends(E, _super); + function E() { + _super.apply(this, arguments); + this.p1 = 0; + } + return E; +})(D); +var F = (function (_super) { + __extends(F, _super); + function F() { + } // ERROR - super call required + return F; +})(E); +var G = (function (_super) { + __extends(G, _super); + function G() { + _super.call(this); + this.p1 = 0; + } // NO ERROR + return G; +})(D); +var H = (function () { + function H() { + _super.call(this); + } // ERROR - no super call allowed + return H; +})(); +var I = (function (_super) { + __extends(I, _super); + function I() { + _super.call(this); + } // ERROR - no super call allowed + return I; +})(Object); +var J = (function (_super) { + __extends(J, _super); + function J(p1) { + _super.call(this); // NO ERROR + this.p1 = p1; + } + return J; +})(G); +var K = (function (_super) { + __extends(K, _super); + function K(p1) { + this.p1 = p1; + var i = 0; + _super.call(this); + } + return K; +})(G); +var L = (function (_super) { + __extends(L, _super); + function L(p1) { + _super.call(this); // NO ERROR + this.p1 = p1; + } + return L; +})(G); +var M = (function (_super) { + __extends(M, _super); + function M(p1) { + this.p1 = p1; + var i = 0; + _super.call(this); + } + return M; +})(G); +// +// test this reference in field initializers +// +var N = (function () { + function N() { + this.p1 = 0; + this.p2 = this.p1; + this.p2 = 0; + } + return N; +})(); +// +// test error on property declarations within class constructors +// +var O = (function () { + function O() { + this.p1 = 0; // ERROR + } + return O; +})(); +var P = (function () { + function P() { + this.p1 = 0; // ERROR + } + return P; +})(); +var Q = (function () { + function Q() { + this.p1 = 0; // ERROR + } + return Q; +})(); +var R = (function () { + function R() { + this.p1 = 0; // ERROR + } + return R; +})(); diff --git a/tests/baselines/reference/classWithOptionalParameter.js b/tests/baselines/reference/classWithOptionalParameter.js new file mode 100644 index 00000000000..082e624916a --- /dev/null +++ b/tests/baselines/reference/classWithOptionalParameter.js @@ -0,0 +1,29 @@ +//// [classWithOptionalParameter.ts] +// classes do not permit optional parameters, these are errors + +class C { + x?: string; + f?() {} +} + +class C2 { + x?: T; + f?(x: T) {} +} + +//// [classWithOptionalParameter.js] +// classes do not permit optional parameters, these are errors +var C = (function () { + function C() { + } + C.prototype.f = function () { + }; + return C; +})(); +var C2 = (function () { + function C2() { + } + C2.prototype.f = function (x) { + }; + return C2; +})(); diff --git a/tests/baselines/reference/classWithPredefinedTypesAsNames2.js b/tests/baselines/reference/classWithPredefinedTypesAsNames2.js new file mode 100644 index 00000000000..a47adcbe32f --- /dev/null +++ b/tests/baselines/reference/classWithPredefinedTypesAsNames2.js @@ -0,0 +1,13 @@ +//// [classWithPredefinedTypesAsNames2.ts] +// classes cannot use predefined types as names + +class void {} + +//// [classWithPredefinedTypesAsNames2.js] +// classes cannot use predefined types as names +var = (function () { + function () { + } + return ; +})(); +void {}; diff --git a/tests/baselines/reference/classWithStaticMembers.js b/tests/baselines/reference/classWithStaticMembers.js new file mode 100644 index 00000000000..2cded4b1f2e --- /dev/null +++ b/tests/baselines/reference/classWithStaticMembers.js @@ -0,0 +1,60 @@ +//// [classWithStaticMembers.ts] +class C { + static fn() { return this; } + static get x() { return 1; } + static set x(v) { } + constructor(public a: number, private b: number) { } + static foo: string; +} + +var r = C.fn(); +var r2 = r.x; +var r3 = r.foo; + +class D extends C { + bar: string; +} + +var r = D.fn(); +var r2 = r.x; +var r3 = r.foo; + +//// [classWithStaticMembers.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function () { + function C(a, b) { + this.a = a; + this.b = b; + } + C.fn = function () { + return this; + }; + Object.defineProperty(C, "x", { + get: function () { + return 1; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + return C; +})(); +var r = C.fn(); +var r2 = r.x; +var r3 = r.foo; +var D = (function (_super) { + __extends(D, _super); + function D() { + _super.apply(this, arguments); + } + return D; +})(C); +var r = D.fn(); +var r2 = r.x; +var r3 = r.foo; diff --git a/tests/baselines/reference/classdecl.js b/tests/baselines/reference/classdecl.js new file mode 100644 index 00000000000..6c6e542e032 --- /dev/null +++ b/tests/baselines/reference/classdecl.js @@ -0,0 +1,206 @@ +//// [classdecl.ts] +class a { + //constructor (); + constructor (n: number); + constructor (s: string); + constructor (ns: any) { + + } + + public pgF() { } + + public pv; + public get d() { + return 30; + } + public set d() { + } + + public static get p2() { + return { x: 30, y: 40 }; + } + + private static d2() { + } + private static get p3() { + return "string"; + } + private pv3; + + private foo(n: number): string; + private foo(s: string): string; + private foo(ns: any) { + return ns.toString(); + } +} + +class b extends a { +} + +module m1 { + export class b { + } + class d { + } + + + export interface ib { + } +} + +module m2 { + + export module m3 { + export class c extends b { + } + export class ib2 implements m1.ib { + } + } +} + +class c extends m1.b { +} + +class ib2 implements m1.ib { +} + +declare class aAmbient { + constructor (n: number); + constructor (s: string); + public pgF(): void; + public pv; + public d : number; + static p2 : { x: number; y: number; }; + static d2(); + static p3; + private pv3; + private foo(s); +} + +class d { + private foo(n: number): string; + private foo(s: string): string; + private foo(ns: any) { + return ns.toString(); + } +} + +class e { + private foo(s: string): string; + private foo(n: number): string; + private foo(ns: any) { + return ns.toString(); + } +} + +//// [classdecl.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var a = (function () { + function a(ns) { + } + a.prototype.pgF = function () { + }; + Object.defineProperty(a.prototype, "d", { + get: function () { + return 30; + }, + set: function () { + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(a, "p2", { + get: function () { + return { x: 30, y: 40 }; + }, + enumerable: true, + configurable: true + }); + a.d2 = function () { + }; + Object.defineProperty(a, "p3", { + get: function () { + return "string"; + }, + enumerable: true, + configurable: true + }); + a.prototype.foo = function (ns) { + return ns.toString(); + }; + return a; +})(); +var b = (function (_super) { + __extends(b, _super); + function b() { + _super.apply(this, arguments); + } + return b; +})(a); +var m1; +(function (m1) { + var b = (function () { + function b() { + } + return b; + })(); + m1.b = b; + var d = (function () { + function d() { + } + return d; + })(); +})(m1 || (m1 = {})); +var m2; +(function (m2) { + var m3; + (function (m3) { + var c = (function (_super) { + __extends(c, _super); + function c() { + _super.apply(this, arguments); + } + return c; + })(b); + m3.c = c; + var ib2 = (function () { + function ib2() { + } + return ib2; + })(); + m3.ib2 = ib2; + })(m3 = m2.m3 || (m2.m3 = {})); +})(m2 || (m2 = {})); +var c = (function (_super) { + __extends(c, _super); + function c() { + _super.apply(this, arguments); + } + return c; +})(m1.b); +var ib2 = (function () { + function ib2() { + } + return ib2; +})(); +var d = (function () { + function d() { + } + d.prototype.foo = function (ns) { + return ns.toString(); + }; + return d; +})(); +var e = (function () { + function e() { + } + e.prototype.foo = function (ns) { + return ns.toString(); + }; + return e; +})(); diff --git a/tests/baselines/reference/cloduleWithDuplicateMember1.js b/tests/baselines/reference/cloduleWithDuplicateMember1.js new file mode 100644 index 00000000000..ed4d69545fc --- /dev/null +++ b/tests/baselines/reference/cloduleWithDuplicateMember1.js @@ -0,0 +1,52 @@ +//// [cloduleWithDuplicateMember1.ts] +class C { + get x() { return 1; } + static get x() { + return ''; + } + static foo() { } +} + +module C { + export var x = 1; +} +module C { + export function foo() { } + export function x() { } +} + +//// [cloduleWithDuplicateMember1.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "x", { + get: function () { + return 1; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(C, "x", { + get: function () { + return ''; + }, + enumerable: true, + configurable: true + }); + C.foo = function () { + }; + return C; +})(); +var C; +(function (C) { + C.x = 1; +})(C || (C = {})); +var C; +(function (C) { + function foo() { + } + C.foo = foo; + function x() { + } + C.x = x; +})(C || (C = {})); diff --git a/tests/baselines/reference/cloduleWithDuplicateMember2.js b/tests/baselines/reference/cloduleWithDuplicateMember2.js new file mode 100644 index 00000000000..461930c02ae --- /dev/null +++ b/tests/baselines/reference/cloduleWithDuplicateMember2.js @@ -0,0 +1,41 @@ +//// [cloduleWithDuplicateMember2.ts] +class C { + set x(y) { } + static set y(z) { } +} + +module C { + export var x = 1; +} +module C { + export function x() { } +} + +//// [cloduleWithDuplicateMember2.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "x", { + set: function (y) { + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(C, "y", { + set: function (z) { + }, + enumerable: true, + configurable: true + }); + return C; +})(); +var C; +(function (C) { + C.x = 1; +})(C || (C = {})); +var C; +(function (C) { + function x() { + } + C.x = x; +})(C || (C = {})); diff --git a/tests/baselines/reference/clodulesDerivedClasses.errors.txt b/tests/baselines/reference/clodulesDerivedClasses.errors.txt index 1753f6051bd..c3866c9e4be 100644 --- a/tests/baselines/reference/clodulesDerivedClasses.errors.txt +++ b/tests/baselines/reference/clodulesDerivedClasses.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/clodulesDerivedClasses.ts(9,7): error TS2417: Class static side 'typeof Path' incorrectly extends base class static side 'typeof Shape'. Types of property 'Utils' are incompatible. - Type 'typeof Utils' is not assignable to type 'typeof Utils'. + Type 'typeof Path.Utils' is not assignable to type 'typeof Shape.Utils'. Property 'convert' is missing in type 'typeof Utils'. @@ -17,7 +17,7 @@ tests/cases/compiler/clodulesDerivedClasses.ts(9,7): error TS2417: Class static ~~~~ !!! error TS2417: Class static side 'typeof Path' incorrectly extends base class static side 'typeof Shape'. !!! error TS2417: Types of property 'Utils' are incompatible. -!!! error TS2417: Type 'typeof Utils' is not assignable to type 'typeof Utils'. +!!! error TS2417: Type 'typeof Path.Utils' is not assignable to type 'typeof Shape.Utils'. !!! error TS2417: Property 'convert' is missing in type 'typeof Utils'. name: string; diff --git a/tests/baselines/reference/collisionCodeGenModuleWithAccessorChildren.js b/tests/baselines/reference/collisionCodeGenModuleWithAccessorChildren.js new file mode 100644 index 00000000000..9db005de9b9 --- /dev/null +++ b/tests/baselines/reference/collisionCodeGenModuleWithAccessorChildren.js @@ -0,0 +1,126 @@ +//// [collisionCodeGenModuleWithAccessorChildren.ts] +module M { + export var x = 3; + class c { + private y; + set Z(M) { + this.y = x; + } + } +} + +module M { + class d { + private y; + set Z(p) { + var M = 10; + this.y = x; + } + } +} + +module M { // Shouldnt be _M + class e { + private y; + set M(p) { + this.y = x; + } + } +} + +module M { + class f { + get Z() { + var M = 10; + return x; + } + } +} + +module M { // Shouldnt be _M + class e { + get M() { + return x; + } + } +} + +//// [collisionCodeGenModuleWithAccessorChildren.js] +var M; +(function (_M) { + _M.x = 3; + var c = (function () { + function c() { + } + Object.defineProperty(c.prototype, "Z", { + set: function (M) { + this.y = _M.x; + }, + enumerable: true, + configurable: true + }); + return c; + })(); +})(M || (M = {})); +var M; +(function (_M) { + var d = (function () { + function d() { + } + Object.defineProperty(d.prototype, "Z", { + set: function (p) { + var M = 10; + this.y = _M.x; + }, + enumerable: true, + configurable: true + }); + return d; + })(); +})(M || (M = {})); +var M; +(function (M) { + var e = (function () { + function e() { + } + Object.defineProperty(e.prototype, "M", { + set: function (p) { + this.y = M.x; + }, + enumerable: true, + configurable: true + }); + return e; + })(); +})(M || (M = {})); +var M; +(function (_M) { + var f = (function () { + function f() { + } + Object.defineProperty(f.prototype, "Z", { + get: function () { + var M = 10; + return _M.x; + }, + enumerable: true, + configurable: true + }); + return f; + })(); +})(M || (M = {})); +var M; +(function (M) { + var e = (function () { + function e() { + } + Object.defineProperty(e.prototype, "M", { + get: function () { + return M.x; + }, + enumerable: true, + configurable: true + }); + return e; + })(); +})(M || (M = {})); diff --git a/tests/baselines/reference/collisionSuperAndLocalFunctionInAccessors.js b/tests/baselines/reference/collisionSuperAndLocalFunctionInAccessors.js new file mode 100644 index 00000000000..92ddebd156c --- /dev/null +++ b/tests/baselines/reference/collisionSuperAndLocalFunctionInAccessors.js @@ -0,0 +1,112 @@ +//// [collisionSuperAndLocalFunctionInAccessors.ts] +function _super() { // No error +} +class Foo { + get prop1(): number { + function _super() { // No error + } + return 10; + } + set prop1(val: number) { + function _super() { // No error + } + } +} +class b extends Foo { + get prop2(): number { + function _super() { // Should be error + } + return 10; + } + set prop2(val: number) { + function _super() { // Should be error + } + } +} +class c extends Foo { + get prop2(): number { + var x = () => { + function _super() { // Should be error + } + } + return 10; + } + set prop2(val: number) { + var x = () => { + function _super() { // Should be error + } + } + } +} + +//// [collisionSuperAndLocalFunctionInAccessors.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +function _super() { +} +var Foo = (function () { + function Foo() { + } + Object.defineProperty(Foo.prototype, "prop1", { + get: function () { + function _super() { + } + return 10; + }, + set: function (val) { + function _super() { + } + }, + enumerable: true, + configurable: true + }); + return Foo; +})(); +var b = (function (_super) { + __extends(b, _super); + function b() { + _super.apply(this, arguments); + } + Object.defineProperty(b.prototype, "prop2", { + get: function () { + function _super() { + } + return 10; + }, + set: function (val) { + function _super() { + } + }, + enumerable: true, + configurable: true + }); + return b; +})(Foo); +var c = (function (_super) { + __extends(c, _super); + function c() { + _super.apply(this, arguments); + } + Object.defineProperty(c.prototype, "prop2", { + get: function () { + var x = function () { + function _super() { + } + }; + return 10; + }, + set: function (val) { + var x = function () { + function _super() { + } + }; + }, + enumerable: true, + configurable: true + }); + return c; +})(Foo); diff --git a/tests/baselines/reference/collisionSuperAndLocalVarInAccessors.js b/tests/baselines/reference/collisionSuperAndLocalVarInAccessors.js new file mode 100644 index 00000000000..5a8e54a6c3d --- /dev/null +++ b/tests/baselines/reference/collisionSuperAndLocalVarInAccessors.js @@ -0,0 +1,98 @@ +//// [collisionSuperAndLocalVarInAccessors.ts] +var _super = 10; // No Error +class Foo { + get prop1(): number { + var _super = 10; // No error + return 10; + } + set prop1(val: number) { + var _super = 10; // No error + } +} +class b extends Foo { + get prop2(): number { + var _super = 10; // Should be error + return 10; + } + set prop2(val: number) { + var _super = 10; // Should be error + } +} +class c extends Foo { + get prop2(): number { + var x = () => { + var _super = 10; // Should be error + } + return 10; + } + set prop2(val: number) { + var x = () => { + var _super = 10; // Should be error + } + } +} + +//// [collisionSuperAndLocalVarInAccessors.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var _super = 10; // No Error +var Foo = (function () { + function Foo() { + } + Object.defineProperty(Foo.prototype, "prop1", { + get: function () { + var _super = 10; // No error + return 10; + }, + set: function (val) { + var _super = 10; // No error + }, + enumerable: true, + configurable: true + }); + return Foo; +})(); +var b = (function (_super) { + __extends(b, _super); + function b() { + _super.apply(this, arguments); + } + Object.defineProperty(b.prototype, "prop2", { + get: function () { + var _super = 10; // Should be error + return 10; + }, + set: function (val) { + var _super = 10; // Should be error + }, + enumerable: true, + configurable: true + }); + return b; +})(Foo); +var c = (function (_super) { + __extends(c, _super); + function c() { + _super.apply(this, arguments); + } + Object.defineProperty(c.prototype, "prop2", { + get: function () { + var x = function () { + var _super = 10; // Should be error + }; + return 10; + }, + set: function (val) { + var x = function () { + var _super = 10; // Should be error + }; + }, + enumerable: true, + configurable: true + }); + return c; +})(Foo); diff --git a/tests/baselines/reference/collisionSuperAndParameter.js b/tests/baselines/reference/collisionSuperAndParameter.js new file mode 100644 index 00000000000..be9e0ce3f68 --- /dev/null +++ b/tests/baselines/reference/collisionSuperAndParameter.js @@ -0,0 +1,136 @@ +//// [collisionSuperAndParameter.ts] +class Foo { + a() { + var lamda = (_super: number) => { // No Error + return x => this; // New scope. So should inject new _this capture + } + } + b(_super: number) { // No Error + var lambda = () => { + return x => this; // New scope. So should inject new _this capture + } + } + set c(_super: number) { // No error + } +} +class Foo2 extends Foo { + x() { + var lamda = (_super: number) => { // Error + return x => this; // New scope. So should inject new _this capture + } + } + y(_super: number) { // Error + var lambda = () => { + return x => this; // New scope. So should inject new _this capture + } + } + set z(_super: number) { // Error + } + public prop3: { + doStuff: (_super: number) => void; // no error - no code gen + } + public prop4 = { + doStuff: (_super: number) => { // should be error + } + } + constructor(_super: number) { // should be error + super(); + } +} +declare class Foo3 extends Foo { + x(); + y(_super: number); // No error - no code gen + constructor(_super: number); // No error - no code gen + public prop2: { + doStuff: (_super: number) => void; // no error - no code gen + }; + public _super: number; // No error +} + +class Foo4 extends Foo { + constructor(_super: number); // no code gen - no error + constructor(_super: string);// no code gen - no error + constructor(_super: any) { // should be error + super(); + } + y(_super: number); // no code gen - no error + y(_super: string); // no code gen - no error + y(_super: any) { // Error + var lambda = () => { + return x => this; // New scope. So should inject new _this capture + } + } +} + +//// [collisionSuperAndParameter.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var Foo = (function () { + function Foo() { + } + Foo.prototype.a = function () { + var _this = this; + var lamda = function (_super) { + return function (x) { return _this; }; // New scope. So should inject new _this capture + }; + }; + Foo.prototype.b = function (_super) { + var _this = this; + var lambda = function () { + return function (x) { return _this; }; // New scope. So should inject new _this capture + }; + }; + Object.defineProperty(Foo.prototype, "c", { + set: function (_super) { + }, + enumerable: true, + configurable: true + }); + return Foo; +})(); +var Foo2 = (function (_super) { + __extends(Foo2, _super); + function Foo2(_super) { + _super.call(this); + this.prop4 = { + doStuff: function (_super) { + } + }; + } + Foo2.prototype.x = function () { + var _this = this; + var lamda = function (_super) { + return function (x) { return _this; }; // New scope. So should inject new _this capture + }; + }; + Foo2.prototype.y = function (_super) { + var _this = this; + var lambda = function () { + return function (x) { return _this; }; // New scope. So should inject new _this capture + }; + }; + Object.defineProperty(Foo2.prototype, "z", { + set: function (_super) { + }, + enumerable: true, + configurable: true + }); + return Foo2; +})(Foo); +var Foo4 = (function (_super) { + __extends(Foo4, _super); + function Foo4(_super) { + _super.call(this); + } + Foo4.prototype.y = function (_super) { + var _this = this; + var lambda = function () { + return function (x) { return _this; }; // New scope. So should inject new _this capture + }; + }; + return Foo4; +})(Foo); diff --git a/tests/baselines/reference/collisionThisExpressionAndLocalVarInAccessors.js b/tests/baselines/reference/collisionThisExpressionAndLocalVarInAccessors.js new file mode 100644 index 00000000000..53df2984544 --- /dev/null +++ b/tests/baselines/reference/collisionThisExpressionAndLocalVarInAccessors.js @@ -0,0 +1,102 @@ +//// [collisionThisExpressionAndLocalVarInAccessors.ts] +class class1 { + get a(): number { + var x2 = { + doStuff: (callback) => () => { + var _this = 2; + return callback(this); + } + } + + return 10; + } + set a(val: number) { + var x2 = { + doStuff: (callback) => () => { + var _this = 2; + return callback(this); + } + } + + } +} + +class class2 { + get a(): number { + var _this = 2; + var x2 = { + doStuff: (callback) => () => { + return callback(this); + } + } + + return 10; + } + set a(val: number) { + var _this = 2; + var x2 = { + doStuff: (callback) => () => { + return callback(this); + } + } + + } +} + +//// [collisionThisExpressionAndLocalVarInAccessors.js] +var class1 = (function () { + function class1() { + } + Object.defineProperty(class1.prototype, "a", { + get: function () { + var _this = this; + var x2 = { + doStuff: function (callback) { return function () { + var _this = 2; + return callback(_this); + }; } + }; + return 10; + }, + set: function (val) { + var _this = this; + var x2 = { + doStuff: function (callback) { return function () { + var _this = 2; + return callback(_this); + }; } + }; + }, + enumerable: true, + configurable: true + }); + return class1; +})(); +var class2 = (function () { + function class2() { + } + Object.defineProperty(class2.prototype, "a", { + get: function () { + var _this = this; + var _this = 2; + var x2 = { + doStuff: function (callback) { return function () { + return callback(_this); + }; } + }; + return 10; + }, + set: function (val) { + var _this = this; + var _this = 2; + var x2 = { + doStuff: function (callback) { return function () { + return callback(_this); + }; } + }; + }, + enumerable: true, + configurable: true + }); + return class2; +})(); diff --git a/tests/baselines/reference/commaOperatorWithoutOperand.js b/tests/baselines/reference/commaOperatorWithoutOperand.js new file mode 100644 index 00000000000..d52b8212344 --- /dev/null +++ b/tests/baselines/reference/commaOperatorWithoutOperand.js @@ -0,0 +1,46 @@ +//// [commaOperatorWithoutOperand.ts] +var ANY: any; +var BOOLEAN: boolean; +var NUMBER: number; +var STRING: string; +var OBJECT: Object; + +// Expect to have compiler errors +// Missing the second operand +(ANY, ); +(BOOLEAN, ); +(NUMBER, ); +(STRING, ); +(OBJECT, ); + +// Missing the first operand +(, ANY); +(, BOOLEAN); +(, NUMBER); +(, STRING); +(, OBJECT); + +// Missing all operands +( , ); + +//// [commaOperatorWithoutOperand.js] +var ANY; +var BOOLEAN; +var NUMBER; +var STRING; +var OBJECT; +// Expect to have compiler errors +// Missing the second operand +(ANY, ); +(BOOLEAN, ); +(NUMBER, ); +(STRING, ); +(OBJECT, ); +// Missing the first operand +(, ANY); +(, BOOLEAN); +(, NUMBER); +(, STRING); +(, OBJECT); +// Missing all operands +(, ); diff --git a/tests/baselines/reference/commentOnClassAccessor1.js b/tests/baselines/reference/commentOnClassAccessor1.js new file mode 100644 index 00000000000..cdd14a829fc --- /dev/null +++ b/tests/baselines/reference/commentOnClassAccessor1.js @@ -0,0 +1,24 @@ +//// [commentOnClassAccessor1.ts] +class C { + /** + * @type {number} + */ + get bar(): number { return 1;} +} + +//// [commentOnClassAccessor1.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "bar", { + /** + * @type {number} + */ + get: function () { + return 1; + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/commentOnClassAccessor2.js b/tests/baselines/reference/commentOnClassAccessor2.js new file mode 100644 index 00000000000..c85d17e6e19 --- /dev/null +++ b/tests/baselines/reference/commentOnClassAccessor2.js @@ -0,0 +1,34 @@ +//// [commentOnClassAccessor2.ts] +class C { + /** + * Getter. + */ + get bar(): number { return 1;} + + /** + * Setter. + */ + set bar(v) { } +} + +//// [commentOnClassAccessor2.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "bar", { + /** + * Getter. + */ + get: function () { + return 1; + }, + /** + * Setter. + */ + set: function (v) { + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/commentsdoNotEmitComments.js b/tests/baselines/reference/commentsdoNotEmitComments.js index fa1cc4c4d12..301ab56e4c0 100644 --- a/tests/baselines/reference/commentsdoNotEmitComments.js +++ b/tests/baselines/reference/commentsdoNotEmitComments.js @@ -86,6 +86,11 @@ module m1 { /// this is x declare var x; + + +/** const enum member value comment (generated by TS) */ +const enum color { red, green, blue } +var shade: color = color.green; //// [commentsdoNotEmitComments.js] @@ -129,6 +134,7 @@ var m1; })(); m1.b = b; })(m1 || (m1 = {})); +var shade = 1; //// [commentsdoNotEmitComments.d.ts] @@ -161,3 +167,9 @@ declare module m1 { } } declare var x: any; +declare const enum color { + red = 0, + green = 1, + blue = 2, +} +declare var shade: color; diff --git a/tests/baselines/reference/commentsdoNotEmitComments.types b/tests/baselines/reference/commentsdoNotEmitComments.types index c42d3d2c17c..bbe3a685ca1 100644 --- a/tests/baselines/reference/commentsdoNotEmitComments.types +++ b/tests/baselines/reference/commentsdoNotEmitComments.types @@ -151,3 +151,18 @@ module m1 { declare var x; >x : any + +/** const enum member value comment (generated by TS) */ +const enum color { red, green, blue } +>color : color +>red : color +>green : color +>blue : color + +var shade: color = color.green; +>shade : color +>color : color +>color.green : color +>color : typeof color +>green : color + diff --git a/tests/baselines/reference/complicatedPrivacy.js b/tests/baselines/reference/complicatedPrivacy.js new file mode 100644 index 00000000000..3d5b321a36f --- /dev/null +++ b/tests/baselines/reference/complicatedPrivacy.js @@ -0,0 +1,204 @@ +//// [complicatedPrivacy.ts] +module m1 { + export module m2 { + + + export function f1(c1: C1) { + } + export function f2(c2: C2) { + } + + export class C2 implements m3.i3 { + public get p1(arg) { + return new C1(); + } + + public set p1(arg1: C1) { + } + + public f55() { + return "Hello world"; + } + } + } + + export function f2(arg1: { x?: C1, y: number }) { + } + + export function f3(): { + (a: number) : C1; + } { + return null; + } + + export function f4(arg1: + { + [number]: C1; // Used to be indexer, now it is a computed property + }) { + } + + + export function f5(arg2: { + new (arg1: C1) : C1 + }) { + } + module m3 { + function f2(f1: C1) { + } + + export interface i3 { + f55(): string; + } + } + + class C1 { + } + + interface i { + x: number; + } + + export class C5 implements i { + public x: number; + } + + export var v2: C1[]; +} + +class C2 { +} + +module m2 { + export module m3 { + + export class c_pr implements mglo5.i5, mglo5.i6 { + f1() { + return "Hello"; + } + } + + module m4 { + class C { + } + module m5 { + + export module m6 { + function f1() { + return new C(); + } + } + } + } + + } +} + +module mglo5 { + export interface i5 { + f1(): string; + } + + interface i6 { + f6(): number; + } +} + + +//// [complicatedPrivacy.js] +var m1; +(function (m1) { + var m2; + (function (m2) { + function f1(c1) { + } + m2.f1 = f1; + function f2(c2) { + } + m2.f2 = f2; + var C2 = (function () { + function C2() { + } + Object.defineProperty(C2.prototype, "p1", { + get: function (arg) { + return new C1(); + }, + set: function (arg1) { + }, + enumerable: true, + configurable: true + }); + C2.prototype.f55 = function () { + return "Hello world"; + }; + return C2; + })(); + m2.C2 = C2; + })(m2 = m1.m2 || (m1.m2 = {})); + function f2(arg1) { + } + m1.f2 = f2; + function f3() { + return null; + } + m1.f3 = f3; + function f4(arg1) { + } + m1.f4 = f4; + function f5(arg2) { + } + m1.f5 = f5; + var m3; + (function (m3) { + function f2(f1) { + } + })(m3 || (m3 = {})); + var C1 = (function () { + function C1() { + } + return C1; + })(); + var C5 = (function () { + function C5() { + } + return C5; + })(); + m1.C5 = C5; + m1.v2; +})(m1 || (m1 = {})); +var C2 = (function () { + function C2() { + } + return C2; +})(); +var m2; +(function (m2) { + var m3; + (function (m3) { + var c_pr = (function () { + function c_pr() { + } + c_pr.prototype.f1 = function () { + return "Hello"; + }; + return c_pr; + })(); + m3.c_pr = c_pr; + var m4; + (function (m4) { + var C = (function () { + function C() { + } + return C; + })(); + var m5; + (function (m5) { + var m6; + (function (m6) { + function f1() { + return new C(); + } + })(m6 = m5.m6 || (m5.m6 = {})); + })(m5 || (m5 = {})); + })(m4 || (m4 = {})); + })(m3 = m2.m3 || (m2.m3 = {})); +})(m2 || (m2 = {})); diff --git a/tests/baselines/reference/compoundAssignmentLHSIsValue.js b/tests/baselines/reference/compoundAssignmentLHSIsValue.js new file mode 100644 index 00000000000..5cefd44e1c5 --- /dev/null +++ b/tests/baselines/reference/compoundAssignmentLHSIsValue.js @@ -0,0 +1,261 @@ +//// [compoundAssignmentLHSIsValue.ts] +// expected error for all the LHS of compound assignments (arithmetic and addition) +var value; + +// this +class C { + constructor() { + this *= value; + this += value; + } + foo() { + this *= value; + this += value; + } + static sfoo() { + this *= value; + this += value; + } +} + +function foo() { + this *= value; + this += value; +} + +this *= value; +this += value; + +// identifiers: module, class, enum, function +module M { export var a; } +M *= value; +M += value; + +C *= value; +C += value; + +enum E { } +E *= value; +E += value; + +foo *= value; +foo += value; + +// literals +null *= value; +null += value; +true *= value; +true += value; +false *= value; +false += value; +0 *= value; +0 += value; +'' *= value; +'' += value; +/d+/ *= value; +/d+/ += value; + +// object literals +{ a: 0} *= value; +{ a: 0} += value; + +// array literals +['', ''] *= value; +['', ''] += value; + +// super +class Derived extends C { + constructor() { + super(); + super *= value; + super += value; + } + + foo() { + super *= value; + super += value; + } + + static sfoo() { + super *= value; + super += value; + } +} + +// function expression +function bar1() { } *= value; +function bar2() { } += value; +() => { } *= value; +() => { } += value; + +// function calls +foo() *= value; +foo() += value; + +// parentheses, the containted expression is value +(this) *= value; +(this) += value; +(M) *= value; +(M) += value; +(C) *= value; +(C) += value; +(E) *= value; +(E) += value; +(foo) *= value; +(foo) += value; +(null) *= value; +(null) += value; +(true) *= value; +(true) += value; +(0) *= value; +(0) += value; +('') *= value; +('') += value; +(/d+/) *= value; +(/d+/) += value; +({}) *= value; +({}) += value; +([]) *= value; +([]) += value; +(function baz1() { }) *= value; +(function baz2() { }) += value; +(foo()) *= value; +(foo()) += value; + +//// [compoundAssignmentLHSIsValue.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +// expected error for all the LHS of compound assignments (arithmetic and addition) +var value; +// this +var C = (function () { + function C() { + this *= value; + this += value; + } + C.prototype.foo = function () { + this *= value; + this += value; + }; + C.sfoo = function () { + this *= value; + this += value; + }; + return C; +})(); +function foo() { + this *= value; + this += value; +} +this *= value; +this += value; +// identifiers: module, class, enum, function +var M; +(function (M) { + M.a; +})(M || (M = {})); +M *= value; +M += value; +C *= value; +C += value; +var E; +(function (E) { +})(E || (E = {})); +E *= value; +E += value; +foo *= value; +foo += value; +// literals +null *= value; +null += value; +true *= value; +true += value; +false *= value; +false += value; +0 *= value; +0 += value; +'' *= value; +'' += value; +/d+/ *= value; +/d+/ += value; +// object literals +{ + a: 0; +} +value; +{ + a: 0; +} +value; +// array literals +['', ''] *= value; +['', ''] += value; +// super +var Derived = (function (_super) { + __extends(Derived, _super); + function Derived() { + _super.call(this); + _super.prototype. *= value; + _super.prototype. += value; + } + Derived.prototype.foo = function () { + _super.prototype. *= value; + _super.prototype. += value; + }; + Derived.sfoo = function () { + _super. *= value; + _super. += value; + }; + return Derived; +})(C); +// function expression +function bar1() { +} +value; +function bar2() { +} +value; +(function () { +}); +value; +(function () { +}); +value; +// function calls +foo() *= value; +foo() += value; +// parentheses, the containted expression is value +(this) *= value; +(this) += value; +(M) *= value; +(M) += value; +(C) *= value; +(C) += value; +(E) *= value; +(E) += value; +(foo) *= value; +(foo) += value; +(null) *= value; +(null) += value; +(true) *= value; +(true) += value; +(0) *= value; +(0) += value; +('') *= value; +('') += value; +(/d+/) *= value; +(/d+/) += value; +({}) *= value; +({}) += value; +([]) *= value; +([]) += value; +(function baz1() { +}) *= value; +(function baz2() { +}) += value; +(foo()) *= value; +(foo()) += value; diff --git a/tests/baselines/reference/computedPropertyNames12.js b/tests/baselines/reference/computedPropertyNames12.js new file mode 100644 index 00000000000..5e5dec0c549 --- /dev/null +++ b/tests/baselines/reference/computedPropertyNames12.js @@ -0,0 +1,31 @@ +//// [computedPropertyNames12.ts] +var s: string; +var n: number; +var a: any; +class C { + [s]: number; + [n] = n; + static [s + s]: string; + [s + n] = 2; + [+s]: typeof s; + static [""]: number; + [0]: number; + [a]: number; + static [true]: number; + [`hello bye`] = 0; + static [`hello ${a} bye`] = 0 +} + +//// [computedPropertyNames12.js] +var s; +var n; +var a; +var C = (function () { + function C() { + this[n] = n; + this[s + n] = 2; + this[`hello bye`] = 0; + } + C[`hello ${a} bye`] = 0; + return C; +})(); diff --git a/tests/baselines/reference/computedPropertyNames29.js b/tests/baselines/reference/computedPropertyNames29.js index dc45746c63c..94e83f34629 100644 --- a/tests/baselines/reference/computedPropertyNames29.js +++ b/tests/baselines/reference/computedPropertyNames29.js @@ -15,10 +15,9 @@ var C = (function () { function C() { } C.prototype.bar = function () { - var _this = this; - (function () { + (() => { var obj = { - [_this.bar()]() { + [this.bar()]() { } // needs capture }; }); diff --git a/tests/baselines/reference/computedPropertyNames3.js b/tests/baselines/reference/computedPropertyNames3.js index fbd76bf48fc..969bbf96d86 100644 --- a/tests/baselines/reference/computedPropertyNames3.js +++ b/tests/baselines/reference/computedPropertyNames3.js @@ -16,7 +16,7 @@ var C = (function () { } C.prototype[0 + 1] = function () { }; - C[function () { + C[() => { }] = function () { }; Object.defineProperty(C.prototype, delete id, { diff --git a/tests/baselines/reference/computedPropertyNames30.js b/tests/baselines/reference/computedPropertyNames30.js index c10ba51316d..608531ffb5b 100644 --- a/tests/baselines/reference/computedPropertyNames30.js +++ b/tests/baselines/reference/computedPropertyNames30.js @@ -31,7 +31,7 @@ var C = (function (_super) { __extends(C, _super); function C() { _super.call(this); - (function () { + (() => { var obj = { // Ideally, we would capture this. But the reference is // illegal, and not capturing this is consistent with diff --git a/tests/baselines/reference/computedPropertyNames31.js b/tests/baselines/reference/computedPropertyNames31.js index bf75ac2be74..9a31b80e346 100644 --- a/tests/baselines/reference/computedPropertyNames31.js +++ b/tests/baselines/reference/computedPropertyNames31.js @@ -37,7 +37,7 @@ var C = (function (_super) { } C.prototype.foo = function () { var _this = this; - (function () { + (() => { var obj = { [_super.prototype.bar.call(_this)]() { } // needs capture diff --git a/tests/baselines/reference/computedPropertyNames35.js b/tests/baselines/reference/computedPropertyNames35.js new file mode 100644 index 00000000000..5a731fd8bda --- /dev/null +++ b/tests/baselines/reference/computedPropertyNames35.js @@ -0,0 +1,11 @@ +//// [computedPropertyNames35.ts] +function foo() { return '' } +interface I { + bar(): string; + [foo()](): void; +} + +//// [computedPropertyNames35.js] +function foo() { + return ''; +} diff --git a/tests/baselines/reference/computedPropertyNames42.js b/tests/baselines/reference/computedPropertyNames42.js new file mode 100644 index 00000000000..c9f24a1c708 --- /dev/null +++ b/tests/baselines/reference/computedPropertyNames42.js @@ -0,0 +1,27 @@ +//// [computedPropertyNames42.ts] +class Foo { x } +class Foo2 { x; y } + +class C { + [s: string]: Foo2; + + // Computed properties + [""]: Foo; +} + +//// [computedPropertyNames42.js] +var Foo = (function () { + function Foo() { + } + return Foo; +})(); +var Foo2 = (function () { + function Foo2() { + } + return Foo2; +})(); +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/computedPropertyNamesContextualType1.js b/tests/baselines/reference/computedPropertyNamesContextualType1.js index d7704c8c377..82429be9c40 100644 --- a/tests/baselines/reference/computedPropertyNamesContextualType1.js +++ b/tests/baselines/reference/computedPropertyNamesContextualType1.js @@ -14,5 +14,5 @@ var o = { ["" + 0](y) { return y.length; }, - ["" + 1]: function (y) { return y.length; } + ["" + 1]: y => { return y.length; } }; diff --git a/tests/baselines/reference/computedPropertyNamesContextualType2.js b/tests/baselines/reference/computedPropertyNamesContextualType2.js index 7b9f98402f5..028e797be18 100644 --- a/tests/baselines/reference/computedPropertyNamesContextualType2.js +++ b/tests/baselines/reference/computedPropertyNamesContextualType2.js @@ -14,5 +14,5 @@ var o = { [+"foo"](y) { return y.length; }, - [+"bar"]: function (y) { return y.length; } + [+"bar"]: y => { return y.length; } }; diff --git a/tests/baselines/reference/computedPropertyNamesContextualType3.js b/tests/baselines/reference/computedPropertyNamesContextualType3.js index f5b2c71bc18..944bb3595d4 100644 --- a/tests/baselines/reference/computedPropertyNamesContextualType3.js +++ b/tests/baselines/reference/computedPropertyNamesContextualType3.js @@ -13,5 +13,5 @@ var o = { [+"foo"](y) { return y.length; }, - [+"bar"]: function (y) { return y.length; } + [+"bar"]: y => { return y.length; } }; diff --git a/tests/baselines/reference/computedPropertyNamesContextualType6.js b/tests/baselines/reference/computedPropertyNamesContextualType6.js index 5d0cc149b2c..a92958871d9 100644 --- a/tests/baselines/reference/computedPropertyNamesContextualType6.js +++ b/tests/baselines/reference/computedPropertyNamesContextualType6.js @@ -16,7 +16,7 @@ foo({ //// [computedPropertyNamesContextualType6.js] foo({ p: "", - 0: function () { + 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, diff --git a/tests/baselines/reference/computedPropertyNamesContextualType7.js b/tests/baselines/reference/computedPropertyNamesContextualType7.js index 74030be6f2a..00103bc76db 100644 --- a/tests/baselines/reference/computedPropertyNamesContextualType7.js +++ b/tests/baselines/reference/computedPropertyNamesContextualType7.js @@ -16,7 +16,7 @@ foo({ //// [computedPropertyNamesContextualType7.js] foo({ p: "", - 0: function () { + 0: () => { }, ["hi" + "bye"]: true, [0 + 1]: 0, diff --git a/tests/baselines/reference/computedPropertyNamesDeclarationEmit3.js b/tests/baselines/reference/computedPropertyNamesDeclarationEmit3.js new file mode 100644 index 00000000000..df351acf6e9 --- /dev/null +++ b/tests/baselines/reference/computedPropertyNamesDeclarationEmit3.js @@ -0,0 +1,6 @@ +//// [computedPropertyNamesDeclarationEmit3.ts] +interface I { + ["" + ""](): void; +} + +//// [computedPropertyNamesDeclarationEmit3.js] diff --git a/tests/baselines/reference/computedPropertyNamesDeclarationEmit4.js b/tests/baselines/reference/computedPropertyNamesDeclarationEmit4.js new file mode 100644 index 00000000000..870f87bb613 --- /dev/null +++ b/tests/baselines/reference/computedPropertyNamesDeclarationEmit4.js @@ -0,0 +1,7 @@ +//// [computedPropertyNamesDeclarationEmit4.ts] +var v: { + ["" + ""](): void; +} + +//// [computedPropertyNamesDeclarationEmit4.js] +var v; diff --git a/tests/baselines/reference/computedPropertyNamesOnOverloads.js b/tests/baselines/reference/computedPropertyNamesOnOverloads.js new file mode 100644 index 00000000000..1db857620e9 --- /dev/null +++ b/tests/baselines/reference/computedPropertyNamesOnOverloads.js @@ -0,0 +1,19 @@ +//// [computedPropertyNamesOnOverloads.ts] +var methodName = "method"; +var accessorName = "accessor"; +class C { + [methodName](v: string); + [methodName](); + [methodName](v?: string) { } +} + +//// [computedPropertyNamesOnOverloads.js] +var methodName = "method"; +var accessorName = "accessor"; +var C = (function () { + function C() { + } + C.prototype[methodName] = function (v) { + }; + return C; +})(); diff --git a/tests/baselines/reference/conflictMarkerTrivia1.js b/tests/baselines/reference/conflictMarkerTrivia1.js new file mode 100644 index 00000000000..68f1b82d38b --- /dev/null +++ b/tests/baselines/reference/conflictMarkerTrivia1.js @@ -0,0 +1,16 @@ +//// [conflictMarkerTrivia1.ts] +class C { +<<<<<<< HEAD + v = 1; +======= + v = 2; +>>>>>>> Branch-a +} + +//// [conflictMarkerTrivia1.js] +var C = (function () { + function C() { + this.v = 1; + } + return C; +})(); diff --git a/tests/baselines/reference/conflictMarkerTrivia2.js b/tests/baselines/reference/conflictMarkerTrivia2.js new file mode 100644 index 00000000000..bbb631de388 --- /dev/null +++ b/tests/baselines/reference/conflictMarkerTrivia2.js @@ -0,0 +1,26 @@ +//// [conflictMarkerTrivia2.ts] +class C { + foo() { +<<<<<<< B + a(); + } +======= + b(); + } +>>>>>>> A + + public bar() { } +} + + +//// [conflictMarkerTrivia2.js] +var C = (function () { + function C() { + } + C.prototype.foo = function () { + a(); + }; + C.prototype.bar = function () { + }; + return C; +})(); diff --git a/tests/baselines/reference/constDeclarationShadowedByVarDeclaration.js b/tests/baselines/reference/constDeclarationShadowedByVarDeclaration.js new file mode 100644 index 00000000000..9fcc9f8f568 --- /dev/null +++ b/tests/baselines/reference/constDeclarationShadowedByVarDeclaration.js @@ -0,0 +1,43 @@ +//// [constDeclarationShadowedByVarDeclaration.ts] + +// Error as declaration of var would cause a write to the const value +var x = 0; +{ + const x = 0; + + var x = 0; +} + + +var y = 0; +{ + const y = 0; + { + var y = 0; + } +} + + +{ + const z = 0; + var z = 0 +} + +//// [constDeclarationShadowedByVarDeclaration.js] +// Error as declaration of var would cause a write to the const value +var x = 0; +{ + const x = 0; + var x = 0; +} +var y = 0; +{ + const y = 0; + { + var y = 0; + } +} +{ + const z = 0; + var z = 0; +} diff --git a/tests/baselines/reference/constDeclarations-access.js b/tests/baselines/reference/constDeclarations-access.js new file mode 100644 index 00000000000..ba913f2d5fc --- /dev/null +++ b/tests/baselines/reference/constDeclarations-access.js @@ -0,0 +1,13 @@ +//// [tests/cases/compiler/constDeclarations-access.ts] //// + +//// [file1.ts] + +const x = 0 + +//// [file2.ts] +x++; + +//// [file1.js] +const x = 0; +//// [file2.js] +x++; diff --git a/tests/baselines/reference/constDeclarations-access2.js b/tests/baselines/reference/constDeclarations-access2.js new file mode 100644 index 00000000000..fd51c932636 --- /dev/null +++ b/tests/baselines/reference/constDeclarations-access2.js @@ -0,0 +1,74 @@ +//// [constDeclarations-access2.ts] + +const x = 0 + +// Errors +x = 1; +x += 2; +x -= 3; +x *= 4; +x /= 5; +x %= 6; +x <<= 7; +x >>= 8; +x >>>= 9; +x &= 10; +x |= 11; +x ^= 12; + +x++; +x--; +++x; +--x; + +++((x)); + +// OK +var a = x + 1; + +function f(v: number) { } +f(x); + +if (x) { } + +x; +(x); + +-x; ++x; + +x.toString(); + + +//// [constDeclarations-access2.js] +const x = 0; +// Errors +x = 1; +x += 2; +x -= 3; +x *= 4; +x /= 5; +x %= 6; +x <<= 7; +x >>= 8; +x >>>= 9; +x &= 10; +x |= 11; +x ^= 12; +x++; +x--; +++x; +--x; +++((x)); +// OK +var a = x + 1; +function f(v) { +} +f(x); +if (x) { +} +x; +(x); +-x; ++x; +x.toString(); diff --git a/tests/baselines/reference/constDeclarations-access3.js b/tests/baselines/reference/constDeclarations-access3.js new file mode 100644 index 00000000000..9ac4880bdd1 --- /dev/null +++ b/tests/baselines/reference/constDeclarations-access3.js @@ -0,0 +1,83 @@ +//// [constDeclarations-access3.ts] + + +module M { + export const x = 0; +} + +// Errors +M.x = 1; +M.x += 2; +M.x -= 3; +M.x *= 4; +M.x /= 5; +M.x %= 6; +M.x <<= 7; +M.x >>= 8; +M.x >>>= 9; +M.x &= 10; +M.x |= 11; +M.x ^= 12; + +M.x++; +M.x--; +++M.x; +--M.x; + +++((M.x)); + +M["x"] = 0; + +// OK +var a = M.x + 1; + +function f(v: number) { } +f(M.x); + +if (M.x) { } + +M.x; +(M.x); + +-M.x; ++M.x; + +M.x.toString(); + + +//// [constDeclarations-access3.js] +var M; +(function (M) { + M.x = 0; +})(M || (M = {})); +// Errors +M.x = 1; +M.x += 2; +M.x -= 3; +M.x *= 4; +M.x /= 5; +M.x %= 6; +M.x <<= 7; +M.x >>= 8; +M.x >>>= 9; +M.x &= 10; +M.x |= 11; +M.x ^= 12; +M.x++; +M.x--; +++M.x; +--M.x; +++((M.x)); +M["x"] = 0; +// OK +var a = M.x + 1; +function f(v) { +} +f(M.x); +if (M.x) { +} +M.x; +(M.x); +-M.x; ++M.x; +M.x.toString(); diff --git a/tests/baselines/reference/constDeclarations-access4.js b/tests/baselines/reference/constDeclarations-access4.js new file mode 100644 index 00000000000..b226e746bba --- /dev/null +++ b/tests/baselines/reference/constDeclarations-access4.js @@ -0,0 +1,79 @@ +//// [constDeclarations-access4.ts] + + +declare module M { + const x: number; +} + +// Errors +M.x = 1; +M.x += 2; +M.x -= 3; +M.x *= 4; +M.x /= 5; +M.x %= 6; +M.x <<= 7; +M.x >>= 8; +M.x >>>= 9; +M.x &= 10; +M.x |= 11; +M.x ^= 12; + +M.x++; +M.x--; +++M.x; +--M.x; + +++((M.x)); + +M["x"] = 0; + +// OK +var a = M.x + 1; + +function f(v: number) { } +f(M.x); + +if (M.x) { } + +M.x; +(M.x); + +-M.x; ++M.x; + +M.x.toString(); + + +//// [constDeclarations-access4.js] +// Errors +M.x = 1; +M.x += 2; +M.x -= 3; +M.x *= 4; +M.x /= 5; +M.x %= 6; +M.x <<= 7; +M.x >>= 8; +M.x >>>= 9; +M.x &= 10; +M.x |= 11; +M.x ^= 12; +M.x++; +M.x--; +++M.x; +--M.x; +++((M.x)); +M["x"] = 0; +// OK +var a = M.x + 1; +function f(v) { +} +f(M.x); +if (M.x) { +} +M.x; +(M.x); +-M.x; ++M.x; +M.x.toString(); diff --git a/tests/baselines/reference/constDeclarations-access5.js b/tests/baselines/reference/constDeclarations-access5.js new file mode 100644 index 00000000000..7acc95ad055 --- /dev/null +++ b/tests/baselines/reference/constDeclarations-access5.js @@ -0,0 +1,89 @@ +//// [tests/cases/compiler/constDeclarations-access5.ts] //// + +//// [constDeclarations_access_1.ts] + + +export const x = 0; + +//// [constDeclarations_access_2.ts] +/// +import m = require('constDeclarations_access_1'); +// Errors +m.x = 1; +m.x += 2; +m.x -= 3; +m.x *= 4; +m.x /= 5; +m.x %= 6; +m.x <<= 7; +m.x >>= 8; +m.x >>>= 9; +m.x &= 10; +m.x |= 11; +m.x ^= 12; +m +m.x++; +m.x--; +++m.x; +--m.x; + +++((m.x)); + +m["x"] = 0; + +// OK +var a = m.x + 1; + +function f(v: number) { } +f(m.x); + +if (m.x) { } + +m.x; +(m.x); + +-m.x; ++m.x; + +m.x.toString(); + + +//// [constDeclarations_access_1.js] +define(["require", "exports"], function (require, exports) { + exports.x = 0; +}); +//// [constDeclarations_access_2.js] +define(["require", "exports", 'constDeclarations_access_1'], function (require, exports, m) { + // Errors + m.x = 1; + m.x += 2; + m.x -= 3; + m.x *= 4; + m.x /= 5; + m.x %= 6; + m.x <<= 7; + m.x >>= 8; + m.x >>>= 9; + m.x &= 10; + m.x |= 11; + m.x ^= 12; + m; + m.x++; + m.x--; + ++m.x; + --m.x; + ++((m.x)); + m["x"] = 0; + // OK + var a = m.x + 1; + function f(v) { + } + f(m.x); + if (m.x) { + } + m.x; + (m.x); + -m.x; + +m.x; + m.x.toString(); +}); diff --git a/tests/baselines/reference/constDeclarations-ambient-errors.js b/tests/baselines/reference/constDeclarations-ambient-errors.js new file mode 100644 index 00000000000..e6e7ac1fb16 --- /dev/null +++ b/tests/baselines/reference/constDeclarations-ambient-errors.js @@ -0,0 +1,13 @@ +//// [constDeclarations-ambient-errors.ts] + +// error: no intialization expected in ambient declarations +declare const c1: boolean = true; +declare const c2: number = 0; +declare const c3 = null, c4 :string = "", c5: any = 0; + +declare module M { + const c6 = 0; + const c7: number = 7; +} + +//// [constDeclarations-ambient-errors.js] diff --git a/tests/baselines/reference/constDeclarations-errors.js b/tests/baselines/reference/constDeclarations-errors.js new file mode 100644 index 00000000000..0af646010f0 --- /dev/null +++ b/tests/baselines/reference/constDeclarations-errors.js @@ -0,0 +1,36 @@ +//// [constDeclarations-errors.ts] + +// error, missing intialicer +const c1; +const c2: number; +const c3, c4, c5 :string, c6; // error, missing initialicer + +// error, can not be unintalized +for(const c in {}) { } + +// error, assigning to a const +for(const c8 = 0; c8 < 1; c8++) { } + +// error, can not be unintalized +for(const c9; c9 < 1;) { } + +// error, can not be unintalized +for(const c10 = 0, c11; c10 < 1;) { } + +//// [constDeclarations-errors.js] +// error, missing intialicer +const c1; +const c2; +const c3, c4, c5, c6; // error, missing initialicer +// error, can not be unintalized +for (var c in {}) { +} +// error, assigning to a const +for (const c8 = 0; c8 < 1; c8++) { +} +// error, can not be unintalized +for (const c9; c9 < 1;) { +} +// error, can not be unintalized +for (const c10 = 0, c11; c10 < 1;) { +} diff --git a/tests/baselines/reference/constDeclarations-es5.js b/tests/baselines/reference/constDeclarations-es5.js new file mode 100644 index 00000000000..20deb9dca37 --- /dev/null +++ b/tests/baselines/reference/constDeclarations-es5.js @@ -0,0 +1,11 @@ +//// [constDeclarations-es5.ts] + +const z7 = false; +const z8: number = 23; +const z9 = 0, z10 :string = "", z11 = null; + + +//// [constDeclarations-es5.js] +const z7 = false; +const z8 = 23; +const z9 = 0, z10 = "", z11 = null; diff --git a/tests/baselines/reference/constDeclarations-invalidContexts.js b/tests/baselines/reference/constDeclarations-invalidContexts.js new file mode 100644 index 00000000000..a9dc1b47145 --- /dev/null +++ b/tests/baselines/reference/constDeclarations-invalidContexts.js @@ -0,0 +1,57 @@ +//// [constDeclarations-invalidContexts.ts] + +// Errors, const must be defined inside a block +if (true) + const c1 = 0; +else + const c2 = 0; + +while (true) + const c3 = 0; + +do + const c4 = 0; +while (true); + +var obj; +with (obj) + const c5 = 0; // No Error will be reported here since we turn off all type checking + +for (var i = 0; i < 10; i++) + const c6 = 0; + +for (var i2 in {}) + const c7 = 0; + +if (true) + label: const c8 = 0; + +while (false) + label2: label3: label4: const c9 = 0; + + + + + +//// [constDeclarations-invalidContexts.js] +// Errors, const must be defined inside a block +if (true) + const c1 = 0; +else + const c2 = 0; +while (true) + const c3 = 0; +do + const c4 = 0; +while (true); +var obj; +with (obj) + const c5 = 0; // No Error will be reported here since we turn off all type checking +for (var i = 0; i < 10; i++) + const c6 = 0; +for (var i2 in {}) + const c7 = 0; +if (true) + label: const c8 = 0; +while (false) + label2: label3: label4: const c9 = 0; diff --git a/tests/baselines/reference/constDeclarations-scopes.js b/tests/baselines/reference/constDeclarations-scopes.js index b1be921849c..f8fbc47312b 100644 --- a/tests/baselines/reference/constDeclarations-scopes.js +++ b/tests/baselines/reference/constDeclarations-scopes.js @@ -223,7 +223,7 @@ function F() { const c = 0; n = c; } -var F2 = function () { +var F2 = () => { const c = 0; n = c; }; @@ -272,7 +272,7 @@ var o = { const c = 0; n = c; }, - f2: function () { + f2: () => { const c = 0; n = c; } diff --git a/tests/baselines/reference/constDeclarations-useBeforeDefinition.js b/tests/baselines/reference/constDeclarations-useBeforeDefinition.js new file mode 100644 index 00000000000..4fe0e64f275 --- /dev/null +++ b/tests/baselines/reference/constDeclarations-useBeforeDefinition.js @@ -0,0 +1,24 @@ +//// [constDeclarations-useBeforeDefinition.ts] + +{ + c1; + const c1 = 0; +} + +var v1; +{ + v1; + const v1 = 0; +} + + +//// [constDeclarations-useBeforeDefinition.js] +{ + c1; + const c1 = 0; +} +var v1; +{ + v1; + const v1 = 0; +} diff --git a/tests/baselines/reference/constDeclarations-useBeforeDefinition2.js b/tests/baselines/reference/constDeclarations-useBeforeDefinition2.js new file mode 100644 index 00000000000..7d1f4cf5725 --- /dev/null +++ b/tests/baselines/reference/constDeclarations-useBeforeDefinition2.js @@ -0,0 +1,12 @@ +//// [tests/cases/compiler/constDeclarations-useBeforeDefinition2.ts] //// + +//// [file1.ts] + +c; + +//// [file2.ts] +const c = 0; + +//// [out.js] +c; +const c = 0; diff --git a/tests/baselines/reference/constDeclarations-validContexts.js b/tests/baselines/reference/constDeclarations-validContexts.js index 8238f69ca15..5a54e915713 100644 --- a/tests/baselines/reference/constDeclarations-validContexts.js +++ b/tests/baselines/reference/constDeclarations-validContexts.js @@ -186,7 +186,7 @@ const c18 = 0; function F() { const c19 = 0; } -var F2 = function () { +var F2 = () => { const c20 = 0; }; var F3 = function () { @@ -226,7 +226,7 @@ var o = { f() { const c28 = 0; }, - f2: function () { + f2: () => { const c29 = 0; } }; diff --git a/tests/baselines/reference/constEnumBadPropertyNames.js b/tests/baselines/reference/constEnumBadPropertyNames.js new file mode 100644 index 00000000000..b73eed780e5 --- /dev/null +++ b/tests/baselines/reference/constEnumBadPropertyNames.js @@ -0,0 +1,6 @@ +//// [constEnumBadPropertyNames.ts] +const enum E { A } +var x = E["B"] + +//// [constEnumBadPropertyNames.js] +var x = E["B"]; diff --git a/tests/baselines/reference/constEnumErrors.js b/tests/baselines/reference/constEnumErrors.js new file mode 100644 index 00000000000..4afd98982f0 --- /dev/null +++ b/tests/baselines/reference/constEnumErrors.js @@ -0,0 +1,58 @@ +//// [constEnumErrors.ts] +const enum E { + A +} + +module E { + var x = 1; +} + +const enum E1 { + // illegal case + // forward reference to the element of the same enum + X = Y, + // forward reference to the element of the same enum + Y = E1.Z, + Y1 = E1["Z"] +} + +const enum E2 { + A +} + +var y0 = E2[1] +var name = "A"; +var y1 = E2[name]; + +var x = E2; +var y = [E2]; + +function foo(t: any): void { +} + +foo(E2); + +const enum NaNOrInfinity { + A = 9007199254740992, + B = A * A, + C = B * B, + D = C * C, + E = D * D, + F = E * E, // overflow + G = 1 / 0, // overflow + H = 0 / 0 // NaN +} + +//// [constEnumErrors.js] +var E; +(function (E) { + var x = 1; +})(E || (E = {})); +var y0 = E2[1]; +var name = "A"; +var y1 = E2[name]; +var x = E2; +var y = [E2]; +function foo(t) { +} +foo(E2); diff --git a/tests/baselines/reference/constructorArgsErrors1.js b/tests/baselines/reference/constructorArgsErrors1.js new file mode 100644 index 00000000000..25701901e13 --- /dev/null +++ b/tests/baselines/reference/constructorArgsErrors1.js @@ -0,0 +1,12 @@ +//// [constructorArgsErrors1.ts] +class foo { + constructor (static a: number) { + } +} + +//// [constructorArgsErrors1.js] +var foo = (function () { + function foo(a) { + } + return foo; +})(); diff --git a/tests/baselines/reference/constructorArgsErrors2.js b/tests/baselines/reference/constructorArgsErrors2.js new file mode 100644 index 00000000000..a0cab9f39f8 --- /dev/null +++ b/tests/baselines/reference/constructorArgsErrors2.js @@ -0,0 +1,14 @@ +//// [constructorArgsErrors2.ts] +class foo { + constructor (public static a: number) { + } +} + + +//// [constructorArgsErrors2.js] +var foo = (function () { + function foo(a) { + this.a = a; + } + return foo; +})(); diff --git a/tests/baselines/reference/constructorArgsErrors3.js b/tests/baselines/reference/constructorArgsErrors3.js new file mode 100644 index 00000000000..3f9b09254a1 --- /dev/null +++ b/tests/baselines/reference/constructorArgsErrors3.js @@ -0,0 +1,14 @@ +//// [constructorArgsErrors3.ts] +class foo { + constructor (public public a: number) { + } +} + + +//// [constructorArgsErrors3.js] +var foo = (function () { + function foo(a) { + this.a = a; + } + return foo; +})(); diff --git a/tests/baselines/reference/constructorArgsErrors4.js b/tests/baselines/reference/constructorArgsErrors4.js new file mode 100644 index 00000000000..c0646a54148 --- /dev/null +++ b/tests/baselines/reference/constructorArgsErrors4.js @@ -0,0 +1,14 @@ +//// [constructorArgsErrors4.ts] +class foo { + constructor (private public a: number) { + } +} + + +//// [constructorArgsErrors4.js] +var foo = (function () { + function foo(a) { + this.a = a; + } + return foo; +})(); diff --git a/tests/baselines/reference/constructorArgsErrors5.js b/tests/baselines/reference/constructorArgsErrors5.js new file mode 100644 index 00000000000..3455490aa6f --- /dev/null +++ b/tests/baselines/reference/constructorArgsErrors5.js @@ -0,0 +1,13 @@ +//// [constructorArgsErrors5.ts] +class foo { + constructor (export a: number) { + } +} + + +//// [constructorArgsErrors5.js] +var foo = (function () { + function foo(a) { + } + return foo; +})(); diff --git a/tests/baselines/reference/constructorOverloads6.js b/tests/baselines/reference/constructorOverloads6.js new file mode 100644 index 00000000000..1996449165c --- /dev/null +++ b/tests/baselines/reference/constructorOverloads6.js @@ -0,0 +1,32 @@ +//// [constructorOverloads6.ts] +declare class FooBase { + constructor(s: string); + constructor(n: number); + constructor(x: any) { + + } + bar1():void; +} + + declare class Foo extends FooBase { + constructor(s: string); + constructor(n: number); + constructor(x: any, y?:any); + + bar1():void; +} + +var f1 = new Foo("hey"); +var f2 = new Foo(0); +var f3 = new Foo(f1); +var f4 = new Foo([f1,f2,f3]); + +f1.bar1(); + + +//// [constructorOverloads6.js] +var f1 = new Foo("hey"); +var f2 = new Foo(0); +var f3 = new Foo(f1); +var f4 = new Foo([f1, f2, f3]); +f1.bar1(); diff --git a/tests/baselines/reference/constructorStaticParamNameErrors.js b/tests/baselines/reference/constructorStaticParamNameErrors.js new file mode 100644 index 00000000000..0bb8985545c --- /dev/null +++ b/tests/baselines/reference/constructorStaticParamNameErrors.js @@ -0,0 +1,15 @@ +//// [constructorStaticParamNameErrors.ts] +'use strict' +// static as constructor parameter name should give error if 'use strict' +class test { + constructor (static) { } +} + +//// [constructorStaticParamNameErrors.js] +'use strict'; +// static as constructor parameter name should give error if 'use strict' +var test = (function () { + function test() { + } + return test; +})(); diff --git a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.js b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.js new file mode 100644 index 00000000000..5a9a03f293c --- /dev/null +++ b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.js @@ -0,0 +1,569 @@ +//// [constructorWithIncompleteTypeAnnotation.ts] +declare module "fs" { + export class File { + constructor(filename: string); + public ReadAllText(): string; + } + export interface IFile { + [index: number]: string; + } +} + +import fs = module("fs"); + + +module TypeScriptAllInOne { + export class Program { + static Main(...args: string[]) { + try { + var bfs = new BasicFeatures(); + var retValue: number = 0; + + retValue = bfs.VARIABLES(); + if (retValue != 0 ^= { + + return 1; + } + + case = bfs.STATEMENTS(4); + if (retValue != 0) { + + return 1; + ^ + + + retValue = bfs.TYPES(); + if (retValue != 0) { + + return 1 && + } + + retValue = bfs.OPERATOR ' ); + if (retValue != 0) { + + return 1; + } + } + catch (e) { + console.log(e); + } + finally { + + } + + console.log('Done'); + + return 0; + + } + } + + class BasicFeatures { + /// + /// Test various of variables. Including nullable,key world as variable,special format + /// + /// + public VARIABLES(): number { + var local = Number.MAX_VALUE; + var min = Number.MIN_VALUE; + var inf = Number.NEGATIVE_INFINITY - + var nan = Number.NaN; + var undef = undefined; + + var _\uD4A5\u7204\uC316\uE59F = local; + var мир = local; + + var local5 = null; + var local6 = local5 instanceof fs.File; + + var hex = 0xBADC0DE, Hex = 0XDEADBEEF; + var float = 6.02e23, float2 = 6.02E-23 + var char = 'c', \u0066 = '\u0066', hexchar = '\x42' != + var quoted = '"', quoted2 = "'"; + var reg = /\w*/; + var objLit = { "var": number = 42, equals: function (x) { return x["var"] === 42; }, instanceof : () => 'objLit{42}' }; + var weekday = Weekdays.Monday; + + var con = char + f + hexchar + float.toString() + float2.toString() + reg.toString() + objLit + weekday; + + // + var any = 0 ^= + var bool = 0; + var declare = 0; + var constructor = 0; + var get = 0; + var implements = 0; + var interface = 0; + var let = 0; + var module = 0; + var number = 0; + var package = 0; + var private = 0; + var protected = 0; + var public = 0; + var set = 0; + var static = 0; + var string = 0 /> + var yield = 0; + + var sum3 = any + bool + declare + constructor + get + implements + interface + let + module + number + package + private + protected + public + set + static + string + yield; + + return 0; + } + + /// + /// Test different statements. Including if-else,swith,foreach,(un)checked,lock,using,try-catch-finally + /// + /// + /// + STATEMENTS(i: number): number { + var retVal = 0; + if (i == 1) + retVal = 1; + else + retVal = 0; + switch (i) { + case 2: + retVal = 1; + break; + case 3: + retVal = 1; + break; + default: + break; + } + + for (var x in { x: 0, y: 1 }) { + ! + + try { + throw null; + } + catch (Exception) ? + } + finally { + try { } + catch (Exception) { } + } + + return retVal; + } + + /// + /// Test types in ts language. Including class,struct,interface,delegate,anonymous type + /// + /// + public TYPES(): number { + var retVal = 0; + var c = new CLASS(); + var xx: IF = c; + retVal += catch .Property; + retVal += c.Member(); + retVal += xx.Foo() ? 0 : 1; + + //anonymous type + var anony = { a: new CLASS() }; + + retVal += anony.a.d(); + + return retVal; + } + + + ///// + ///// Test different operators + ///// + ///// + public OPERATOR(): number { + var a: number[] = [1, 2, 3, 4, 5, ];/*[] bug*/ // YES [] + var i = a[1];/*[]*/ + i = i + i - i * i / i % i & i | i ^ i;/*+ - * / % & | ^*/ + var b = true && false || true ^ false;/*& | ^*/ + b = !b;/*!*/ + i = ~i;/*~i*/ + b = i < (i - 1) && (i + 1) > i;/*< && >*/ + var f = true ? 1 : 0;/*? :*/ // YES : + i++;/*++*/ + i--;/*--*/ + b = true && false || true;/*&& ||*/ + i = i << 5;/*<<*/ + i = i >> 5;/*>>*/ + var j = i; + b = i == j && i != j && i <= j && i >= j;/*= == && != <= >=*/ + i += 5.0;/*+=*/ + i -= i;/*-=*/ + i *= i;/**=*/ + if (i == 0) + i++; + i /= i;/*/=*/ + i %= i;/*%=*/ + i &= i;/*&=*/ + i |= i;/*|=*/ + i ^= i;/*^=*/ + i <<= i;/*<<=*/ + i >>= i;/*>>=*/ + + if (i == 0 && != b && f == 1) + return 0; + else return 1; + } + + } + + interface IF { + Foo(): bool; + } + + class CLASS implements IF { + + case d = () => { yield 0; }; + public get Property() { return 0; } + public Member() { + return 0; + } + public Foo(): bool { + var myEvent = () => { return 1; }; + if (myEvent() == 1) + return true ? + else + return false; + } + } + + + // todo: use these + class A . + public method1(val:number) { + return val; + } + public method2() { + return 2 * this.method1(2); + } + } + + class B extends A { + + public method2() { + return this.method1(2); + } + } + + class Overloading { + + private otherValue = 42; + + constructor(private value: number, public name: string) : } + + public Overloads(value: string); + public Overloads( while : string, ...rest: string[]) { & + + public DefaultValue(value?: string = "Hello") { } + } +} + +enum Weekdays { + Monday, + Tuesday, + Weekend, +} + +enum Fruit { + Apple, + Pear +} + +interface IDisposable { + Dispose(): void; +} + +TypeScriptAllInOne.Program.Main(); + + +//// [constructorWithIncompleteTypeAnnotation.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var fs = module; +("fs"); +var TypeScriptAllInOne; +(function (TypeScriptAllInOne) { + var Program = (function () { + function Program() { + this.case = bfs.STATEMENTS(4); + } + Program.Main = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + try { + var bfs = new BasicFeatures(); + var retValue = 0; + retValue = bfs.VARIABLES(); + if (retValue != 0) + ^= { + return: 1 + }; + } + finally { + } + }; + Program.prototype.if = function (retValue) { + if (retValue === void 0) { retValue = != 0; } + return 1; + ^ retValue; + bfs.TYPES(); + if (retValue != 0) { + return 1 && ; + } + retValue = bfs.OPERATOR; + ' );; + if (retValue != 0) { + return 1; + } + }; + Program.prototype.catch = function (e) { + console.log(e); + }; + return Program; + })(); + TypeScriptAllInOne.Program = Program; + try { + } + finally { + } + console.log('Done'); + return 0; +})(TypeScriptAllInOne || (TypeScriptAllInOne = {})); +var BasicFeatures = (function () { + function BasicFeatures() { + } + /// + /// Test various of variables. Including nullable,key world as variable,special format + /// + /// + BasicFeatures.prototype.VARIABLES = function () { + var local = Number.MAX_VALUE; + var min = Number.MIN_VALUE; + var inf = Number.NEGATIVE_INFINITY - ; + var nan = Number.NaN; + var undef = undefined; + var _\uD4A5\u7204\uC316, uE59F = local; + var мир = local; + var local5 = null; + var local6 = local5 instanceof fs.File; + var hex = 0xBADC0DE, Hex = 0XDEADBEEF; + var float = 6.02e23, float2 = 6.02E-23; + var char = 'c', \u0066 = '\u0066', hexchar = '\x42' != ; + var quoted = '"', quoted2 = "'"; + var reg = /\w*/; + var objLit = { "var": number = 42, equals: function (x) { + return x["var"] === 42; + }, instanceof: function () { return 'objLit{42}'; } }; + var weekday = 0 /* Monday */; + var con = char + f + hexchar + float.toString() + float2.toString() + reg.toString() + objLit + weekday; + // + var any = 0 ^= ; + var bool = 0; + var declare = 0; + var constructor = 0; + var get = 0; + var implements = 0; + var interface = 0; + var let = 0; + var module = 0; + var number = 0; + var package = 0; + var private = 0; + var protected = 0; + var public = 0; + var set = 0; + var static = 0; + var string = 0 / > ; + var yield = 0; + var sum3 = any + bool + declare + constructor + get + implements + interface + let + module + number + package + private + protected + public + set + static + string + yield; + return 0; + }; + /// + /// Test different statements. Including if-else,swith,foreach,(un)checked,lock,using,try-catch-finally + /// + /// + /// + BasicFeatures.prototype.STATEMENTS = function (i) { + var retVal = 0; + if (i == 1) + retVal = 1; + else + retVal = 0; + switch (i) { + case 2: + retVal = 1; + break; + case 3: + retVal = 1; + break; + default: + break; + } + for (var x in { x: 0, y: 1 }) { + !; + try { + throw null; + } + catch (Exception) { + } + } + try { + } + finally { + try { + } + catch (Exception) { + } + } + return retVal; + }; + /// + /// Test types in ts language. Including class,struct,interface,delegate,anonymous type + /// + /// + BasicFeatures.prototype.TYPES = function () { + var retVal = 0; + var c = new CLASS(); + var xx = c; + retVal += ; + try { + } + catch () { + } + Property; + retVal += c.Member(); + retVal += xx.Foo() ? 0 : 1; + //anonymous type + var anony = { a: new CLASS() }; + retVal += anony.a.d(); + return retVal; + }; + ///// + ///// Test different operators + ///// + ///// + BasicFeatures.prototype.OPERATOR = function () { + var a = [1, 2, 3, 4, 5,]; /*[] bug*/ // YES [] + var i = a[1]; /*[]*/ + i = i + i - i * i / i % i & i | i ^ i; /*+ - * / % & | ^*/ + var b = true && false || true ^ false; /*& | ^*/ + b = !b; /*!*/ + i = ~i; /*~i*/ + b = i < (i - 1) && (i + 1) > i; /*< && >*/ + var f = true ? 1 : 0; /*? :*/ // YES : + i++; /*++*/ + i--; /*--*/ + b = true && false || true; /*&& ||*/ + i = i << 5; /*<<*/ + i = i >> 5; /*>>*/ + var j = i; + b = i == j && i != j && i <= j && i >= j; /*= == && != <= >=*/ + i += 5.0; /*+=*/ + i -= i; /*-=*/ + i *= i; /**=*/ + if (i == 0) + i++; + i /= i; /*/=*/ + i %= i; /*%=*/ + i &= i; /*&=*/ + i |= i; /*|=*/ + i ^= i; /*^=*/ + i <<= i; /*<<=*/ + i >>= i; /*>>=*/ + if (i == 0 && != b && f == 1) + return 0; + else + return 1; + }; + return BasicFeatures; +})(); +var CLASS = (function () { + function CLASS() { + this.d = function () { + yield; + 0; + }; + } + Object.defineProperty(CLASS.prototype, "Property", { + get: function () { + return 0; + }, + enumerable: true, + configurable: true + }); + CLASS.prototype.Member = function () { + return 0; + }; + CLASS.prototype.Foo = function () { + var myEvent = function () { + return 1; + }; + if (myEvent() == 1) + return true ? : ; + else + return false; + }; + return CLASS; +})(); +// todo: use these +var A = (function () { + function A() { + } + return A; +})(); +method1(val, number); +{ + return val; +} +method2(); +{ + return 2 * this.method1(2); +} +var B = (function (_super) { + __extends(B, _super); + function B() { + _super.apply(this, arguments); + } + B.prototype.method2 = function () { + return this.method1(2); + }; + return B; +})(A); +var Overloading = (function () { + function Overloading() { + this.otherValue = 42; + } + return Overloading; +})(); +Overloads(value, string); +Overloads(); +while () + : string, ; +rest: string[]; +{ + & public; + DefaultValue(value ? : string = "Hello"); + { + } +} +var Weekdays; +(function (Weekdays) { + Weekdays[Weekdays["Monday"] = 0] = "Monday"; + Weekdays[Weekdays["Tuesday"] = 1] = "Tuesday"; + Weekdays[Weekdays["Weekend"] = 2] = "Weekend"; +})(Weekdays || (Weekdays = {})); +var Fruit; +(function (Fruit) { + Fruit[Fruit["Apple"] = 0] = "Apple"; + Fruit[Fruit["Pear"] = 1] = "Pear"; +})(Fruit || (Fruit = {})); +TypeScriptAllInOne.Program.Main(); diff --git a/tests/baselines/reference/contextualTypingOfAccessors.js b/tests/baselines/reference/contextualTypingOfAccessors.js new file mode 100644 index 00000000000..45463936831 --- /dev/null +++ b/tests/baselines/reference/contextualTypingOfAccessors.js @@ -0,0 +1,25 @@ +//// [contextualTypingOfAccessors.ts] +// not contextually typing accessors + +var x: { + foo: (x: number) => number; +} + +x = { + get foo() { + return (n)=>n + }, + set foo(x) {} +} + + +//// [contextualTypingOfAccessors.js] +// not contextually typing accessors +var x; +x = { + get foo() { + return function (n) { return n; }; + }, + set foo(x) { + } +}; diff --git a/tests/baselines/reference/contextualTypingWithFixedTypeParameters1.errors.txt b/tests/baselines/reference/contextualTypingWithFixedTypeParameters1.errors.txt index adfb1c68b7a..251a3a1bde3 100644 --- a/tests/baselines/reference/contextualTypingWithFixedTypeParameters1.errors.txt +++ b/tests/baselines/reference/contextualTypingWithFixedTypeParameters1.errors.txt @@ -1,7 +1,6 @@ tests/cases/compiler/contextualTypingWithFixedTypeParameters1.ts(2,22): error TS2339: Property 'foo' does not exist on type 'string'. -tests/cases/compiler/contextualTypingWithFixedTypeParameters1.ts(3,10): error TS2453: The type argument for type parameter 'T' cannot be inferred from the usage. Consider specifying the type arguments explicitly. - Type argument candidate 'string' is not a valid type argument because it is not a supertype of candidate 'T'. -tests/cases/compiler/contextualTypingWithFixedTypeParameters1.ts(3,32): error TS2339: Property 'foo' does not exist on type 'T'. +tests/cases/compiler/contextualTypingWithFixedTypeParameters1.ts(3,32): error TS2339: Property 'foo' does not exist on type 'string'. +tests/cases/compiler/contextualTypingWithFixedTypeParameters1.ts(3,38): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. ==== tests/cases/compiler/contextualTypingWithFixedTypeParameters1.ts (3 errors) ==== @@ -10,8 +9,7 @@ tests/cases/compiler/contextualTypingWithFixedTypeParameters1.ts(3,32): error TS ~~~ !!! error TS2339: Property 'foo' does not exist on type 'string'. var r9 = f10('', () => (a => a.foo), 1); // error - ~~~ -!!! error TS2453: The type argument for type parameter 'T' cannot be inferred from the usage. Consider specifying the type arguments explicitly. -!!! error TS2453: Type argument candidate 'string' is not a valid type argument because it is not a supertype of candidate 'T'. ~~~ -!!! error TS2339: Property 'foo' does not exist on type 'T'. \ No newline at end of file +!!! error TS2339: Property 'foo' does not exist on type 'string'. + ~ +!!! error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. \ No newline at end of file diff --git a/tests/baselines/reference/continueNotInIterationStatement1.js b/tests/baselines/reference/continueNotInIterationStatement1.js new file mode 100644 index 00000000000..b6fd1786cdf --- /dev/null +++ b/tests/baselines/reference/continueNotInIterationStatement1.js @@ -0,0 +1,5 @@ +//// [continueNotInIterationStatement1.ts] +continue; + +//// [continueNotInIterationStatement1.js] +continue; diff --git a/tests/baselines/reference/continueNotInIterationStatement2.js b/tests/baselines/reference/continueNotInIterationStatement2.js new file mode 100644 index 00000000000..047c3b49f06 --- /dev/null +++ b/tests/baselines/reference/continueNotInIterationStatement2.js @@ -0,0 +1,13 @@ +//// [continueNotInIterationStatement2.ts] +while (true) { + function f() { + continue; + } +} + +//// [continueNotInIterationStatement2.js] +while (true) { + function f() { + continue; + } +} diff --git a/tests/baselines/reference/continueNotInIterationStatement3.js b/tests/baselines/reference/continueNotInIterationStatement3.js new file mode 100644 index 00000000000..11018019871 --- /dev/null +++ b/tests/baselines/reference/continueNotInIterationStatement3.js @@ -0,0 +1,11 @@ +//// [continueNotInIterationStatement3.ts] +switch (0) { + default: + continue; +} + +//// [continueNotInIterationStatement3.js] +switch (0) { + default: + continue; +} diff --git a/tests/baselines/reference/continueNotInIterationStatement4.js b/tests/baselines/reference/continueNotInIterationStatement4.js new file mode 100644 index 00000000000..f3f52ecb48c --- /dev/null +++ b/tests/baselines/reference/continueNotInIterationStatement4.js @@ -0,0 +1,15 @@ +//// [continueNotInIterationStatement4.ts] +TWO: +while (true){ + var x = () => { + continue TWO; + } +} + + +//// [continueNotInIterationStatement4.js] +TWO: while (true) { + var x = function () { + continue TWO; + }; +} diff --git a/tests/baselines/reference/continueTarget1.js b/tests/baselines/reference/continueTarget1.js new file mode 100644 index 00000000000..07e5a7b9b50 --- /dev/null +++ b/tests/baselines/reference/continueTarget1.js @@ -0,0 +1,6 @@ +//// [continueTarget1.ts] +target: + continue target; + +//// [continueTarget1.js] +target: continue target; diff --git a/tests/baselines/reference/continueTarget5.js b/tests/baselines/reference/continueTarget5.js new file mode 100644 index 00000000000..5bf309d2690 --- /dev/null +++ b/tests/baselines/reference/continueTarget5.js @@ -0,0 +1,18 @@ +//// [continueTarget5.ts] +target: +while (true) { + function f() { + while (true) { + continue target; + } + } +} + +//// [continueTarget5.js] +target: while (true) { + function f() { + while (true) { + continue target; + } + } +} diff --git a/tests/baselines/reference/continueTarget6.js b/tests/baselines/reference/continueTarget6.js new file mode 100644 index 00000000000..aefa8e97652 --- /dev/null +++ b/tests/baselines/reference/continueTarget6.js @@ -0,0 +1,9 @@ +//// [continueTarget6.ts] +while (true) { + continue target; +} + +//// [continueTarget6.js] +while (true) { + continue target; +} diff --git a/tests/baselines/reference/createArray.js b/tests/baselines/reference/createArray.js new file mode 100644 index 00000000000..82572e05cad --- /dev/null +++ b/tests/baselines/reference/createArray.js @@ -0,0 +1,34 @@ +//// [createArray.ts] +var na=new number[]; + +class C { +} + +new C[]; +var ba=new boolean[]; +var sa=new string[]; +function f(s:string):number { return 0; +} +if (ba[14]) { + na[2]=f(sa[3]); +} + +new C[1]; // not an error + +//// [createArray.js] +var na = new number[]; +var C = (function () { + function C() { + } + return C; +})(); +new C[]; +var ba = new boolean[]; +var sa = new string[]; +function f(s) { + return 0; +} +if (ba[14]) { + na[2] = f(sa[3]); +} +new C[1]; // not an error diff --git a/tests/baselines/reference/declFileObjectLiteralWithAccessors.js b/tests/baselines/reference/declFileObjectLiteralWithAccessors.js new file mode 100644 index 00000000000..00598cfcf3e --- /dev/null +++ b/tests/baselines/reference/declFileObjectLiteralWithAccessors.js @@ -0,0 +1,29 @@ +//// [declFileObjectLiteralWithAccessors.ts] + +function /*1*/makePoint(x: number) { + return { + b: 10, + get x() { return x; }, + set x(a: number) { this.b = a; } + }; +}; +var /*4*/point = makePoint(2); +var /*2*/x = point.x; +point./*3*/x = 30; + +//// [declFileObjectLiteralWithAccessors.js] +function makePoint(x) { + return { + b: 10, + get x() { + return x; + }, + set x(a) { + this.b = a; + } + }; +} +; +var point = makePoint(2); +var x = point.x; +point.x = 30; diff --git a/tests/baselines/reference/declFileObjectLiteralWithOnlyGetter.js b/tests/baselines/reference/declFileObjectLiteralWithOnlyGetter.js new file mode 100644 index 00000000000..ed457931a69 --- /dev/null +++ b/tests/baselines/reference/declFileObjectLiteralWithOnlyGetter.js @@ -0,0 +1,22 @@ +//// [declFileObjectLiteralWithOnlyGetter.ts] + +function /*1*/makePoint(x: number) { + return { + get x() { return x; }, + }; +}; +var /*4*/point = makePoint(2); +var /*2*/x = point./*3*/x; + + +//// [declFileObjectLiteralWithOnlyGetter.js] +function makePoint(x) { + return { + get x() { + return x; + } + }; +} +; +var point = makePoint(2); +var x = point.x; diff --git a/tests/baselines/reference/declFileObjectLiteralWithOnlySetter.js b/tests/baselines/reference/declFileObjectLiteralWithOnlySetter.js new file mode 100644 index 00000000000..f5716bb06e0 --- /dev/null +++ b/tests/baselines/reference/declFileObjectLiteralWithOnlySetter.js @@ -0,0 +1,23 @@ +//// [declFileObjectLiteralWithOnlySetter.ts] + +function /*1*/makePoint(x: number) { + return { + b: 10, + set x(a: number) { this.b = a; } + }; +}; +var /*3*/point = makePoint(2); +point./*2*/x = 30; + +//// [declFileObjectLiteralWithOnlySetter.js] +function makePoint(x) { + return { + b: 10, + set x(a) { + this.b = a; + } + }; +} +; +var point = makePoint(2); +point.x = 30; diff --git a/tests/baselines/reference/declFilePrivateStatic.js b/tests/baselines/reference/declFilePrivateStatic.js new file mode 100644 index 00000000000..38dbdb126af --- /dev/null +++ b/tests/baselines/reference/declFilePrivateStatic.js @@ -0,0 +1,54 @@ +//// [declFilePrivateStatic.ts] + +class C { + private static x = 1; + static y = 1; + + private static a() { } + static b() { } + + private static get c() { return 1; } + static get d() { return 1; } + + private static set e(v) { } + static set f(v) { } +} + +//// [declFilePrivateStatic.js] +var C = (function () { + function C() { + } + C.a = function () { + }; + C.b = function () { + }; + Object.defineProperty(C, "c", { + get: function () { + return 1; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(C, "d", { + get: function () { + return 1; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(C, "e", { + set: function (v) { + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(C, "f", { + set: function (v) { + }, + enumerable: true, + configurable: true + }); + C.x = 1; + C.y = 1; + return C; +})(); diff --git a/tests/baselines/reference/declarationEmit_invalidReference2.js b/tests/baselines/reference/declarationEmit_invalidReference2.js new file mode 100644 index 00000000000..78fb232cca7 --- /dev/null +++ b/tests/baselines/reference/declarationEmit_invalidReference2.js @@ -0,0 +1,11 @@ +//// [declarationEmit_invalidReference2.ts] +/// +var x = 0; + +//// [declarationEmit_invalidReference2.js] +/// +var x = 0; + + +//// [declarationEmit_invalidReference2.d.ts] +declare var x: number; diff --git a/tests/baselines/reference/declarationInAmbientContext.js b/tests/baselines/reference/declarationInAmbientContext.js new file mode 100644 index 00000000000..eb39bccc818 --- /dev/null +++ b/tests/baselines/reference/declarationInAmbientContext.js @@ -0,0 +1,6 @@ +//// [declarationInAmbientContext.ts] +declare var [a, b]; // Error, destructuring declaration not allowed in ambient context +declare var {c, d}; // Error, destructuring declaration not allowed in ambient context + + +//// [declarationInAmbientContext.js] diff --git a/tests/baselines/reference/declarationWithNoInitializer.js b/tests/baselines/reference/declarationWithNoInitializer.js new file mode 100644 index 00000000000..54d89368fb1 --- /dev/null +++ b/tests/baselines/reference/declarationWithNoInitializer.js @@ -0,0 +1,8 @@ +//// [declarationWithNoInitializer.ts] +var [a, b]; // Error, no initializer +var {c, d}; // Error, no initializer + + +//// [declarationWithNoInitializer.js] +var _a = void 0, a = _a[0], b = _a[1]; // Error, no initializer +var _b = void 0, c = _b.c, d = _b.d; // Error, no initializer diff --git a/tests/baselines/reference/declareAlreadySeen.js b/tests/baselines/reference/declareAlreadySeen.js new file mode 100644 index 00000000000..51421a67cb7 --- /dev/null +++ b/tests/baselines/reference/declareAlreadySeen.js @@ -0,0 +1,14 @@ +//// [declareAlreadySeen.ts] +module M { + declare declare var x; + declare declare function f(); + + declare declare module N { } + + declare declare class C { } +} + +//// [declareAlreadySeen.js] +var M; +(function (M) { +})(M || (M = {})); diff --git a/tests/baselines/reference/declareModifierOnImport1.js b/tests/baselines/reference/declareModifierOnImport1.js new file mode 100644 index 00000000000..510407b4deb --- /dev/null +++ b/tests/baselines/reference/declareModifierOnImport1.js @@ -0,0 +1,4 @@ +//// [declareModifierOnImport1.ts] +declare import a = b; + +//// [declareModifierOnImport1.js] diff --git a/tests/baselines/reference/deleteOperatorInStrictMode.js b/tests/baselines/reference/deleteOperatorInStrictMode.js new file mode 100644 index 00000000000..3fcf8dd836b --- /dev/null +++ b/tests/baselines/reference/deleteOperatorInStrictMode.js @@ -0,0 +1,9 @@ +//// [deleteOperatorInStrictMode.ts] +"use strict" +var a; +delete a; + +//// [deleteOperatorInStrictMode.js] +"use strict"; +var a; +delete a; diff --git a/tests/baselines/reference/deleteOperatorInvalidOperations.js b/tests/baselines/reference/deleteOperatorInvalidOperations.js new file mode 100644 index 00000000000..fd15797698e --- /dev/null +++ b/tests/baselines/reference/deleteOperatorInvalidOperations.js @@ -0,0 +1,33 @@ +//// [deleteOperatorInvalidOperations.ts] +// Unary operator delete +var ANY; + +// operand before delete operator +var BOOLEAN1 = ANY delete ; //expect error + +// miss an operand +var BOOLEAN2 = delete ; + +// delete global variable s +class testADelx { + constructor(public s: () => {}) { + delete s; //expect error + } +} + +//// [deleteOperatorInvalidOperations.js] +// Unary operator delete +var ANY; +// operand before delete operator +var BOOLEAN1 = ANY; +delete ; //expect error +// miss an operand +var BOOLEAN2 = delete ; +// delete global variable s +var testADelx = (function () { + function testADelx(s) { + this.s = s; + delete s; //expect error + } + return testADelx; +})(); diff --git a/tests/baselines/reference/derivedClassFunctionOverridesBaseClassAccessor.js b/tests/baselines/reference/derivedClassFunctionOverridesBaseClassAccessor.js new file mode 100644 index 00000000000..615c3e7f7a6 --- /dev/null +++ b/tests/baselines/reference/derivedClassFunctionOverridesBaseClassAccessor.js @@ -0,0 +1,48 @@ +//// [derivedClassFunctionOverridesBaseClassAccessor.ts] +class Base { + get x() { + return 1; + } + set x(v) { + } +} + +// error +class Derived extends Base { + x() { + return 1; + } +} + +//// [derivedClassFunctionOverridesBaseClassAccessor.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var Base = (function () { + function Base() { + } + Object.defineProperty(Base.prototype, "x", { + get: function () { + return 1; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + return Base; +})(); +// error +var Derived = (function (_super) { + __extends(Derived, _super); + function Derived() { + _super.apply(this, arguments); + } + Derived.prototype.x = function () { + return 1; + }; + return Derived; +})(Base); diff --git a/tests/baselines/reference/derivedClassIncludesInheritedMembers.js b/tests/baselines/reference/derivedClassIncludesInheritedMembers.js new file mode 100644 index 00000000000..db54affa6d9 --- /dev/null +++ b/tests/baselines/reference/derivedClassIncludesInheritedMembers.js @@ -0,0 +1,107 @@ +//// [derivedClassIncludesInheritedMembers.ts] +class Base { + a: string; + b() { } + get c() { return ''; } + set c(v) { } + + static r: string; + static s() { } + static get t() { return ''; } + static set t(v) { } + + constructor(x) { } +} + +class Derived extends Base { +} + +var d: Derived = new Derived(1); +var r1 = d.a; +var r2 = d.b(); +var r3 = d.c; +d.c = ''; +var r4 = Derived.r; +var r5 = Derived.s(); +var r6 = Derived.t; +Derived.t = ''; + +class Base2 { + [x: string]: Object; + [x: number]: Date; +} + +class Derived2 extends Base2 { +} + +var d2: Derived2; +var r7 = d2['']; +var r8 = d2[1]; + + + +//// [derivedClassIncludesInheritedMembers.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var Base = (function () { + function Base(x) { + } + Base.prototype.b = function () { + }; + Object.defineProperty(Base.prototype, "c", { + get: function () { + return ''; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + Base.s = function () { + }; + Object.defineProperty(Base, "t", { + get: function () { + return ''; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + return Base; +})(); +var Derived = (function (_super) { + __extends(Derived, _super); + function Derived() { + _super.apply(this, arguments); + } + return Derived; +})(Base); +var d = new Derived(1); +var r1 = d.a; +var r2 = d.b(); +var r3 = d.c; +d.c = ''; +var r4 = Derived.r; +var r5 = Derived.s(); +var r6 = Derived.t; +Derived.t = ''; +var Base2 = (function () { + function Base2() { + } + return Base2; +})(); +var Derived2 = (function (_super) { + __extends(Derived2, _super); + function Derived2() { + _super.apply(this, arguments); + } + return Derived2; +})(Base2); +var d2; +var r7 = d2['']; +var r8 = d2[1]; diff --git a/tests/baselines/reference/derivedClassOverridesPublicMembers.js b/tests/baselines/reference/derivedClassOverridesPublicMembers.js new file mode 100644 index 00000000000..f673d9ab856 --- /dev/null +++ b/tests/baselines/reference/derivedClassOverridesPublicMembers.js @@ -0,0 +1,155 @@ +//// [derivedClassOverridesPublicMembers.ts] +var x: { foo: string; } +var y: { foo: string; bar: string; } + +class Base { + a: typeof x; + b(a: typeof x) { } + get c() { return x; } + set c(v: typeof x) { } + d: (a: typeof x) => void; + + static r: typeof x; + static s(a: typeof x) { } + static get t() { return x; } + static set t(v: typeof x) { } + static u: (a: typeof x) => void; + + constructor(a: typeof x) { } +} + +class Derived extends Base { + a: typeof y; + b(a: typeof y) { } + get c() { return y; } + set c(v: typeof y) { } + d: (a: typeof y) => void; + + static r: typeof y; + static s(a: typeof y) { } + static get t() { return y; } + static set t(a: typeof y) { } + static u: (a: typeof y) => void; + + constructor(a: typeof y) { super(x) } +} + +var d: Derived = new Derived(y); +var r1 = d.a; +var r2 = d.b(y); +var r3 = d.c; +var r3a = d.d; +d.c = y; +var r4 = Derived.r; +var r5 = Derived.s(y); +var r6 = Derived.t; +var r6a = Derived.u; +Derived.t = y; + +class Base2 { + [i: string]: Object; + [i: number]: typeof x; +} + +class Derived2 extends Base2 { + [i: string]: typeof x; + [i: number]: typeof y; +} + +var d2: Derived2; +var r7 = d2['']; +var r8 = d2[1]; + + + +//// [derivedClassOverridesPublicMembers.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var x; +var y; +var Base = (function () { + function Base(a) { + } + Base.prototype.b = function (a) { + }; + Object.defineProperty(Base.prototype, "c", { + get: function () { + return x; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + Base.s = function (a) { + }; + Object.defineProperty(Base, "t", { + get: function () { + return x; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + return Base; +})(); +var Derived = (function (_super) { + __extends(Derived, _super); + function Derived(a) { + _super.call(this, x); + } + Derived.prototype.b = function (a) { + }; + Object.defineProperty(Derived.prototype, "c", { + get: function () { + return y; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + Derived.s = function (a) { + }; + Object.defineProperty(Derived, "t", { + get: function () { + return y; + }, + set: function (a) { + }, + enumerable: true, + configurable: true + }); + return Derived; +})(Base); +var d = new Derived(y); +var r1 = d.a; +var r2 = d.b(y); +var r3 = d.c; +var r3a = d.d; +d.c = y; +var r4 = Derived.r; +var r5 = Derived.s(y); +var r6 = Derived.t; +var r6a = Derived.u; +Derived.t = y; +var Base2 = (function () { + function Base2() { + } + return Base2; +})(); +var Derived2 = (function (_super) { + __extends(Derived2, _super); + function Derived2() { + _super.apply(this, arguments); + } + return Derived2; +})(Base2); +var d2; +var r7 = d2['']; +var r8 = d2[1]; diff --git a/tests/baselines/reference/derivedClassSuperCallsInNonConstructorMembers.js b/tests/baselines/reference/derivedClassSuperCallsInNonConstructorMembers.js new file mode 100644 index 00000000000..14ac1f47e2f --- /dev/null +++ b/tests/baselines/reference/derivedClassSuperCallsInNonConstructorMembers.js @@ -0,0 +1,83 @@ +//// [derivedClassSuperCallsInNonConstructorMembers.ts] +// error to use super calls outside a constructor + +class Base { + x: string; +} + +class Derived extends Base { + a: super(); + b() { + super(); + } + get C() { + super(); + return 1; + } + set C(v) { + super(); + } + + static a: super(); + static b() { + super(); + } + static get C() { + super(); + return 1; + } + static set C(v) { + super(); + } +} + +//// [derivedClassSuperCallsInNonConstructorMembers.js] +// error to use super calls outside a constructor +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var Base = (function () { + function Base() { + } + return Base; +})(); +var Derived = (function (_super) { + __extends(Derived, _super); + function Derived() { + _super.apply(this, arguments); + this.a = _super.call(this); + } + Derived.prototype.b = function () { + _super.call(this); + }; + Object.defineProperty(Derived.prototype, "C", { + get: function () { + _super.call(this); + return 1; + }, + set: function (v) { + _super.call(this); + }, + enumerable: true, + configurable: true + }); + Derived.b = function () { + _super.call(this); + }; + Object.defineProperty(Derived, "C", { + get: function () { + _super.call(this); + return 1; + }, + set: function (v) { + _super.call(this); + }, + enumerable: true, + configurable: true + }); + Derived.a = _super.call(this); + return Derived; +})(Base); diff --git a/tests/baselines/reference/derivedClassWithAny.js b/tests/baselines/reference/derivedClassWithAny.js new file mode 100644 index 00000000000..0b568eaec9b --- /dev/null +++ b/tests/baselines/reference/derivedClassWithAny.js @@ -0,0 +1,154 @@ +//// [derivedClassWithAny.ts] +class C { + x: number; + get X(): number { return 1; } + foo(): number { + return 1; + } + + static y: number; + static get Y(): number { + return 1; + } + static bar(): number { + return 1; + } +} + +class D extends C { + x: any; + get X(): any { + return null; + } + foo(): any { + return 1; + } + + static y: any; + static get Y(): any { + return null; + } + static bar(): any { + return null; + } +} + +// if D is a valid class definition than E is now not safe tranisitively through C +class E extends D { + x: string; + get X(): string{ return ''; } + foo(): string { + return ''; + } + + static y: string; + static get Y(): string { + return ''; + } + static bar(): string { + return ''; + } +} + +var c: C; +var d: D; +var e: E; + +c = d; +c = e; +var r = c.foo(); // e.foo would return string + + +//// [derivedClassWithAny.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "X", { + get: function () { + return 1; + }, + enumerable: true, + configurable: true + }); + C.prototype.foo = function () { + return 1; + }; + Object.defineProperty(C, "Y", { + get: function () { + return 1; + }, + enumerable: true, + configurable: true + }); + C.bar = function () { + return 1; + }; + return C; +})(); +var D = (function (_super) { + __extends(D, _super); + function D() { + _super.apply(this, arguments); + } + Object.defineProperty(D.prototype, "X", { + get: function () { + return null; + }, + enumerable: true, + configurable: true + }); + D.prototype.foo = function () { + return 1; + }; + Object.defineProperty(D, "Y", { + get: function () { + return null; + }, + enumerable: true, + configurable: true + }); + D.bar = function () { + return null; + }; + return D; +})(C); +// if D is a valid class definition than E is now not safe tranisitively through C +var E = (function (_super) { + __extends(E, _super); + function E() { + _super.apply(this, arguments); + } + Object.defineProperty(E.prototype, "X", { + get: function () { + return ''; + }, + enumerable: true, + configurable: true + }); + E.prototype.foo = function () { + return ''; + }; + Object.defineProperty(E, "Y", { + get: function () { + return ''; + }, + enumerable: true, + configurable: true + }); + E.bar = function () { + return ''; + }; + return E; +})(D); +var c; +var d; +var e; +c = d; +c = e; +var r = c.foo(); // e.foo would return string diff --git a/tests/baselines/reference/derivedClassWithPrivateInstanceShadowingPublicInstance.js b/tests/baselines/reference/derivedClassWithPrivateInstanceShadowingPublicInstance.js new file mode 100644 index 00000000000..fb0dee3e57b --- /dev/null +++ b/tests/baselines/reference/derivedClassWithPrivateInstanceShadowingPublicInstance.js @@ -0,0 +1,86 @@ +//// [derivedClassWithPrivateInstanceShadowingPublicInstance.ts] +class Base { + public x: string; + public fn(): string { + return ''; + } + + public get a() { return 1; } + public set a(v) { } +} + +// error, not a subtype +class Derived extends Base { + private x: string; + private fn(): string { + return ''; + } + + private get a() { return 1; } + private set a(v) { } +} + +var r = Base.x; // ok +var r2 = Derived.x; // error + +var r3 = Base.fn(); // ok +var r4 = Derived.fn(); // error + +var r5 = Base.a; // ok +Base.a = 2; // ok + +var r6 = Derived.a; // error +Derived.a = 2; // error + +//// [derivedClassWithPrivateInstanceShadowingPublicInstance.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var Base = (function () { + function Base() { + } + Base.prototype.fn = function () { + return ''; + }; + Object.defineProperty(Base.prototype, "a", { + get: function () { + return 1; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + return Base; +})(); +// error, not a subtype +var Derived = (function (_super) { + __extends(Derived, _super); + function Derived() { + _super.apply(this, arguments); + } + Derived.prototype.fn = function () { + return ''; + }; + Object.defineProperty(Derived.prototype, "a", { + get: function () { + return 1; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + return Derived; +})(Base); +var r = Base.x; // ok +var r2 = Derived.x; // error +var r3 = Base.fn(); // ok +var r4 = Derived.fn(); // error +var r5 = Base.a; // ok +Base.a = 2; // ok +var r6 = Derived.a; // error +Derived.a = 2; // error diff --git a/tests/baselines/reference/derivedClassWithPrivateStaticShadowingPublicStatic.js b/tests/baselines/reference/derivedClassWithPrivateStaticShadowingPublicStatic.js new file mode 100644 index 00000000000..b2468f62d81 --- /dev/null +++ b/tests/baselines/reference/derivedClassWithPrivateStaticShadowingPublicStatic.js @@ -0,0 +1,88 @@ +//// [derivedClassWithPrivateStaticShadowingPublicStatic.ts] +class Base { + public static x: string; + public static fn(): string { + return ''; + } + + public static get a() { return 1; } + public static set a(v) { } +} + +// BUG 847404 +// should be error +class Derived extends Base { + private static x: string; + private static fn(): string { + return ''; + } + + private static get a() { return 1; } + private static set a(v) { } +} + +var r = Base.x; // ok +var r2 = Derived.x; // error + +var r3 = Base.fn(); // ok +var r4 = Derived.fn(); // error + +var r5 = Base.a; // ok +Base.a = 2; // ok + +var r6 = Derived.a; // error +Derived.a = 2; // error + +//// [derivedClassWithPrivateStaticShadowingPublicStatic.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var Base = (function () { + function Base() { + } + Base.fn = function () { + return ''; + }; + Object.defineProperty(Base, "a", { + get: function () { + return 1; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + return Base; +})(); +// BUG 847404 +// should be error +var Derived = (function (_super) { + __extends(Derived, _super); + function Derived() { + _super.apply(this, arguments); + } + Derived.fn = function () { + return ''; + }; + Object.defineProperty(Derived, "a", { + get: function () { + return 1; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + return Derived; +})(Base); +var r = Base.x; // ok +var r2 = Derived.x; // error +var r3 = Base.fn(); // ok +var r4 = Derived.fn(); // error +var r5 = Base.a; // ok +Base.a = 2; // ok +var r6 = Derived.a; // error +Derived.a = 2; // error diff --git a/tests/baselines/reference/derivedGenericClassWithAny.js b/tests/baselines/reference/derivedGenericClassWithAny.js new file mode 100644 index 00000000000..677fadf3876 --- /dev/null +++ b/tests/baselines/reference/derivedGenericClassWithAny.js @@ -0,0 +1,118 @@ +//// [derivedGenericClassWithAny.ts] +class C { + x: T; + get X(): T { return null; } + foo(): T { + return null; + } +} + +class D extends C { + x: any; + get X(): any { + return null; + } + foo(): any { + return 1; + } + + static y: any; + static get Y(): any { + return null; + } + static bar(): any { + return null; + } +} + +// if D is a valid class definition than E is now not safe tranisitively through C +class E extends D { + x: T; + get X(): T { return ''; } // error + foo(): T { + return ''; // error + } +} + +var c: C; +var d: D; +var e: E; + +c = d; +c = e; +var r = c.foo(); // e.foo would return string + +//// [derivedGenericClassWithAny.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "X", { + get: function () { + return null; + }, + enumerable: true, + configurable: true + }); + C.prototype.foo = function () { + return null; + }; + return C; +})(); +var D = (function (_super) { + __extends(D, _super); + function D() { + _super.apply(this, arguments); + } + Object.defineProperty(D.prototype, "X", { + get: function () { + return null; + }, + enumerable: true, + configurable: true + }); + D.prototype.foo = function () { + return 1; + }; + Object.defineProperty(D, "Y", { + get: function () { + return null; + }, + enumerable: true, + configurable: true + }); + D.bar = function () { + return null; + }; + return D; +})(C); +// if D is a valid class definition than E is now not safe tranisitively through C +var E = (function (_super) { + __extends(E, _super); + function E() { + _super.apply(this, arguments); + } + Object.defineProperty(E.prototype, "X", { + get: function () { + return ''; + } // error + , + enumerable: true, + configurable: true + }); + E.prototype.foo = function () { + return ''; // error + }; + return E; +})(D); +var c; +var d; +var e; +c = d; +c = e; +var r = c.foo(); // e.foo would return string diff --git a/tests/baselines/reference/differentTypesWithSameName.errors.txt b/tests/baselines/reference/differentTypesWithSameName.errors.txt new file mode 100644 index 00000000000..b0850ee7f41 --- /dev/null +++ b/tests/baselines/reference/differentTypesWithSameName.errors.txt @@ -0,0 +1,24 @@ +tests/cases/compiler/differentTypesWithSameName.ts(16,15): error TS2345: Argument of type 'variable' is not assignable to parameter of type 'm.variable'. + Property 's' is missing in type 'variable'. + + +==== tests/cases/compiler/differentTypesWithSameName.ts (1 errors) ==== + module m { + export class variable{ + s: string; + } + export function doSomething(v: m.variable) { + + } + } + + class variable { + t: number; + } + + + var v: variable = new variable(); + m.doSomething(v); + ~ +!!! error TS2345: Argument of type 'variable' is not assignable to parameter of type 'm.variable'. +!!! error TS2345: Property 's' is missing in type 'variable'. \ No newline at end of file diff --git a/tests/baselines/reference/differentTypesWithSameName.js b/tests/baselines/reference/differentTypesWithSameName.js new file mode 100644 index 00000000000..54a7a0f43bd --- /dev/null +++ b/tests/baselines/reference/differentTypesWithSameName.js @@ -0,0 +1,38 @@ +//// [differentTypesWithSameName.ts] +module m { + export class variable{ + s: string; + } + export function doSomething(v: m.variable) { + + } +} + +class variable { + t: number; +} + + +var v: variable = new variable(); +m.doSomething(v); + +//// [differentTypesWithSameName.js] +var m; +(function (m) { + var variable = (function () { + function variable() { + } + return variable; + })(); + m.variable = variable; + function doSomething(v) { + } + m.doSomething = doSomething; +})(m || (m = {})); +var variable = (function () { + function variable() { + } + return variable; +})(); +var v = new variable(); +m.doSomething(v); diff --git a/tests/baselines/reference/dontShowCompilerGeneratedMembers.js b/tests/baselines/reference/dontShowCompilerGeneratedMembers.js new file mode 100644 index 00000000000..5815e49c893 --- /dev/null +++ b/tests/baselines/reference/dontShowCompilerGeneratedMembers.js @@ -0,0 +1,9 @@ +//// [dontShowCompilerGeneratedMembers.ts] +var f: { + x: number; + <- +}; + +//// [dontShowCompilerGeneratedMembers.js] +var f = -; +; diff --git a/tests/baselines/reference/dottedModuleName.js b/tests/baselines/reference/dottedModuleName.js new file mode 100644 index 00000000000..6a8f33ca7bb --- /dev/null +++ b/tests/baselines/reference/dottedModuleName.js @@ -0,0 +1,55 @@ +//// [dottedModuleName.ts] +module M { + export module N { + export function f(x:number)=>2*x; + export module X.Y.Z { + export var v2=f(v); + } + } +} + + + +module M.N { + export module X { + export module Y.Z { + export var v=f(10); + } + } +} + + +//// [dottedModuleName.js] +var M; +(function (M) { + var N; + (function (N) { + 2 * x; + var X; + (function (X) { + var Y; + (function (Y) { + var Z; + (function (Z) { + Z.v2 = f(Z.v); + })(Z = Y.Z || (Y.Z = {})); + })(Y = X.Y || (X.Y = {})); + })(X = N.X || (N.X = {})); + })(N = M.N || (M.N = {})); +})(M || (M = {})); +var M; +(function (M) { + var N; + (function (N) { + var X; + (function (X) { + var Y; + (function (Y) { + var Z; + (function (Z) { + Z.v = N.f(10); + })(Z = Y.Z || (Y.Z = {})); + })(Y = X.Y || (X.Y = {})); + })(X = N.X || (N.X = {})); + })(N = M.N || (M.N = {})); +})(M || (M = {})); diff --git a/tests/baselines/reference/duplicateClassElements.js b/tests/baselines/reference/duplicateClassElements.js new file mode 100644 index 00000000000..da320eb9ac4 --- /dev/null +++ b/tests/baselines/reference/duplicateClassElements.js @@ -0,0 +1,105 @@ +//// [duplicateClassElements.ts] +class a { + public a; + public a; + public b() { + } + public b() { + } + public x; + get x() { + return 10; + } + set x(_x: number) { + } + + get y() { + return "Hello"; + } + set y(_y: string) { + } + + public z() { + } + get z() { + return "Hello"; + } + set z(_y: string) { + } + + get x2() { + return 10; + } + set x2(_x: number) { + } + public x2; + + get z2() { + return "Hello"; + } + set z2(_y: string) { + } + public z2() { + } + +} + +//// [duplicateClassElements.js] +var a = (function () { + function a() { + } + a.prototype.b = function () { + }; + a.prototype.b = function () { + }; + Object.defineProperty(a.prototype, "x", { + get: function () { + return 10; + }, + set: function (_x) { + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(a.prototype, "y", { + get: function () { + return "Hello"; + }, + set: function (_y) { + }, + enumerable: true, + configurable: true + }); + a.prototype.z = function () { + }; + Object.defineProperty(a.prototype, "z", { + get: function () { + return "Hello"; + }, + set: function (_y) { + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(a.prototype, "x2", { + get: function () { + return 10; + }, + set: function (_x) { + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(a.prototype, "z2", { + get: function () { + return "Hello"; + }, + set: function (_y) { + }, + enumerable: true, + configurable: true + }); + a.prototype.z2 = function () { + }; + return a; +})(); diff --git a/tests/baselines/reference/duplicateExportAssignments.js b/tests/baselines/reference/duplicateExportAssignments.js new file mode 100644 index 00000000000..7d2776962f7 --- /dev/null +++ b/tests/baselines/reference/duplicateExportAssignments.js @@ -0,0 +1,80 @@ +//// [tests/cases/conformance/externalModules/duplicateExportAssignments.ts] //// + +//// [foo1.ts] +var x = 10; +var y = 20; +export = x; +export = y; + +//// [foo2.ts] +var x = 10; +class y {}; +export = x; +export = y; + +//// [foo3.ts] +module x { + export var x = 10; +} +class y { + y: number; +} +export = x; +export = y; + +//// [foo4.ts] +export = x; +function x(){ + return 42; +} +function y(){ + return 42; +} +export = y; + +//// [foo5.ts] +var x = 5; +var y = "test"; +var z = {}; +export = x; +export = y; +export = z; + + +//// [foo1.js] +var x = 10; +var y = 20; +module.exports = x; +//// [foo2.js] +var x = 10; +var y = (function () { + function y() { + } + return y; +})(); +; +module.exports = x; +//// [foo3.js] +var x; +(function (_x) { + _x.x = 10; +})(x || (x = {})); +var y = (function () { + function y() { + } + return y; +})(); +module.exports = x; +//// [foo4.js] +function x() { + return 42; +} +function y() { + return 42; +} +module.exports = x; +//// [foo5.js] +var x = 5; +var y = "test"; +var z = {}; +module.exports = x; diff --git a/tests/baselines/reference/duplicateLabel1.js b/tests/baselines/reference/duplicateLabel1.js new file mode 100644 index 00000000000..e7976895c94 --- /dev/null +++ b/tests/baselines/reference/duplicateLabel1.js @@ -0,0 +1,9 @@ +//// [duplicateLabel1.ts] +target: +target: +while (true) { +} + +//// [duplicateLabel1.js] +target: target: while (true) { +} diff --git a/tests/baselines/reference/duplicateLabel2.js b/tests/baselines/reference/duplicateLabel2.js new file mode 100644 index 00000000000..9ee9671d59d --- /dev/null +++ b/tests/baselines/reference/duplicateLabel2.js @@ -0,0 +1,13 @@ +//// [duplicateLabel2.ts] +target: +while (true) { + target: + while (true) { + } +} + +//// [duplicateLabel2.js] +target: while (true) { + target: while (true) { + } +} diff --git a/tests/baselines/reference/duplicateObjectLiteralProperty.js b/tests/baselines/reference/duplicateObjectLiteralProperty.js new file mode 100644 index 00000000000..5bbeb433a0c --- /dev/null +++ b/tests/baselines/reference/duplicateObjectLiteralProperty.js @@ -0,0 +1,41 @@ +//// [duplicateObjectLiteralProperty.ts] +var x = { + a: 1, + b: true, // OK + a: 56, // Duplicate + \u0061: "ss", // Duplicate + a: { + c: 1, + "c": 56, // Duplicate + } +}; + + +var y = { + get a() { return 0; }, + set a(v: number) { }, + get a() { return 0; } +}; + + +//// [duplicateObjectLiteralProperty.js] +var x = { + a: 1, + b: true, + a: 56, + \u0061: "ss", + a: { + c: 1, + "c": 56, + } +}; +var y = { + get a() { + return 0; + }, + set a(v) { + }, + get a() { + return 0; + } +}; diff --git a/tests/baselines/reference/duplicatePropertiesInStrictMode.js b/tests/baselines/reference/duplicatePropertiesInStrictMode.js new file mode 100644 index 00000000000..37bb3d62b7f --- /dev/null +++ b/tests/baselines/reference/duplicatePropertiesInStrictMode.js @@ -0,0 +1,13 @@ +//// [duplicatePropertiesInStrictMode.ts] +"use strict"; +var x = { + x: 1, + x: 2 +} + +//// [duplicatePropertiesInStrictMode.js] +"use strict"; +var x = { + x: 1, + x: 2 +}; diff --git a/tests/baselines/reference/emitArrowFunction.js b/tests/baselines/reference/emitArrowFunction.js new file mode 100644 index 00000000000..1c00a7579b6 --- /dev/null +++ b/tests/baselines/reference/emitArrowFunction.js @@ -0,0 +1,29 @@ +//// [emitArrowFunction.ts] +var f1 = () => { } +var f2 = (x: string, y: string) => { } +var f3 = (x: string, y: number, ...rest) => { } +var f4 = (x: string, y: number, z = 10) => { } +function foo(func: () => boolean) { } +foo(() => true); +foo(() => { return false; }); + +//// [emitArrowFunction.js] +var f1 = function () { +}; +var f2 = function (x, y) { +}; +var f3 = function (x, y) { + var rest = []; + for (var _i = 2; _i < arguments.length; _i++) { + rest[_i - 2] = arguments[_i]; + } +}; +var f4 = function (x, y, z) { + if (z === void 0) { z = 10; } +}; +function foo(func) { +} +foo(function () { return true; }); +foo(function () { + return false; +}); diff --git a/tests/baselines/reference/emitArrowFunction.types b/tests/baselines/reference/emitArrowFunction.types new file mode 100644 index 00000000000..030ed0cde60 --- /dev/null +++ b/tests/baselines/reference/emitArrowFunction.types @@ -0,0 +1,39 @@ +=== tests/cases/conformance/es6/arrowFunction/emitArrowFunction.ts === +var f1 = () => { } +>f1 : () => void +>() => { } : () => void + +var f2 = (x: string, y: string) => { } +>f2 : (x: string, y: string) => void +>(x: string, y: string) => { } : (x: string, y: string) => void +>x : string +>y : string + +var f3 = (x: string, y: number, ...rest) => { } +>f3 : (x: string, y: number, ...rest: any[]) => void +>(x: string, y: number, ...rest) => { } : (x: string, y: number, ...rest: any[]) => void +>x : string +>y : number +>rest : any[] + +var f4 = (x: string, y: number, z = 10) => { } +>f4 : (x: string, y: number, z?: number) => void +>(x: string, y: number, z = 10) => { } : (x: string, y: number, z?: number) => void +>x : string +>y : number +>z : number + +function foo(func: () => boolean) { } +>foo : (func: () => boolean) => void +>func : () => boolean + +foo(() => true); +>foo(() => true) : void +>foo : (func: () => boolean) => void +>() => true : () => boolean + +foo(() => { return false; }); +>foo(() => { return false; }) : void +>foo : (func: () => boolean) => void +>() => { return false; } : () => boolean + diff --git a/tests/baselines/reference/emitArrowFunctionAsIs.js b/tests/baselines/reference/emitArrowFunctionAsIs.js new file mode 100644 index 00000000000..11df7903ad8 --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionAsIs.js @@ -0,0 +1,13 @@ +//// [emitArrowFunctionAsIs.ts] +var arrow1 = a => { }; +var arrow2 = (a) => { }; + +var arrow3 = (a, b) => { }; + +//// [emitArrowFunctionAsIs.js] +var arrow1 = function (a) { +}; +var arrow2 = function (a) { +}; +var arrow3 = function (a, b) { +}; diff --git a/tests/baselines/reference/emitArrowFunctionAsIs.types b/tests/baselines/reference/emitArrowFunctionAsIs.types new file mode 100644 index 00000000000..1ab5de9724a --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionAsIs.types @@ -0,0 +1,17 @@ +=== tests/cases/conformance/es6/arrowFunction/emitArrowFunctionAsIs.ts === +var arrow1 = a => { }; +>arrow1 : (a: any) => void +>a => { } : (a: any) => void +>a : any + +var arrow2 = (a) => { }; +>arrow2 : (a: any) => void +>(a) => { } : (a: any) => void +>a : any + +var arrow3 = (a, b) => { }; +>arrow3 : (a: any, b: any) => void +>(a, b) => { } : (a: any, b: any) => void +>a : any +>b : any + diff --git a/tests/baselines/reference/emitArrowFunctionAsIsES6.js b/tests/baselines/reference/emitArrowFunctionAsIsES6.js new file mode 100644 index 00000000000..9941434ae10 --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionAsIsES6.js @@ -0,0 +1,13 @@ +//// [emitArrowFunctionAsIsES6.ts] +var arrow1 = a => { }; +var arrow2 = (a) => { }; + +var arrow3 = (a, b) => { }; + +//// [emitArrowFunctionAsIsES6.js] +var arrow1 = a => { +}; +var arrow2 = (a) => { +}; +var arrow3 = (a, b) => { +}; diff --git a/tests/baselines/reference/emitArrowFunctionAsIsES6.types b/tests/baselines/reference/emitArrowFunctionAsIsES6.types new file mode 100644 index 00000000000..6b8c9e54bbe --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionAsIsES6.types @@ -0,0 +1,17 @@ +=== tests/cases/conformance/es6/arrowFunction/emitArrowFunctionAsIsES6.ts === +var arrow1 = a => { }; +>arrow1 : (a: any) => void +>a => { } : (a: any) => void +>a : any + +var arrow2 = (a) => { }; +>arrow2 : (a: any) => void +>(a) => { } : (a: any) => void +>a : any + +var arrow3 = (a, b) => { }; +>arrow3 : (a: any, b: any) => void +>(a, b) => { } : (a: any, b: any) => void +>a : any +>b : any + diff --git a/tests/baselines/reference/emitArrowFunctionES6.js b/tests/baselines/reference/emitArrowFunctionES6.js new file mode 100644 index 00000000000..c518a52f629 --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionES6.js @@ -0,0 +1,25 @@ +//// [emitArrowFunctionES6.ts] +var f1 = () => { } +var f2 = (x: string, y: string) => { } +var f3 = (x: string, y: number, ...rest) => { } +var f4 = (x: string, y: number, z=10) => { } +function foo(func: () => boolean) { } +foo(() => true); +foo(() => { return false; }); + + +//// [emitArrowFunctionES6.js] +var f1 = () => { +}; +var f2 = (x, y) => { +}; +var f3 = (x, y, ...rest) => { +}; +var f4 = (x, y, z = 10) => { +}; +function foo(func) { +} +foo(() => { return true; }); +foo(() => { + return false; +}); diff --git a/tests/baselines/reference/emitArrowFunctionES6.types b/tests/baselines/reference/emitArrowFunctionES6.types new file mode 100644 index 00000000000..1f0c1941bdb --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionES6.types @@ -0,0 +1,39 @@ +=== tests/cases/conformance/es6/arrowFunction/emitArrowFunctionES6.ts === +var f1 = () => { } +>f1 : () => void +>() => { } : () => void + +var f2 = (x: string, y: string) => { } +>f2 : (x: string, y: string) => void +>(x: string, y: string) => { } : (x: string, y: string) => void +>x : string +>y : string + +var f3 = (x: string, y: number, ...rest) => { } +>f3 : (x: string, y: number, ...rest: any[]) => void +>(x: string, y: number, ...rest) => { } : (x: string, y: number, ...rest: any[]) => void +>x : string +>y : number +>rest : any[] + +var f4 = (x: string, y: number, z=10) => { } +>f4 : (x: string, y: number, z?: number) => void +>(x: string, y: number, z=10) => { } : (x: string, y: number, z?: number) => void +>x : string +>y : number +>z : number + +function foo(func: () => boolean) { } +>foo : (func: () => boolean) => void +>func : () => boolean + +foo(() => true); +>foo(() => true) : void +>foo : (func: () => boolean) => void +>() => true : () => boolean + +foo(() => { return false; }); +>foo(() => { return false; }) : void +>foo : (func: () => boolean) => void +>() => { return false; } : () => boolean + diff --git a/tests/baselines/reference/emitArrowFunctionThisCapturing.js b/tests/baselines/reference/emitArrowFunctionThisCapturing.js new file mode 100644 index 00000000000..25d9f7f100b --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionThisCapturing.js @@ -0,0 +1,30 @@ +//// [emitArrowFunctionThisCapturing.ts] +var f1 = () => { + this.age = 10 +}; + +var f2 = (x: string) => { + this.name = x +} + +function foo(func: () => boolean) { } +foo(() => { + this.age = 100; + return true; +}); + + +//// [emitArrowFunctionThisCapturing.js] +var _this = this; +var f1 = function () { + _this.age = 10; +}; +var f2 = function (x) { + _this.name = x; +}; +function foo(func) { +} +foo(function () { + _this.age = 100; + return true; +}); diff --git a/tests/baselines/reference/emitArrowFunctionThisCapturing.types b/tests/baselines/reference/emitArrowFunctionThisCapturing.types new file mode 100644 index 00000000000..433f38e5ecc --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionThisCapturing.types @@ -0,0 +1,44 @@ +=== tests/cases/conformance/es6/arrowFunction/emitArrowFunctionThisCapturing.ts === +var f1 = () => { +>f1 : () => void +>() => { this.age = 10} : () => void + + this.age = 10 +>this.age = 10 : number +>this.age : any +>this : any +>age : any + +}; + +var f2 = (x: string) => { +>f2 : (x: string) => void +>(x: string) => { this.name = x} : (x: string) => void +>x : string + + this.name = x +>this.name = x : string +>this.name : any +>this : any +>name : any +>x : string +} + +function foo(func: () => boolean) { } +>foo : (func: () => boolean) => void +>func : () => boolean + +foo(() => { +>foo(() => { this.age = 100; return true;}) : void +>foo : (func: () => boolean) => void +>() => { this.age = 100; return true;} : () => boolean + + this.age = 100; +>this.age = 100 : number +>this.age : any +>this : any +>age : any + + return true; +}); + diff --git a/tests/baselines/reference/emitArrowFunctionThisCapturingES6.js b/tests/baselines/reference/emitArrowFunctionThisCapturingES6.js new file mode 100644 index 00000000000..bf235bc0eef --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionThisCapturingES6.js @@ -0,0 +1,29 @@ +//// [emitArrowFunctionThisCapturingES6.ts] +var f1 = () => { + this.age = 10 +}; + +var f2 = (x: string) => { + this.name = x +} + +function foo(func: () => boolean){ } +foo(() => { + this.age = 100; + return true; +}); + + +//// [emitArrowFunctionThisCapturingES6.js] +var f1 = () => { + this.age = 10; +}; +var f2 = (x) => { + this.name = x; +}; +function foo(func) { +} +foo(() => { + this.age = 100; + return true; +}); diff --git a/tests/baselines/reference/emitArrowFunctionThisCapturingES6.types b/tests/baselines/reference/emitArrowFunctionThisCapturingES6.types new file mode 100644 index 00000000000..989130ef280 --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionThisCapturingES6.types @@ -0,0 +1,44 @@ +=== tests/cases/conformance/es6/arrowFunction/emitArrowFunctionThisCapturingES6.ts === +var f1 = () => { +>f1 : () => void +>() => { this.age = 10} : () => void + + this.age = 10 +>this.age = 10 : number +>this.age : any +>this : any +>age : any + +}; + +var f2 = (x: string) => { +>f2 : (x: string) => void +>(x: string) => { this.name = x} : (x: string) => void +>x : string + + this.name = x +>this.name = x : string +>this.name : any +>this : any +>name : any +>x : string +} + +function foo(func: () => boolean){ } +>foo : (func: () => boolean) => void +>func : () => boolean + +foo(() => { +>foo(() => { this.age = 100; return true;}) : void +>foo : (func: () => boolean) => void +>() => { this.age = 100; return true;} : () => boolean + + this.age = 100; +>this.age = 100 : number +>this.age : any +>this : any +>age : any + + return true; +}); + diff --git a/tests/baselines/reference/emitArrowFunctionWhenUsingArguments.errors.txt b/tests/baselines/reference/emitArrowFunctionWhenUsingArguments.errors.txt new file mode 100644 index 00000000000..3a0ab0e597c --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionWhenUsingArguments.errors.txt @@ -0,0 +1,46 @@ +tests/cases/conformance/es6/arrowFunction/emitArrowFunctionWhenUsingArguments.ts(2,15): error TS9002: The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression. +tests/cases/conformance/es6/arrowFunction/emitArrowFunctionWhenUsingArguments.ts(7,19): error TS9002: The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression. +tests/cases/conformance/es6/arrowFunction/emitArrowFunctionWhenUsingArguments.ts(13,13): error TS9002: The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression. +tests/cases/conformance/es6/arrowFunction/emitArrowFunctionWhenUsingArguments.ts(19,15): error TS9002: The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression. + + +==== tests/cases/conformance/es6/arrowFunction/emitArrowFunctionWhenUsingArguments.ts (4 errors) ==== + var a = () => { + var arg = arguments[0]; // error + ~~~~~~~~~ +!!! error TS9002: The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression. + } + + var b = function () { + var a = () => { + var arg = arguments[0]; // error + ~~~~~~~~~ +!!! error TS9002: The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression. + } + } + + function baz() { + () => { + var arg = arguments[0]; + ~~~~~~~~~ +!!! error TS9002: The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression. + } + } + + function foo(inputFunc: () => void) { } + foo(() => { + var arg = arguments[0]; // error + ~~~~~~~~~ +!!! error TS9002: The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression. + }); + + function bar() { + var arg = arguments[0]; // no error + } + + + () => { + function foo() { + var arg = arguments[0]; // no error + } + } \ No newline at end of file diff --git a/tests/baselines/reference/emitArrowFunctionWhenUsingArguments.js b/tests/baselines/reference/emitArrowFunctionWhenUsingArguments.js new file mode 100644 index 00000000000..00a4c7aa051 --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionWhenUsingArguments.js @@ -0,0 +1,60 @@ +//// [emitArrowFunctionWhenUsingArguments.ts] +var a = () => { + var arg = arguments[0]; // error +} + +var b = function () { + var a = () => { + var arg = arguments[0]; // error + } +} + +function baz() { + () => { + var arg = arguments[0]; + } +} + +function foo(inputFunc: () => void) { } +foo(() => { + var arg = arguments[0]; // error +}); + +function bar() { + var arg = arguments[0]; // no error +} + + +() => { + function foo() { + var arg = arguments[0]; // no error + } +} + +//// [emitArrowFunctionWhenUsingArguments.js] +var a = () => { + var arg = arguments[0]; // error +}; +var b = function () { + var a = () => { + var arg = arguments[0]; // error + }; +}; +function baz() { + (() => { + var arg = arguments[0]; + }); +} +function foo(inputFunc) { +} +foo(() => { + var arg = arguments[0]; // error +}); +function bar() { + var arg = arguments[0]; // no error +} +(() => { + function foo() { + var arg = arguments[0]; // no error + } +}); diff --git a/tests/baselines/reference/emitArrowFunctionWhenUsingArgumentsES6.errors.txt b/tests/baselines/reference/emitArrowFunctionWhenUsingArgumentsES6.errors.txt new file mode 100644 index 00000000000..f879f11799b --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionWhenUsingArgumentsES6.errors.txt @@ -0,0 +1,46 @@ +tests/cases/conformance/es6/arrowFunction/emitArrowFunctionWhenUsingArgumentsES6.ts(2,15): error TS9002: The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression. +tests/cases/conformance/es6/arrowFunction/emitArrowFunctionWhenUsingArgumentsES6.ts(7,19): error TS9002: The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression. +tests/cases/conformance/es6/arrowFunction/emitArrowFunctionWhenUsingArgumentsES6.ts(13,13): error TS9002: The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression. +tests/cases/conformance/es6/arrowFunction/emitArrowFunctionWhenUsingArgumentsES6.ts(19,15): error TS9002: The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression. + + +==== tests/cases/conformance/es6/arrowFunction/emitArrowFunctionWhenUsingArgumentsES6.ts (4 errors) ==== + var a = () => { + var arg = arguments[0]; // error + ~~~~~~~~~ +!!! error TS9002: The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression. + } + + var b = function () { + var a = () => { + var arg = arguments[0]; // error + ~~~~~~~~~ +!!! error TS9002: The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression. + } + } + + function baz() { + () => { + var arg = arguments[0]; + ~~~~~~~~~ +!!! error TS9002: The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression. + } + } + + function foo(inputFunc: () => void) { } + foo(() => { + var arg = arguments[0]; // error + ~~~~~~~~~ +!!! error TS9002: The 'arguments' object cannot be referenced in an arrow function. Consider using a standard function expression. + }); + + function bar() { + var arg = arguments[0]; // no error + } + + + () => { + function foo() { + var arg = arguments[0]; // no error + } + } \ No newline at end of file diff --git a/tests/baselines/reference/emitArrowFunctionWhenUsingArgumentsES6.js b/tests/baselines/reference/emitArrowFunctionWhenUsingArgumentsES6.js new file mode 100644 index 00000000000..0deacd409df --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionWhenUsingArgumentsES6.js @@ -0,0 +1,60 @@ +//// [emitArrowFunctionWhenUsingArgumentsES6.ts] +var a = () => { + var arg = arguments[0]; // error +} + +var b = function () { + var a = () => { + var arg = arguments[0]; // error + } +} + +function baz() { + () => { + var arg = arguments[0]; + } +} + +function foo(inputFunc: () => void) { } +foo(() => { + var arg = arguments[0]; // error +}); + +function bar() { + var arg = arguments[0]; // no error +} + + +() => { + function foo() { + var arg = arguments[0]; // no error + } +} + +//// [emitArrowFunctionWhenUsingArgumentsES6.js] +var a = () => { + var arg = arguments[0]; // error +}; +var b = function () { + var a = () => { + var arg = arguments[0]; // error + }; +}; +function baz() { + (() => { + var arg = arguments[0]; + }); +} +function foo(inputFunc) { +} +foo(() => { + var arg = arguments[0]; // error +}); +function bar() { + var arg = arguments[0]; // no error +} +(() => { + function foo() { + var arg = arguments[0]; // no error + } +}); diff --git a/tests/baselines/reference/emitArrowFunctionsAsIs.js b/tests/baselines/reference/emitArrowFunctionsAsIs.js new file mode 100644 index 00000000000..ee8347dda3e --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionsAsIs.js @@ -0,0 +1,13 @@ +//// [emitArrowFunctionsAsIs.ts] +var arrow1 = a => { }; +var arrow2 = (a) => { }; + +var arrow3 = (a, b) => { }; + +//// [emitArrowFunctionsAsIs.js] +var arrow1 = function (a) { +}; +var arrow2 = function (a) { +}; +var arrow3 = function (a, b) { +}; diff --git a/tests/baselines/reference/emitArrowFunctionsAsIs.types b/tests/baselines/reference/emitArrowFunctionsAsIs.types new file mode 100644 index 00000000000..36dae7e9c5a --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionsAsIs.types @@ -0,0 +1,17 @@ +=== tests/cases/conformance/es6/arrowFunction/emitArrowFunctionsAsIs.ts === +var arrow1 = a => { }; +>arrow1 : (a: any) => void +>a => { } : (a: any) => void +>a : any + +var arrow2 = (a) => { }; +>arrow2 : (a: any) => void +>(a) => { } : (a: any) => void +>a : any + +var arrow3 = (a, b) => { }; +>arrow3 : (a: any, b: any) => void +>(a, b) => { } : (a: any, b: any) => void +>a : any +>b : any + diff --git a/tests/baselines/reference/emitArrowFunctionsAsIsES6.js b/tests/baselines/reference/emitArrowFunctionsAsIsES6.js new file mode 100644 index 00000000000..021e048ed88 --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionsAsIsES6.js @@ -0,0 +1,13 @@ +//// [emitArrowFunctionsAsIsES6.ts] +var arrow1 = a => { }; +var arrow2 = (a) => { }; + +var arrow3 = (a, b) => { }; + +//// [emitArrowFunctionsAsIsES6.js] +var arrow1 = a => { +}; +var arrow2 = (a) => { +}; +var arrow3 = (a, b) => { +}; diff --git a/tests/baselines/reference/emitArrowFunctionsAsIsES6.types b/tests/baselines/reference/emitArrowFunctionsAsIsES6.types new file mode 100644 index 00000000000..4073355d259 --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionsAsIsES6.types @@ -0,0 +1,17 @@ +=== tests/cases/conformance/es6/arrowFunction/emitArrowFunctionsAsIsES6.ts === +var arrow1 = a => { }; +>arrow1 : (a: any) => void +>a => { } : (a: any) => void +>a : any + +var arrow2 = (a) => { }; +>arrow2 : (a: any) => void +>(a) => { } : (a: any) => void +>a : any + +var arrow3 = (a, b) => { }; +>arrow3 : (a: any, b: any) => void +>(a, b) => { } : (a: any, b: any) => void +>a : any +>b : any + diff --git a/tests/baselines/reference/emitDefaultParametersFunctionExpressionES6.js b/tests/baselines/reference/emitDefaultParametersFunctionExpressionES6.js index eabb0e1e344..5a49a200c6b 100644 --- a/tests/baselines/reference/emitDefaultParametersFunctionExpressionES6.js +++ b/tests/baselines/reference/emitDefaultParametersFunctionExpressionES6.js @@ -9,13 +9,13 @@ var y = (function (num = 10, boo = false, ...rest) { })() var z = (function (num: number, boo = false, ...rest) { })(10) //// [emitDefaultParametersFunctionExpressionES6.js] -var lambda1 = function (y = "hello") { +var lambda1 = (y = "hello") => { }; -var lambda2 = function (x, y = "hello") { +var lambda2 = (x, y = "hello") => { }; -var lambda3 = function (x, y = "hello", ...rest) { +var lambda3 = (x, y = "hello", ...rest) => { }; -var lambda4 = function (y = "hello", ...rest) { +var lambda4 = (y = "hello", ...rest) => { }; var x = function (str = "hello", ...rest) { }; diff --git a/tests/baselines/reference/emitRestParametersFunctionExpressionES6.js b/tests/baselines/reference/emitRestParametersFunctionExpressionES6.js index 6c79e4956ae..c7851db5e78 100644 --- a/tests/baselines/reference/emitRestParametersFunctionExpressionES6.js +++ b/tests/baselines/reference/emitRestParametersFunctionExpressionES6.js @@ -5,9 +5,9 @@ var funcExp2 = function (...rest) { } var funcExp3 = (function (...rest) { })() //// [emitRestParametersFunctionExpressionES6.js] -var funcExp = function (...rest) { +var funcExp = (...rest) => { }; -var funcExp1 = function (X, ...rest) { +var funcExp1 = (X, ...rest) => { }; var funcExp2 = function (...rest) { }; diff --git a/tests/baselines/reference/emptyGenericParamList.js b/tests/baselines/reference/emptyGenericParamList.js new file mode 100644 index 00000000000..c5d01778f2d --- /dev/null +++ b/tests/baselines/reference/emptyGenericParamList.js @@ -0,0 +1,11 @@ +//// [emptyGenericParamList.ts] +class I {} +var x: I<>; + +//// [emptyGenericParamList.js] +var I = (function () { + function I() { + } + return I; +})(); +var x; diff --git a/tests/baselines/reference/emptyMemberAccess.js b/tests/baselines/reference/emptyMemberAccess.js new file mode 100644 index 00000000000..c0fc6064b5d --- /dev/null +++ b/tests/baselines/reference/emptyMemberAccess.js @@ -0,0 +1,12 @@ +//// [emptyMemberAccess.ts] +function getObj() { + + ().toString(); + +} + + +//// [emptyMemberAccess.js] +function getObj() { + ().toString(); +} diff --git a/tests/baselines/reference/emptyTypeArgumentList.js b/tests/baselines/reference/emptyTypeArgumentList.js new file mode 100644 index 00000000000..91fce396289 --- /dev/null +++ b/tests/baselines/reference/emptyTypeArgumentList.js @@ -0,0 +1,8 @@ +//// [emptyTypeArgumentList.ts] +function foo() { } +foo<>(); + +//// [emptyTypeArgumentList.js] +function foo() { +} +foo(); diff --git a/tests/baselines/reference/emptyTypeArgumentListWithNew.js b/tests/baselines/reference/emptyTypeArgumentListWithNew.js new file mode 100644 index 00000000000..d51c4f630a6 --- /dev/null +++ b/tests/baselines/reference/emptyTypeArgumentListWithNew.js @@ -0,0 +1,11 @@ +//// [emptyTypeArgumentListWithNew.ts] +class foo { } +new foo<>(); + +//// [emptyTypeArgumentListWithNew.js] +var foo = (function () { + function foo() { + } + return foo; +})(); +new foo(); diff --git a/tests/baselines/reference/enumConflictsWithGlobalIdentifier.js b/tests/baselines/reference/enumConflictsWithGlobalIdentifier.js new file mode 100644 index 00000000000..67d9a020bb6 --- /dev/null +++ b/tests/baselines/reference/enumConflictsWithGlobalIdentifier.js @@ -0,0 +1,15 @@ +//// [enumConflictsWithGlobalIdentifier.ts] +enum Position { + IgnoreRulesSpecific = 0, +} +var x = IgnoreRulesSpecific. +var y = Position.IgnoreRulesSpecific; + + +//// [enumConflictsWithGlobalIdentifier.js] +var Position; +(function (Position) { + Position[Position["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; +})(Position || (Position = {})); +var x = IgnoreRulesSpecific.; +var y = 0 /* IgnoreRulesSpecific */; diff --git a/tests/baselines/reference/enumConstantMembers.js b/tests/baselines/reference/enumConstantMembers.js new file mode 100644 index 00000000000..f58c7d253af --- /dev/null +++ b/tests/baselines/reference/enumConstantMembers.js @@ -0,0 +1,38 @@ +//// [enumConstantMembers.ts] +// Constant members allow negatives, but not decimals. Also hex literals are allowed +enum E1 { + a = 1, + b +} +enum E2 { + a = - 1, + b +} +enum E3 { + a = 0.1, + b // Error because 0.1 is not a constant +} + +declare enum E4 { + a = 1, + b = -1, + c = 0.1 // Not a constant +} + +//// [enumConstantMembers.js] +// Constant members allow negatives, but not decimals. Also hex literals are allowed +var E1; +(function (E1) { + E1[E1["a"] = 1] = "a"; + E1[E1["b"] = 2] = "b"; +})(E1 || (E1 = {})); +var E2; +(function (E2) { + E2[E2["a"] = -1] = "a"; + E2[E2["b"] = 0] = "b"; +})(E2 || (E2 = {})); +var E3; +(function (E3) { + E3[E3["a"] = 0.1] = "a"; + E3[E3["b"] = 1.1] = "b"; // Error because 0.1 is not a constant +})(E3 || (E3 = {})); diff --git a/tests/baselines/reference/enumInitializersWithExponents.js b/tests/baselines/reference/enumInitializersWithExponents.js new file mode 100644 index 00000000000..b4dd38e32c2 --- /dev/null +++ b/tests/baselines/reference/enumInitializersWithExponents.js @@ -0,0 +1,12 @@ +//// [enumInitializersWithExponents.ts] +// Must be integer literals. +declare enum E { + a = 1e3, // ok + b = 1e25, // ok + c = 1e-3, // error + d = 1e-9, // error + e = 1e0, // ok + f = 1e+25 // ok +} + +//// [enumInitializersWithExponents.js] diff --git a/tests/baselines/reference/enumMemberResolution.js b/tests/baselines/reference/enumMemberResolution.js new file mode 100644 index 00000000000..e1d79ebeb92 --- /dev/null +++ b/tests/baselines/reference/enumMemberResolution.js @@ -0,0 +1,17 @@ +//// [enumMemberResolution.ts] +enum Position2 { + IgnoreRulesSpecific = 0 +} +var x = IgnoreRulesSpecific. // error +var y = 1; +var z = Position2.IgnoreRulesSpecific; // no error + + +//// [enumMemberResolution.js] +var Position2; +(function (Position2) { + Position2[Position2["IgnoreRulesSpecific"] = 0] = "IgnoreRulesSpecific"; +})(Position2 || (Position2 = {})); +var x = IgnoreRulesSpecific.; // error +var y = 1; +var z = 0 /* IgnoreRulesSpecific */; // no error diff --git a/tests/baselines/reference/enumWithParenthesizedInitializer1.js b/tests/baselines/reference/enumWithParenthesizedInitializer1.js new file mode 100644 index 00000000000..0c125b3d8b2 --- /dev/null +++ b/tests/baselines/reference/enumWithParenthesizedInitializer1.js @@ -0,0 +1,10 @@ +//// [enumWithParenthesizedInitializer1.ts] +enum E { + e = -(3 +} + +//// [enumWithParenthesizedInitializer1.js] +var E; +(function (E) { + E[E["e"] = -(3)] = "e"; +})(E || (E = {})); diff --git a/tests/baselines/reference/enumWithoutInitializerAfterComputedMember.js b/tests/baselines/reference/enumWithoutInitializerAfterComputedMember.js new file mode 100644 index 00000000000..ef9192c1c90 --- /dev/null +++ b/tests/baselines/reference/enumWithoutInitializerAfterComputedMember.js @@ -0,0 +1,14 @@ +//// [enumWithoutInitializerAfterComputedMember.ts] +enum E { + a, + b = a, + c +} + +//// [enumWithoutInitializerAfterComputedMember.js] +var E; +(function (E) { + E[E["a"] = 0] = "a"; + E[E["b"] = E.a] = "b"; + E[E["c"] = undefined] = "c"; +})(E || (E = {})); diff --git a/tests/baselines/reference/errorSuperCalls.js b/tests/baselines/reference/errorSuperCalls.js new file mode 100644 index 00000000000..4e0f84656fd --- /dev/null +++ b/tests/baselines/reference/errorSuperCalls.js @@ -0,0 +1,170 @@ +//// [errorSuperCalls.ts] +//super call in class constructor with no base type +class NoBase { + constructor() { + super(); + } + + //super call in class member function with no base type + fn() { + super(); + } + + //super call in class accessor (get and set) with no base type + get foo() { + super(); + return null; + } + set foo(v) { + super(); + } + + //super call in class member initializer with no base type + p = super(); + + //super call in static class member function with no base type + static fn() { + super(); + } + + //super call in static class member initializer with no base type + static k = super(); + + //super call in static class accessor (get and set) with no base type + static get q() { + super(); + return null; + } + static set q(n) { + super(); + } +} + +class Base { private n: T; } +class Derived extends Base { + //super call with type arguments + constructor() { + super(); + super(); + } +} + + +class OtherBase { + private n: string; +} + +class OtherDerived extends OtherBase { + //super call in class member initializer of derived type + t = super(); + + fn() { + //super call in class member function of derived type + super(); + } + + //super call in class accessor (get and set) of derived type + get foo() { + super(); + return null; + } + set foo(n) { + super(); + } +} + + +//// [errorSuperCalls.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +//super call in class constructor with no base type +var NoBase = (function () { + function NoBase() { + //super call in class member initializer with no base type + this.p = _super.call(this); + _super.call(this); + } + //super call in class member function with no base type + NoBase.prototype.fn = function () { + _super.call(this); + }; + Object.defineProperty(NoBase.prototype, "foo", { + //super call in class accessor (get and set) with no base type + get: function () { + _super.call(this); + return null; + }, + set: function (v) { + _super.call(this); + }, + enumerable: true, + configurable: true + }); + //super call in static class member function with no base type + NoBase.fn = function () { + _super.call(this); + }; + Object.defineProperty(NoBase, "q", { + //super call in static class accessor (get and set) with no base type + get: function () { + _super.call(this); + return null; + }, + set: function (n) { + _super.call(this); + }, + enumerable: true, + configurable: true + }); + //super call in static class member initializer with no base type + NoBase.k = _super.call(this); + return NoBase; +})(); +var Base = (function () { + function Base() { + } + return Base; +})(); +var Derived = (function (_super) { + __extends(Derived, _super); + //super call with type arguments + function Derived() { + _super.prototype..call(this); + _super.call(this); + } + return Derived; +})(Base); +var OtherBase = (function () { + function OtherBase() { + } + return OtherBase; +})(); +var OtherDerived = (function (_super) { + __extends(OtherDerived, _super); + function OtherDerived() { + _super.apply(this, arguments); + //super call in class member initializer of derived type + this.t = _super.call(this); + } + OtherDerived.prototype.fn = function () { + //super call in class member function of derived type + _super.call(this); + }; + Object.defineProperty(OtherDerived.prototype, "foo", { + //super call in class accessor (get and set) of derived type + get: function () { + _super.call(this); + return null; + }, + set: function (n) { + _super.call(this); + }, + enumerable: true, + configurable: true + }); + return OtherDerived; +})(OtherBase); diff --git a/tests/baselines/reference/errorSuperPropertyAccess.js b/tests/baselines/reference/errorSuperPropertyAccess.js new file mode 100644 index 00000000000..26c66a1222c --- /dev/null +++ b/tests/baselines/reference/errorSuperPropertyAccess.js @@ -0,0 +1,280 @@ +//// [errorSuperPropertyAccess.ts] +//super property access in constructor of class with no base type +//super property access in instance member function of class with no base type +//super property access in instance member accessor(get and set) of class with no base type +class NoBase { + constructor() { + var a = super.prototype; + var b = super.hasOwnProperty(''); + } + + fn() { + var a = super.prototype; + var b = super.hasOwnProperty(''); + } + + m = super.prototype; + n = super.hasOwnProperty(''); + + //super static property access in static member function of class with no base type + //super static property access in static member accessor(get and set) of class with no base type + public static static1() { + super.hasOwnProperty(''); + } + + public static get static2() { + super.hasOwnProperty(''); + return ''; + } + + public static set static2(n) { + super.hasOwnProperty(''); + } +} + +class SomeBase { + private privateFunc() { } + private privateMember = 0; + + public publicFunc() { } + public publicMember = 0; + + private static privateStaticFunc() { } + private static privateStaticMember = 0; + + public static publicStaticFunc() { } + public static publicStaticMember = 0; + +} + + +//super.publicInstanceMemberNotFunction in constructor of derived class +//super.publicInstanceMemberNotFunction in instance member function of derived class +//super.publicInstanceMemberNotFunction in instance member accessor(get and set) of derived class +//super property access only available with typed this +class SomeDerived1 extends SomeBase { + constructor() { + super(); + super.publicMember = 1; + } + + fn() { + var x = super.publicMember; + } + + get a() { + var x = super.publicMember; + return undefined; + } + set a(n) { + n = super.publicMember; + } + fn2() { + function inner() { + super.publicFunc(); + } + var x = { + test: function () { return super.publicFunc(); } + } + } +} + +//super.privateProperty in constructor of derived class +//super.privateProperty in instance member function of derived class +//super.privateProperty in instance member accessor(get and set) of derived class +class SomeDerived2 extends SomeBase { + constructor() { + super(); + super.privateMember = 1; + } + + fn() { + var x = super.privateMember; + } + + get a() { + var x = super.privateMember; + return undefined; + } + set a(n) { + n = super.privateMember; + } +} + +//super.publicStaticMemberNotFunction in static member function of derived class +//super.publicStaticMemberNotFunction in static member accessor(get and set) of derived class +//super.privateStaticProperty in static member function of derived class +//super.privateStaticProperty in static member accessor(get and set) of derived class +class SomeDerived3 extends SomeBase { + static fn() { + super.publicStaticMember = 3; + super.privateStaticMember = 3; + super.privateStaticFunc(); + } + static get a() { + super.publicStaticMember = 3; + super.privateStaticMember = 3; + super.privateStaticFunc(); + return ''; + } + static set a(n) { + super.publicStaticMember = 3; + super.privateStaticMember = 3; + super.privateStaticFunc(); + } +} + +// In object literal +var obj = { n: super.wat, p: super.foo() }; + + +//// [errorSuperPropertyAccess.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +//super property access in constructor of class with no base type +//super property access in instance member function of class with no base type +//super property access in instance member accessor(get and set) of class with no base type +var NoBase = (function () { + function NoBase() { + this.m = super.prototype; + this.n = super.hasOwnProperty.call(this, ''); + var a = super.prototype; + var b = super.hasOwnProperty.call(this, ''); + } + NoBase.prototype.fn = function () { + var a = super.prototype; + var b = super.hasOwnProperty.call(this, ''); + }; + //super static property access in static member function of class with no base type + //super static property access in static member accessor(get and set) of class with no base type + NoBase.static1 = function () { + super.hasOwnProperty.call(this, ''); + }; + Object.defineProperty(NoBase, "static2", { + get: function () { + super.hasOwnProperty.call(this, ''); + return ''; + }, + set: function (n) { + super.hasOwnProperty.call(this, ''); + }, + enumerable: true, + configurable: true + }); + return NoBase; +})(); +var SomeBase = (function () { + function SomeBase() { + this.privateMember = 0; + this.publicMember = 0; + } + SomeBase.prototype.privateFunc = function () { + }; + SomeBase.prototype.publicFunc = function () { + }; + SomeBase.privateStaticFunc = function () { + }; + SomeBase.publicStaticFunc = function () { + }; + SomeBase.privateStaticMember = 0; + SomeBase.publicStaticMember = 0; + return SomeBase; +})(); +//super.publicInstanceMemberNotFunction in constructor of derived class +//super.publicInstanceMemberNotFunction in instance member function of derived class +//super.publicInstanceMemberNotFunction in instance member accessor(get and set) of derived class +//super property access only available with typed this +var SomeDerived1 = (function (_super) { + __extends(SomeDerived1, _super); + function SomeDerived1() { + _super.call(this); + _super.prototype.publicMember = 1; + } + SomeDerived1.prototype.fn = function () { + var x = _super.prototype.publicMember; + }; + Object.defineProperty(SomeDerived1.prototype, "a", { + get: function () { + var x = _super.prototype.publicMember; + return undefined; + }, + set: function (n) { + n = _super.prototype.publicMember; + }, + enumerable: true, + configurable: true + }); + SomeDerived1.prototype.fn2 = function () { + function inner() { + super.publicFunc.call(this); + } + var x = { + test: function () { + return super.publicFunc.call(this); + } + }; + }; + return SomeDerived1; +})(SomeBase); +//super.privateProperty in constructor of derived class +//super.privateProperty in instance member function of derived class +//super.privateProperty in instance member accessor(get and set) of derived class +var SomeDerived2 = (function (_super) { + __extends(SomeDerived2, _super); + function SomeDerived2() { + _super.call(this); + _super.prototype.privateMember = 1; + } + SomeDerived2.prototype.fn = function () { + var x = _super.prototype.privateMember; + }; + Object.defineProperty(SomeDerived2.prototype, "a", { + get: function () { + var x = _super.prototype.privateMember; + return undefined; + }, + set: function (n) { + n = _super.prototype.privateMember; + }, + enumerable: true, + configurable: true + }); + return SomeDerived2; +})(SomeBase); +//super.publicStaticMemberNotFunction in static member function of derived class +//super.publicStaticMemberNotFunction in static member accessor(get and set) of derived class +//super.privateStaticProperty in static member function of derived class +//super.privateStaticProperty in static member accessor(get and set) of derived class +var SomeDerived3 = (function (_super) { + __extends(SomeDerived3, _super); + function SomeDerived3() { + _super.apply(this, arguments); + } + SomeDerived3.fn = function () { + _super.publicStaticMember = 3; + _super.privateStaticMember = 3; + _super.privateStaticFunc.call(this); + }; + Object.defineProperty(SomeDerived3, "a", { + get: function () { + _super.publicStaticMember = 3; + _super.privateStaticMember = 3; + _super.privateStaticFunc.call(this); + return ''; + }, + set: function (n) { + _super.publicStaticMember = 3; + _super.privateStaticMember = 3; + _super.privateStaticFunc.call(this); + }, + enumerable: true, + configurable: true + }); + return SomeDerived3; +})(SomeBase); +// In object literal +var obj = { n: super.wat, p: super.foo.call(this) }; diff --git a/tests/baselines/reference/errorsInGenericTypeReference.js b/tests/baselines/reference/errorsInGenericTypeReference.js new file mode 100644 index 00000000000..6a9f62c5e49 --- /dev/null +++ b/tests/baselines/reference/errorsInGenericTypeReference.js @@ -0,0 +1,158 @@ +//// [errorsInGenericTypeReference.ts] + +interface IFoo { } + +class Foo { } + + +// in call type arguments +class testClass1 { + method(): void { } +} +var tc1 = new testClass1(); +tc1.method<{ x: V }>(); // error: could not find symbol V + + +// in constructor type arguments +class testClass2 { +} +var tc2 = new testClass2<{ x: V }>(); // error: could not find symbol V + + +// in method return type annotation +class testClass3 { + testMethod1(): Foo<{ x: V }> { return null; } // error: could not find symbol V + static testMethod2(): Foo<{ x: V }> { return null } // error: could not find symbol V + set a(value: Foo<{ x: V }>) { } // error: could not find symbol V + property: Foo<{ x: V }>; // error: could not find symbol V +} + + +// in function return type annotation +function testFunction1(): Foo<{ x: V }> { return null; } // error: could not find symbol V + + +// in paramter types +function testFunction2(p: Foo<{ x: V }>) { }// error: could not find symbol V + + +// in var type annotation +var f: Foo<{ x: V }>; // error: could not find symbol V + + +// in constraints +class testClass4 { } // error: could not find symbol V + +interface testClass5> { } // error: could not find symbol V + +class testClass6 { + method(): void { } // error: could not find symbol V +} + +interface testInterface1 { + new (a: M); // error: could not find symbol V +} + + +// in extends clause +class testClass7 extends Foo<{ x: V }> { } // error: could not find symbol V + + +// in implements clause +class testClass8 implements IFoo<{ x: V }> { } // error: could not find symbol V + + +// in signatures +interface testInterface2 { + new (a: Foo<{ x: V }>): Foo<{ x: V }>; //2x: error: could not find symbol V + [x: string]: Foo<{ x: V }>; // error: could not find symbol V + method(a: Foo<{ x: V }>): Foo<{ x: V }>; //2x: error: could not find symbol V + property: Foo<{ x: V }>; // error: could not find symbol V +} + + + +//// [errorsInGenericTypeReference.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var Foo = (function () { + function Foo() { + } + return Foo; +})(); +// in call type arguments +var testClass1 = (function () { + function testClass1() { + } + testClass1.prototype.method = function () { + }; + return testClass1; +})(); +var tc1 = new testClass1(); +tc1.method(); // error: could not find symbol V +// in constructor type arguments +var testClass2 = (function () { + function testClass2() { + } + return testClass2; +})(); +var tc2 = new testClass2(); // error: could not find symbol V +// in method return type annotation +var testClass3 = (function () { + function testClass3() { + } + testClass3.prototype.testMethod1 = function () { + return null; + }; // error: could not find symbol V + testClass3.testMethod2 = function () { + return null; + }; // error: could not find symbol V + Object.defineProperty(testClass3.prototype, "a", { + set: function (value) { + } // error: could not find symbol V + , + enumerable: true, + configurable: true + }); + return testClass3; +})(); +// in function return type annotation +function testFunction1() { + return null; +} // error: could not find symbol V +// in paramter types +function testFunction2(p) { +} // error: could not find symbol V +// in var type annotation +var f; // error: could not find symbol V +// in constraints +var testClass4 = (function () { + function testClass4() { + } + return testClass4; +})(); // error: could not find symbol V +var testClass6 = (function () { + function testClass6() { + } + testClass6.prototype.method = function () { + }; // error: could not find symbol V + return testClass6; +})(); +// in extends clause +var testClass7 = (function (_super) { + __extends(testClass7, _super); + function testClass7() { + _super.apply(this, arguments); + } + return testClass7; +})(Foo); // error: could not find symbol V +// in implements clause +var testClass8 = (function () { + function testClass8() { + } + return testClass8; +})(); // error: could not find symbol V diff --git a/tests/baselines/reference/es6ClassTest.js b/tests/baselines/reference/es6ClassTest.js new file mode 100644 index 00000000000..5fd9f0e9b7f --- /dev/null +++ b/tests/baselines/reference/es6ClassTest.js @@ -0,0 +1,151 @@ +//// [es6ClassTest.ts] +class Bar { + public goo: number; + public prop1(x) { + return x; + } + + constructor (n) { } +} + +// new-style class +class Foo extends Bar { + foo:number; + gar = 0; + zoo:string = "zoo"; + x: any; + + bar() { return 0; } + + private boo(); + private boo(x?) { return x; } + + static statVal = 0; + + constructor(); + constructor(x?, private y?:string, public z?=0) { + super(x); + this.x = x; + this.gar = 5; + } +} + +var f = new Foo(); + +declare module AmbientMod { + export class Provide { + foo:number; + zoo:string; + + constructor(); + + private boo(); + bar(); + } +} + + +//class GetSetMonster { + + +// // attack(target) { +// // WScript.Echo("Attacks " + target); +// // } +// // The contextual keyword "get" followed by an identifier and +// // a curly body defines a getter in the same way that "get" +// // defines one in an object literal. +// // get isAlive() { +// // return this.health > 0; +// // } + +// // Likewise, "set" can be used to define setters. +// set health(value:number) { +// if (value < 0) { +// throw new Error('Health must be non-negative.') +// } +// this.health = value +// } +// get health() { return 0; } + +// constructor(this.name: string, health: number) { +// this.health = 0; +// } +//} + + +//class bar { + +// static fnOverload( ); + +// static fnOverload(foo: string){ } // no error + +// constructor(){}; + +//} + + +//// [es6ClassTest.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var Bar = (function () { + function Bar(n) { + } + Bar.prototype.prop1 = function (x) { + return x; + }; + return Bar; +})(); +// new-style class +var Foo = (function (_super) { + __extends(Foo, _super); + function Foo(x, y, z) { + if (z === void 0) { z = 0; } + _super.call(this, x); + this.y = y; + this.z = z; + this.gar = 0; + this.zoo = "zoo"; + this.x = x; + this.gar = 5; + } + Foo.prototype.bar = function () { + return 0; + }; + Foo.prototype.boo = function (x) { + return x; + }; + Foo.statVal = 0; + return Foo; +})(Bar); +var f = new Foo(); +//class GetSetMonster { +// // attack(target) { +// // WScript.Echo("Attacks " + target); +// // } +// // The contextual keyword "get" followed by an identifier and +// // a curly body defines a getter in the same way that "get" +// // defines one in an object literal. +// // get isAlive() { +// // return this.health > 0; +// // } +// // Likewise, "set" can be used to define setters. +// set health(value:number) { +// if (value < 0) { +// throw new Error('Health must be non-negative.') +// } +// this.health = value +// } +// get health() { return 0; } +// constructor(this.name: string, health: number) { +// this.health = 0; +// } +//} +//class bar { +// static fnOverload( ); +// static fnOverload(foo: string){ } // no error +// constructor(){}; +//} diff --git a/tests/baselines/reference/es6ClassTest2.js b/tests/baselines/reference/es6ClassTest2.js new file mode 100644 index 00000000000..8ef7a2fa379 --- /dev/null +++ b/tests/baselines/reference/es6ClassTest2.js @@ -0,0 +1,326 @@ +//// [es6ClassTest2.ts] +class BasicMonster { + constructor(public name: string, public health: number) { + + } + + attack(target) { + // WScript.Echo("Attacks " + target); + } + + isAlive = true; +} + +var m1 = new BasicMonster("1", 100); +var m2 = new BasicMonster("2", 100); +m1.attack(m2); +m1.health = 0; +console.log((m5.isAlive).toString()); + +class GetSetMonster { + constructor(public name: string, private _health: number) { + + } + + attack(target) { + // WScript.Echo("Attacks " + target); + } + // The contextual keyword "get" followed by an identifier and + // a curly body defines a getter in the same way that "get" + // defines one in an object literal. + get isAlive() { + return this._health > 0; + } + + // Likewise, "set" can be used to define setters. + set health(value: number) { + if (value < 0) { + throw new Error('Health must be non-negative.') + } + this._health = value + } +} + +var m3 = new BasicMonster("1", 100); +var m4 = new BasicMonster("2", 100); +m3.attack(m4); +m3.health = 0; +var x = (m5.isAlive).toString() + +class OverloadedMonster { + constructor(name: string); + constructor(public name: string, public health?: number) { + + } + + attack(); + attack(a: any); + attack(target?) { + //WScript.Echo("Attacks " + target); + } + + isAlive = true; +} + +var m5 = new OverloadedMonster("1"); +var m6 = new OverloadedMonster("2"); +m5.attack(m6); +m5.health = 0; +var y = (m5.isAlive).toString() + +class SplatMonster { + constructor(...args: string[]) { } + roar(name: string, ...args: number[]) { } +} + + +function foo() { return true; } +class PrototypeMonster { + age: number = 1; + name: string; + b = foo(); +} + +class SuperParent { + constructor(a: number) { + + } + + b(b: string) { + + } + + c() { + + } +} + +class SuperChild extends SuperParent { + constructor() { + super(1); + } + + b() { + super.b('str'); + } + + c() { + super.c(); + } +} + +class Statics { + static foo = 1; + static bar: string; + + static baz() { + return ""; + } +} + +var stat = new Statics(); + +interface IFoo { + x: number; + z: string; +} + +class ImplementsInterface implements IFoo { + public x: number; + public z: string; + constructor() { + this.x = 1; + this.z = "foo"; + } +} + +class Visibility { + public foo() { } + private bar() { } + private x: number; + public y: number; + public z: number; + constructor() { + this.x = 1; + this.y = 2; + } +} + +class BaseClassWithConstructor { + constructor(public x: number, public s: string) { } +} + +// used to test codegen +class ChildClassWithoutConstructor extends BaseClassWithConstructor { } + + +var ccwc = new ChildClassWithoutConstructor(1, "s"); + + + +//// [es6ClassTest2.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var BasicMonster = (function () { + function BasicMonster(name, health) { + this.name = name; + this.health = health; + this.isAlive = true; + } + BasicMonster.prototype.attack = function (target) { + // WScript.Echo("Attacks " + target); + }; + return BasicMonster; +})(); +var m1 = new BasicMonster("1", 100); +var m2 = new BasicMonster("2", 100); +m1.attack(m2); +m1.health = 0; +console.log(m5.isAlive.toString()); +var GetSetMonster = (function () { + function GetSetMonster(name, _health) { + this.name = name; + this._health = _health; + } + GetSetMonster.prototype.attack = function (target) { + // WScript.Echo("Attacks " + target); + }; + Object.defineProperty(GetSetMonster.prototype, "isAlive", { + // The contextual keyword "get" followed by an identifier and + // a curly body defines a getter in the same way that "get" + // defines one in an object literal. + get: function () { + return this._health > 0; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(GetSetMonster.prototype, "health", { + // Likewise, "set" can be used to define setters. + set: function (value) { + if (value < 0) { + throw new Error('Health must be non-negative.'); + } + this._health = value; + }, + enumerable: true, + configurable: true + }); + return GetSetMonster; +})(); +var m3 = new BasicMonster("1", 100); +var m4 = new BasicMonster("2", 100); +m3.attack(m4); +m3.health = 0; +var x = m5.isAlive.toString(); +var OverloadedMonster = (function () { + function OverloadedMonster(name, health) { + this.name = name; + this.health = health; + this.isAlive = true; + } + OverloadedMonster.prototype.attack = function (target) { + //WScript.Echo("Attacks " + target); + }; + return OverloadedMonster; +})(); +var m5 = new OverloadedMonster("1"); +var m6 = new OverloadedMonster("2"); +m5.attack(m6); +m5.health = 0; +var y = m5.isAlive.toString(); +var SplatMonster = (function () { + function SplatMonster() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i - 0] = arguments[_i]; + } + } + SplatMonster.prototype.roar = function (name) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + }; + return SplatMonster; +})(); +function foo() { + return true; +} +var PrototypeMonster = (function () { + function PrototypeMonster() { + this.age = 1; + this.b = foo(); + } + return PrototypeMonster; +})(); +var SuperParent = (function () { + function SuperParent(a) { + } + SuperParent.prototype.b = function (b) { + }; + SuperParent.prototype.c = function () { + }; + return SuperParent; +})(); +var SuperChild = (function (_super) { + __extends(SuperChild, _super); + function SuperChild() { + _super.call(this, 1); + } + SuperChild.prototype.b = function () { + _super.prototype.b.call(this, 'str'); + }; + SuperChild.prototype.c = function () { + _super.prototype.c.call(this); + }; + return SuperChild; +})(SuperParent); +var Statics = (function () { + function Statics() { + } + Statics.baz = function () { + return ""; + }; + Statics.foo = 1; + return Statics; +})(); +var stat = new Statics(); +var ImplementsInterface = (function () { + function ImplementsInterface() { + this.x = 1; + this.z = "foo"; + } + return ImplementsInterface; +})(); +var Visibility = (function () { + function Visibility() { + this.x = 1; + this.y = 2; + } + Visibility.prototype.foo = function () { + }; + Visibility.prototype.bar = function () { + }; + return Visibility; +})(); +var BaseClassWithConstructor = (function () { + function BaseClassWithConstructor(x, s) { + this.x = x; + this.s = s; + } + return BaseClassWithConstructor; +})(); +// used to test codegen +var ChildClassWithoutConstructor = (function (_super) { + __extends(ChildClassWithoutConstructor, _super); + function ChildClassWithoutConstructor() { + _super.apply(this, arguments); + } + return ChildClassWithoutConstructor; +})(BaseClassWithConstructor); +var ccwc = new ChildClassWithoutConstructor(1, "s"); diff --git a/tests/baselines/reference/es6ClassTest3.js b/tests/baselines/reference/es6ClassTest3.js new file mode 100644 index 00000000000..371a983d152 --- /dev/null +++ b/tests/baselines/reference/es6ClassTest3.js @@ -0,0 +1,31 @@ +//// [es6ClassTest3.ts] +module M { + class Visibility { + public foo() { }; + private bar() { }; + private x: number; + public y: number; + public z: number; + + constructor() { + this.x = 1; + this.y = 2; + } + } +} + +//// [es6ClassTest3.js] +var M; +(function (M) { + var Visibility = (function () { + function Visibility() { + this.x = 1; + this.y = 2; + } + Visibility.prototype.foo = function () { + }; + Visibility.prototype.bar = function () { + }; + return Visibility; + })(); +})(M || (M = {})); diff --git a/tests/baselines/reference/es6ClassTest9.js b/tests/baselines/reference/es6ClassTest9.js new file mode 100644 index 00000000000..d45c99d3b04 --- /dev/null +++ b/tests/baselines/reference/es6ClassTest9.js @@ -0,0 +1,9 @@ +//// [es6ClassTest9.ts] +declare class foo(); +function foo() {} + + +//// [es6ClassTest9.js] +(); +function foo() { +} diff --git a/tests/baselines/reference/everyTypeWithAnnotationAndInvalidInitializer.errors.txt b/tests/baselines/reference/everyTypeWithAnnotationAndInvalidInitializer.errors.txt index 4ebb93b10a7..12478442472 100644 --- a/tests/baselines/reference/everyTypeWithAnnotationAndInvalidInitializer.errors.txt +++ b/tests/baselines/reference/everyTypeWithAnnotationAndInvalidInitializer.errors.txt @@ -25,10 +25,10 @@ tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAnd Type 'string' is not assignable to type 'number'. tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAndInvalidInitializer.ts(50,5): error TS2322: Type 'typeof N' is not assignable to type 'typeof M'. Types of property 'A' are incompatible. - Type 'typeof A' is not assignable to type 'typeof A'. - Type 'A' is not assignable to type 'A'. + Type 'typeof N.A' is not assignable to type 'typeof M.A'. + Type 'N.A' is not assignable to type 'M.A'. Property 'name' is missing in type 'A'. -tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAndInvalidInitializer.ts(51,5): error TS2322: Type 'A' is not assignable to type 'A'. +tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAndInvalidInitializer.ts(51,5): error TS2322: Type 'N.A' is not assignable to type 'M.A'. tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAndInvalidInitializer.ts(52,5): error TS2322: Type '(x: number) => boolean' is not assignable to type '(x: number) => string'. Type 'boolean' is not assignable to type 'string'. @@ -124,12 +124,12 @@ tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAnd ~~~~~~~ !!! error TS2322: Type 'typeof N' is not assignable to type 'typeof M'. !!! error TS2322: Types of property 'A' are incompatible. -!!! error TS2322: Type 'typeof A' is not assignable to type 'typeof A'. -!!! error TS2322: Type 'A' is not assignable to type 'A'. +!!! error TS2322: Type 'typeof N.A' is not assignable to type 'typeof M.A'. +!!! error TS2322: Type 'N.A' is not assignable to type 'M.A'. !!! error TS2322: Property 'name' is missing in type 'A'. var aClassInModule: M.A = new N.A(); ~~~~~~~~~~~~~~ -!!! error TS2322: Type 'A' is not assignable to type 'A'. +!!! error TS2322: Type 'N.A' is not assignable to type 'M.A'. var aFunctionInModule: typeof M.F2 = F2; ~~~~~~~~~~~~~~~~~ !!! error TS2322: Type '(x: number) => boolean' is not assignable to type '(x: number) => string'. diff --git a/tests/baselines/reference/exportAlreadySeen.js b/tests/baselines/reference/exportAlreadySeen.js new file mode 100644 index 00000000000..e18c0bbf7f6 --- /dev/null +++ b/tests/baselines/reference/exportAlreadySeen.js @@ -0,0 +1,38 @@ +//// [exportAlreadySeen.ts] +module M { + export export var x = 1; + export export function f() { } + + export export module N { + export export class C { } + export export interface I { } + } +} + +declare module A { + export export var x; + export export function f() + + export export module N { + export export class C { } + export export interface I { } + } +} + +//// [exportAlreadySeen.js] +var M; +(function (M) { + M.x = 1; + function f() { + } + M.f = f; + var N; + (function (N) { + var C = (function () { + function C() { + } + return C; + })(); + N.C = C; + })(N = M.N || (M.N = {})); +})(M || (M = {})); diff --git a/tests/baselines/reference/exportAssignDottedName.js b/tests/baselines/reference/exportAssignDottedName.js new file mode 100644 index 00000000000..48b06273c17 --- /dev/null +++ b/tests/baselines/reference/exportAssignDottedName.js @@ -0,0 +1,21 @@ +//// [tests/cases/conformance/externalModules/exportAssignDottedName.ts] //// + +//// [foo1.ts] +export function x(){ + return true; +} + +//// [foo2.ts] +import foo1 = require('./foo1'); +export = foo1.x; // Error, export assignment must be identifier only + + +//// [foo1.js] +function x() { + return true; +} +exports.x = x; +//// [foo2.js] +var foo1 = require('./foo1'); +x; // Error, export assignment must be identifier only +module.exports = foo1; diff --git a/tests/baselines/reference/exportAssignImportedIdentifier.js b/tests/baselines/reference/exportAssignImportedIdentifier.js new file mode 100644 index 00000000000..b371e4db5e0 --- /dev/null +++ b/tests/baselines/reference/exportAssignImportedIdentifier.js @@ -0,0 +1,28 @@ +//// [tests/cases/conformance/externalModules/exportAssignImportedIdentifier.ts] //// + +//// [foo1.ts] +export function x(){ + return true; +} + +//// [foo2.ts] +import foo1 = require('./foo1'); +var x = foo1.x; +export = x; + +//// [foo3.ts] +import foo2 = require('./foo2'); +var x = foo2(); // should be boolean + +//// [foo1.js] +function x() { + return true; +} +exports.x = x; +//// [foo2.js] +var foo1 = require('./foo1'); +var x = foo1.x; +module.exports = x; +//// [foo3.js] +var foo2 = require('./foo2'); +var x = foo2(); // should be boolean diff --git a/tests/baselines/reference/exportAssignNonIdentifier.js b/tests/baselines/reference/exportAssignNonIdentifier.js new file mode 100644 index 00000000000..aaefca034cb --- /dev/null +++ b/tests/baselines/reference/exportAssignNonIdentifier.js @@ -0,0 +1,52 @@ +//// [tests/cases/conformance/externalModules/exportAssignNonIdentifier.ts] //// + +//// [foo1.ts] +var x = 10; +export = typeof x; // Error + +//// [foo2.ts] +export = "sausages"; // Error + +//// [foo3.ts] +export = class Foo3 {}; // Error + +//// [foo4.ts] +export = true; // Error + +//// [foo5.ts] +export = undefined; // Valid. undefined is an identifier in JavaScript/TypeScript + +//// [foo6.ts] +export = void; // Error + +//// [foo7.ts] +export = Date || String; // Error + +//// [foo8.ts] +export = null; // Error + + + +//// [foo1.js] +var x = 10; +typeof x; // Error +//// [foo2.js] +"sausages"; // Error +//// [foo3.js] +var Foo3 = (function () { + function Foo3() { + } + return Foo3; +})(); +; // Error +//// [foo4.js] +true; // Error +//// [foo5.js] +module.exports = undefined; +//// [foo6.js] +void ; // Error +//// [foo7.js] + || String; // Error +module.exports = Date; +//// [foo8.js] +null; // Error diff --git a/tests/baselines/reference/exportAssignTypes.js b/tests/baselines/reference/exportAssignTypes.js new file mode 100644 index 00000000000..e898f798a7c --- /dev/null +++ b/tests/baselines/reference/exportAssignTypes.js @@ -0,0 +1,93 @@ +//// [tests/cases/conformance/externalModules/exportAssignTypes.ts] //// + +//// [expString.ts] +var x = "test"; +export = x; + +//// [expNumber.ts] +var x = 42; +export = x; + +//// [expBoolean.ts] +var x = true; +export = x; + +//// [expArray.ts] +var x = [1,2]; +export = x; + +//// [expObject.ts] +var x = { answer: 42, when: 1776}; +export = x; + +//// [expAny.ts] +var x; +export = x; + +//// [expGeneric.ts] +function x(a: T){ + return a; +} +export = x; + +//// [consumer.ts] +import iString = require('./expString'); +var v1: string = iString; + +import iNumber = require('./expNumber'); +var v2: number = iNumber; + +import iBoolean = require('./expBoolean'); +var v3: boolean = iBoolean; + +import iArray = require('./expArray'); +var v4: Array = iArray; + +import iObject = require('./expObject'); +var v5: Object = iObject; + +import iAny = require('./expAny'); +var v6 = iAny; + +import iGeneric = require('./expGeneric'); +var v7: {(p1: x): x} = iGeneric; + + +//// [expString.js] +var x = "test"; +module.exports = x; +//// [expNumber.js] +var x = 42; +module.exports = x; +//// [expBoolean.js] +var x = true; +module.exports = x; +//// [expArray.js] +var x = [1, 2]; +module.exports = x; +//// [expObject.js] +var x = { answer: 42, when: 1776 }; +module.exports = x; +//// [expAny.js] +var x; +module.exports = x; +//// [expGeneric.js] +function x(a) { + return a; +} +module.exports = x; +//// [consumer.js] +var iString = require('./expString'); +var v1 = iString; +var iNumber = require('./expNumber'); +var v2 = iNumber; +var iBoolean = require('./expBoolean'); +var v3 = iBoolean; +var iArray = require('./expArray'); +var v4 = iArray; +var iObject = require('./expObject'); +var v5 = iObject; +var iAny = require('./expAny'); +var v6 = iAny; +var iGeneric = require('./expGeneric'); +var v7 = iGeneric; diff --git a/tests/baselines/reference/exportAssignmentWithDeclareAndExportModifiers.js b/tests/baselines/reference/exportAssignmentWithDeclareAndExportModifiers.js new file mode 100644 index 00000000000..74396bb951b --- /dev/null +++ b/tests/baselines/reference/exportAssignmentWithDeclareAndExportModifiers.js @@ -0,0 +1,7 @@ +//// [exportAssignmentWithDeclareAndExportModifiers.ts] +var x; +export declare export = x; + +//// [exportAssignmentWithDeclareAndExportModifiers.js] +var x; +module.exports = x; diff --git a/tests/baselines/reference/exportAssignmentWithDeclareModifier.js b/tests/baselines/reference/exportAssignmentWithDeclareModifier.js new file mode 100644 index 00000000000..711538616aa --- /dev/null +++ b/tests/baselines/reference/exportAssignmentWithDeclareModifier.js @@ -0,0 +1,7 @@ +//// [exportAssignmentWithDeclareModifier.ts] +var x; +declare export = x; + +//// [exportAssignmentWithDeclareModifier.js] +var x; +module.exports = x; diff --git a/tests/baselines/reference/exportAssignmentWithExportModifier.js b/tests/baselines/reference/exportAssignmentWithExportModifier.js new file mode 100644 index 00000000000..9d94cc8db75 --- /dev/null +++ b/tests/baselines/reference/exportAssignmentWithExportModifier.js @@ -0,0 +1,7 @@ +//// [exportAssignmentWithExportModifier.ts] +var x; +export export = x; + +//// [exportAssignmentWithExportModifier.js] +var x; +module.exports = x; diff --git a/tests/baselines/reference/exportAssignmentWithoutIdentifier1.js b/tests/baselines/reference/exportAssignmentWithoutIdentifier1.js new file mode 100644 index 00000000000..a90e17d790e --- /dev/null +++ b/tests/baselines/reference/exportAssignmentWithoutIdentifier1.js @@ -0,0 +1,18 @@ +//// [exportAssignmentWithoutIdentifier1.ts] +function Greeter() { + //... +} +Greeter.prototype.greet = function () { + //... +} +export = new Greeter(); + + +//// [exportAssignmentWithoutIdentifier1.js] +function Greeter() { + //... +} +Greeter.prototype.greet = function () { + //... +}; +new Greeter(); diff --git a/tests/baselines/reference/exportDeclareClass1.js b/tests/baselines/reference/exportDeclareClass1.js new file mode 100644 index 00000000000..121db110cc1 --- /dev/null +++ b/tests/baselines/reference/exportDeclareClass1.js @@ -0,0 +1,16 @@ +//// [exportDeclareClass1.ts] + export declare class eaC { + static tF() { }; + static tsF(param:any) { }; + }; + + export declare class eaC2 { + static tF(); + static tsF(param:any); + }; + +//// [exportDeclareClass1.js] +define(["require", "exports"], function (require, exports) { + ; + ; +}); diff --git a/tests/baselines/reference/exportDeclaredModule.js b/tests/baselines/reference/exportDeclaredModule.js new file mode 100644 index 00000000000..7aa75288bff --- /dev/null +++ b/tests/baselines/reference/exportDeclaredModule.js @@ -0,0 +1,19 @@ +//// [tests/cases/conformance/externalModules/exportDeclaredModule.ts] //// + +//// [foo1.ts] + +declare module M1 { + export var a: string; + export function b(): number; +} +export = M1; + +//// [foo2.ts] +import foo1 = require('./foo1'); +var x: number = foo1.b(); + +//// [foo1.js] +module.exports = M1; +//// [foo2.js] +var foo1 = require('./foo1'); +var x = foo1.b(); diff --git a/tests/baselines/reference/exportNonVisibleType.js b/tests/baselines/reference/exportNonVisibleType.js new file mode 100644 index 00000000000..101c356d582 --- /dev/null +++ b/tests/baselines/reference/exportNonVisibleType.js @@ -0,0 +1,54 @@ +//// [tests/cases/conformance/externalModules/exportNonVisibleType.ts] //// + +//// [foo1.ts] +interface I1 { + a: string; + b: number; +} + +var x: I1 = {a: "test", b: 42}; +export = x; // Should fail, I1 not exported. + + +//// [foo2.ts] +interface I1 { + a: string; + b: number; +} + +class C1 { + m1: I1; +} + +export = C1; // Should fail, type I1 of visible member C1.m1 not exported. + +//// [foo3.ts] +interface I1 { + a: string; + b: number; +} + +class C1 { + private m1: I1; +} + +export = C1; // Should work, private type I1 of visible class C1 only used in private member m1. + + +//// [foo1.js] +var x = { a: "test", b: 42 }; +module.exports = x; +//// [foo2.js] +var C1 = (function () { + function C1() { + } + return C1; +})(); +module.exports = C1; +//// [foo3.js] +var C1 = (function () { + function C1() { + } + return C1; +})(); +module.exports = C1; diff --git a/tests/baselines/reference/exportingContainingVisibleType.js b/tests/baselines/reference/exportingContainingVisibleType.js new file mode 100644 index 00000000000..2246a63bc49 --- /dev/null +++ b/tests/baselines/reference/exportingContainingVisibleType.js @@ -0,0 +1,29 @@ +//// [exportingContainingVisibleType.ts] +class Foo { + public get foo() { + var i: Foo; + return i; // Should be fine (previous bug report visibility error). + + } +} + +export var x = 5; + + +//// [exportingContainingVisibleType.js] +define(["require", "exports"], function (require, exports) { + var Foo = (function () { + function Foo() { + } + Object.defineProperty(Foo.prototype, "foo", { + get: function () { + var i; + return i; // Should be fine (previous bug report visibility error). + }, + enumerable: true, + configurable: true + }); + return Foo; + })(); + exports.x = 5; +}); diff --git a/tests/baselines/reference/extendsClauseAlreadySeen.js b/tests/baselines/reference/extendsClauseAlreadySeen.js new file mode 100644 index 00000000000..5c328e39131 --- /dev/null +++ b/tests/baselines/reference/extendsClauseAlreadySeen.js @@ -0,0 +1,29 @@ +//// [extendsClauseAlreadySeen.ts] +class C { + +} +class D extends C extends C { + baz() { } +} + +//// [extendsClauseAlreadySeen.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function () { + function C() { + } + return C; +})(); +var D = (function (_super) { + __extends(D, _super); + function D() { + _super.apply(this, arguments); + } + D.prototype.baz = function () { + }; + return D; +})(C); diff --git a/tests/baselines/reference/extendsClauseAlreadySeen2.js b/tests/baselines/reference/extendsClauseAlreadySeen2.js new file mode 100644 index 00000000000..3f3b7049311 --- /dev/null +++ b/tests/baselines/reference/extendsClauseAlreadySeen2.js @@ -0,0 +1,29 @@ +//// [extendsClauseAlreadySeen2.ts] +class C { + +} +class D extends C extends C { + baz() { } +} + +//// [extendsClauseAlreadySeen2.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function () { + function C() { + } + return C; +})(); +var D = (function (_super) { + __extends(D, _super); + function D() { + _super.apply(this, arguments); + } + D.prototype.baz = function () { + }; + return D; +})(C); diff --git a/tests/baselines/reference/extension.js b/tests/baselines/reference/extension.js new file mode 100644 index 00000000000..40f4af12564 --- /dev/null +++ b/tests/baselines/reference/extension.js @@ -0,0 +1,37 @@ +//// [extension.ts] +interface I { + x; +} + +interface I { + y; +} + +declare module M { + export class C { + public p:number; + } +} + +declare module M { + export extension class C { + public pe:string; + } +} + +var c=new M.C(); +c.pe; +c.p; +var i:I; +i.x; +i.y; + + + +//// [extension.js] +var c = new M.C(); +c.pe; +c.p; +var i; +i.x; +i.y; diff --git a/tests/baselines/reference/externModule.js b/tests/baselines/reference/externModule.js new file mode 100644 index 00000000000..0dc3d8e84cd --- /dev/null +++ b/tests/baselines/reference/externModule.js @@ -0,0 +1,58 @@ +//// [externModule.ts] +declare module { + export class XDate { + public getDay():number; + public getXDate():number; + // etc. + + // Called as a function + // Not supported anymore? public (): string; + + // Called as a constructor + constructor(year: number, month: number); + constructor(year: number, month: number, date: number); + constructor(year: number, month: number, date: number, hours: number); + constructor(year: number, month: number, date: number, hours: number, minutes: number); + constructor(year: number, month: number, date: number, hours: number, minutes: number, seconds: number); + constructor(year: number, month: number, date: number, hours: number, minutes: number, seconds: number, ms: number); + constructor(value: number); + constructor(); + + static parse(string: string): number; + static UTC(year: number, month: number): number; + static UTC(year: number, month: number, date: number): number; + static UTC(year: number, month: number, date: number, hours: number): number; + static UTC(year: number, month: number, date: number, hours: number, minutes: number): number; + static UTC(year: number, month: number, date: number, hours: number, minutes: number, seconds: number): number; + static UTC(year: number, month: number, date: number, hours: number, minutes: number, seconds: number, + ms: number): number; + static now(): number; + } +} + +var d=new XDate(); +d.getDay(); +d=new XDate(1978,2); +d.getXDate(); +var n=XDate.parse("3/2/2004"); +n=XDate.UTC(1964,2,1); + + + +//// [externModule.js] +declare; +module; +{ +} +var XDate = (function () { + function XDate() { + } + return XDate; +})(); +exports.XDate = XDate; +var d = new XDate(); +d.getDay(); +d = new XDate(1978, 2); +d.getXDate(); +var n = XDate.parse("3/2/2004"); +n = XDate.UTC(1964, 2, 1); diff --git a/tests/baselines/reference/externSemantics.js b/tests/baselines/reference/externSemantics.js new file mode 100644 index 00000000000..ed418c66f18 --- /dev/null +++ b/tests/baselines/reference/externSemantics.js @@ -0,0 +1,7 @@ +//// [externSemantics.ts] +declare var x=10; +declare var v; +declare var y:number=3; + + +//// [externSemantics.js] diff --git a/tests/baselines/reference/externSyntax.js b/tests/baselines/reference/externSyntax.js new file mode 100644 index 00000000000..409a9bcecef --- /dev/null +++ b/tests/baselines/reference/externSyntax.js @@ -0,0 +1,17 @@ +//// [externSyntax.ts] +declare var v; +declare module M { + export class D { + public p; + } + export class C { + public f(); + public g() { } // error body + } +} + + + + + +//// [externSyntax.js] diff --git a/tests/baselines/reference/externalModuleWithoutCompilerFlag1.js b/tests/baselines/reference/externalModuleWithoutCompilerFlag1.js new file mode 100644 index 00000000000..b5c939453e6 --- /dev/null +++ b/tests/baselines/reference/externalModuleWithoutCompilerFlag1.js @@ -0,0 +1,7 @@ +//// [externalModuleWithoutCompilerFlag1.ts] + +// Not on line 0 because we want to verify the error is placed in the appropriate location. + export module M { +} + +//// [externalModuleWithoutCompilerFlag1.js] diff --git a/tests/baselines/reference/fatarrowfunctionsErrors.js b/tests/baselines/reference/fatarrowfunctionsErrors.js new file mode 100644 index 00000000000..fd47f60b6a0 --- /dev/null +++ b/tests/baselines/reference/fatarrowfunctionsErrors.js @@ -0,0 +1,47 @@ +//// [fatarrowfunctionsErrors.ts] +foo((...Far:any[])=>{return 0;}) +foo((1)=>{return 0;}); +foo((x?)=>{return x;}) +foo((x=0)=>{return x;}) +var y = x:number => x*x; +false? (() => null): null; + +// missing fatarrow +var x1 = () :void {}; +var x2 = (a:number) :void {}; +var x3 = (a:number) {}; +var x4= (...a: any[]) { }; + +//// [fatarrowfunctionsErrors.js] +foo(function () { + var Far = []; + for (var _i = 0; _i < arguments.length; _i++) { + Far[_i - 0] = arguments[_i]; + } + return 0; +}); +foo((1), { return: 0 }); +; +foo(function (x) { + return x; +}); +foo(function (x) { + if (x === void 0) { x = 0; } + return x; +}); +var y = x, number; +x * x; +false ? (function () { return null; }) : null; +// missing fatarrow +var x1 = function () { +}; +var x2 = function (a) { +}; +var x3 = function (a) { +}; +var x4 = function () { + var a = []; + for (var _i = 0; _i < arguments.length; _i++) { + a[_i - 0] = arguments[_i]; + } +}; diff --git a/tests/baselines/reference/fatarrowfunctionsOptionalArgs.js b/tests/baselines/reference/fatarrowfunctionsOptionalArgs.js new file mode 100644 index 00000000000..0b816cc9e09 --- /dev/null +++ b/tests/baselines/reference/fatarrowfunctionsOptionalArgs.js @@ -0,0 +1,394 @@ +//// [fatarrowfunctionsOptionalArgs.ts] +// valid + +// no params +() => 1; + +// one param, no type +(arg) => 2; + +// one param, no type +arg => 2; + +// one param, no type with default value +(arg = 1) => 3; + +// one param, no type, optional +(arg?) => 4; + +// typed param +(arg: number) => 5; + +// typed param with default value +(arg: number = 0) => 6; + +// optional param +(arg?: number) => 7; + +// var arg param +(...arg: number[]) => 8; + +// multiple arguments +(arg1, arg2) => 12; +(arg1 = 1, arg2 =3) => 13; +(arg1?, arg2?) => 14; +(arg1: number, arg2: number) => 15; +(arg1: number = 0, arg2: number = 1) => 16; +(arg1?: number, arg2?: number) => 17; +(arg1, ...arg2: number[]) => 18; +(arg1, arg2?: number) => 19; + +// in paren +(() => 21); +((arg) => 22); +((arg = 1) => 23); +((arg?) => 24); +((arg: number) => 25); +((arg: number = 0) => 26); +((arg?: number) => 27); +((...arg: number[]) => 28); + +// in multiple paren +(((((arg) => { return 32; })))); + +// in ternary exression +false ? () => 41 : null; +false ? (arg) => 42 : null; +false ? (arg = 1) => 43 : null; +false ? (arg?) => 44 : null; +false ? (arg: number) => 45 : null; +false ? (arg?: number) => 46 : null; +false ? (arg?: number = 0) => 47 : null; +false ? (...arg: number[]) => 48 : null; + +// in ternary exression within paren +false ? (() => 51) : null; +false ? ((arg) => 52) : null; +false ? ((arg = 1) => 53) : null; +false ? ((arg?) => 54) : null; +false ? ((arg: number) => 55) : null; +false ? ((arg?: number) => 56) : null; +false ? ((arg?: number = 0) => 57) : null; +false ? ((...arg: number[]) => 58) : null; + +// ternary exression's else clause +false ? null : () => 61; +false ? null : (arg) => 62; +false ? null : (arg = 1) => 63; +false ? null : (arg?) => 64; +false ? null : (arg: number) => 65; +false ? null : (arg?: number) => 66; +false ? null : (arg?: number = 0) => 67; +false ? null : (...arg: number[]) => 68; + + +// nested ternary expressions +((a?) => { return a; }) ? (b? ) => { return b; } : (c? ) => { return c; }; + +//multiple levels +(a?) => { return a; } ? (b)=>(c)=>81 : (c)=>(d)=>82; + + +// In Expressions +((arg) => 90) instanceof Function; +((arg = 1) => 91) instanceof Function; +((arg? ) => 92) instanceof Function; +((arg: number) => 93) instanceof Function; +((arg: number = 1) => 94) instanceof Function; +((arg?: number) => 95) instanceof Function; +((...arg: number[]) => 96) instanceof Function; + +'' + ((arg) => 100); +((arg) => 0) + '' + ((arg) => 101); +((arg = 1) => 0) + '' + ((arg = 2) => 102); +((arg?) => 0) + '' + ((arg?) => 103); +((arg:number) => 0) + '' + ((arg:number) => 104); +((arg:number = 1) => 0) + '' + ((arg:number = 2) => 105); +((arg?:number = 1) => 0) + '' + ((arg?:number = 2) => 106); +((...arg:number[]) => 0) + '' + ((...arg:number[]) => 107); +((arg1, arg2?) => 0) + '' + ((arg1,arg2?) => 108); +((arg1, ...arg2:number[]) => 0) + '' + ((arg1, ...arg2:number[]) => 108); + + +// Function Parameters +function foo(...arg: any[]) { } + +foo( + (a) => 110, + ((a) => 111), + (a) => { + return 112; + }, + (a? ) => 113, + (a, b? ) => 114, + (a: number) => 115, + (a: number = 0) => 116, + (a = 0) => 117, + (a?: number = 0) => 118, + (...a: number[]) => 119, + (a, b? = 0, ...c: number[]) => 120, + (a) => (b) => (c) => 121, + false? (a) => 0 : (b) => 122 +); + +//// [fatarrowfunctionsOptionalArgs.js] +// valid +// no params +(function () { return 1; }); +// one param, no type +(function (arg) { return 2; }); +// one param, no type +(function (arg) { return 2; }); +// one param, no type with default value +(function (arg) { + if (arg === void 0) { arg = 1; } + return 3; +}); +// one param, no type, optional +(function (arg) { return 4; }); +// typed param +(function (arg) { return 5; }); +// typed param with default value +(function (arg) { + if (arg === void 0) { arg = 0; } + return 6; +}); +// optional param +(function (arg) { return 7; }); +// var arg param +(function () { + var arg = []; + for (var _i = 0; _i < arguments.length; _i++) { + arg[_i - 0] = arguments[_i]; + } + return 8; +}); +// multiple arguments +(function (arg1, arg2) { return 12; }); +(function (arg1, arg2) { + if (arg1 === void 0) { arg1 = 1; } + if (arg2 === void 0) { arg2 = 3; } + return 13; +}); +(function (arg1, arg2) { return 14; }); +(function (arg1, arg2) { return 15; }); +(function (arg1, arg2) { + if (arg1 === void 0) { arg1 = 0; } + if (arg2 === void 0) { arg2 = 1; } + return 16; +}); +(function (arg1, arg2) { return 17; }); +(function (arg1) { + var arg2 = []; + for (var _i = 1; _i < arguments.length; _i++) { + arg2[_i - 1] = arguments[_i]; + } + return 18; +}); +(function (arg1, arg2) { return 19; }); +// in paren +(function () { return 21; }); +(function (arg) { return 22; }); +(function (arg) { + if (arg === void 0) { arg = 1; } + return 23; +}); +(function (arg) { return 24; }); +(function (arg) { return 25; }); +(function (arg) { + if (arg === void 0) { arg = 0; } + return 26; +}); +(function (arg) { return 27; }); +(function () { + var arg = []; + for (var _i = 0; _i < arguments.length; _i++) { + arg[_i - 0] = arguments[_i]; + } + return 28; +}); +// in multiple paren +((((function (arg) { + return 32; +})))); +// in ternary exression +false ? function () { return 41; } : null; +false ? function (arg) { return 42; } : null; +false ? function (arg) { + if (arg === void 0) { arg = 1; } + return 43; +} : null; +false ? function (arg) { return 44; } : null; +false ? function (arg) { return 45; } : null; +false ? function (arg) { return 46; } : null; +false ? function (arg) { + if (arg === void 0) { arg = 0; } + return 47; +} : null; +false ? function () { + var arg = []; + for (var _i = 0; _i < arguments.length; _i++) { + arg[_i - 0] = arguments[_i]; + } + return 48; +} : null; +// in ternary exression within paren +false ? (function () { return 51; }) : null; +false ? (function (arg) { return 52; }) : null; +false ? (function (arg) { + if (arg === void 0) { arg = 1; } + return 53; +}) : null; +false ? (function (arg) { return 54; }) : null; +false ? (function (arg) { return 55; }) : null; +false ? (function (arg) { return 56; }) : null; +false ? (function (arg) { + if (arg === void 0) { arg = 0; } + return 57; +}) : null; +false ? (function () { + var arg = []; + for (var _i = 0; _i < arguments.length; _i++) { + arg[_i - 0] = arguments[_i]; + } + return 58; +}) : null; +// ternary exression's else clause +false ? null : function () { return 61; }; +false ? null : function (arg) { return 62; }; +false ? null : function (arg) { + if (arg === void 0) { arg = 1; } + return 63; +}; +false ? null : function (arg) { return 64; }; +false ? null : function (arg) { return 65; }; +false ? null : function (arg) { return 66; }; +false ? null : function (arg) { + if (arg === void 0) { arg = 0; } + return 67; +}; +false ? null : function () { + var arg = []; + for (var _i = 0; _i < arguments.length; _i++) { + arg[_i - 0] = arguments[_i]; + } + return 68; +}; +// nested ternary expressions +(function (a) { + return a; +}) ? function (b) { + return b; +} : function (c) { + return c; +}; +//multiple levels +(function (a) { + return a; +}); +(function (b) { return function (c) { return 81; }; }); +(function (c) { return function (d) { return 82; }; }); +// In Expressions +(function (arg) { return 90; }) instanceof Function; +(function (arg) { + if (arg === void 0) { arg = 1; } + return 91; +}) instanceof Function; +(function (arg) { return 92; }) instanceof Function; +(function (arg) { return 93; }) instanceof Function; +(function (arg) { + if (arg === void 0) { arg = 1; } + return 94; +}) instanceof Function; +(function (arg) { return 95; }) instanceof Function; +(function () { + var arg = []; + for (var _i = 0; _i < arguments.length; _i++) { + arg[_i - 0] = arguments[_i]; + } + return 96; +}) instanceof Function; +'' + (function (arg) { return 100; }); +(function (arg) { return 0; }) + '' + (function (arg) { return 101; }); +(function (arg) { + if (arg === void 0) { arg = 1; } + return 0; +}) + '' + (function (arg) { + if (arg === void 0) { arg = 2; } + return 102; +}); +(function (arg) { return 0; }) + '' + (function (arg) { return 103; }); +(function (arg) { return 0; }) + '' + (function (arg) { return 104; }); +(function (arg) { + if (arg === void 0) { arg = 1; } + return 0; +}) + '' + (function (arg) { + if (arg === void 0) { arg = 2; } + return 105; +}); +(function (arg) { + if (arg === void 0) { arg = 1; } + return 0; +}) + '' + (function (arg) { + if (arg === void 0) { arg = 2; } + return 106; +}); +(function () { + var arg = []; + for (var _i = 0; _i < arguments.length; _i++) { + arg[_i - 0] = arguments[_i]; + } + return 0; +}) + '' + (function () { + var arg = []; + for (var _i = 0; _i < arguments.length; _i++) { + arg[_i - 0] = arguments[_i]; + } + return 107; +}); +(function (arg1, arg2) { return 0; }) + '' + (function (arg1, arg2) { return 108; }); +(function (arg1) { + var arg2 = []; + for (var _i = 1; _i < arguments.length; _i++) { + arg2[_i - 1] = arguments[_i]; + } + return 0; +}) + '' + (function (arg1) { + var arg2 = []; + for (var _i = 1; _i < arguments.length; _i++) { + arg2[_i - 1] = arguments[_i]; + } + return 108; +}); +// Function Parameters +function foo() { + var arg = []; + for (var _i = 0; _i < arguments.length; _i++) { + arg[_i - 0] = arguments[_i]; + } +} +foo(function (a) { return 110; }, (function (a) { return 111; }), function (a) { + return 112; +}, function (a) { return 113; }, function (a, b) { return 114; }, function (a) { return 115; }, function (a) { + if (a === void 0) { a = 0; } + return 116; +}, function (a) { + if (a === void 0) { a = 0; } + return 117; +}, function (a) { + if (a === void 0) { a = 0; } + return 118; +}, function () { + var a = []; + for (var _i = 0; _i < arguments.length; _i++) { + a[_i - 0] = arguments[_i]; + } + return 119; +}, function (a, b) { + if (b === void 0) { b = 0; } + var c = []; + for (var _i = 2; _i < arguments.length; _i++) { + c[_i - 2] = arguments[_i]; + } + return 120; +}, function (a) { return function (b) { return function (c) { return 121; }; }; }, false ? function (a) { return 0; } : function (b) { return 122; }); diff --git a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors1.js b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors1.js new file mode 100644 index 00000000000..428a085ca56 --- /dev/null +++ b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors1.js @@ -0,0 +1,38 @@ +//// [fatarrowfunctionsOptionalArgsErrors1.ts] +(arg1?, arg2) => 101; +(...arg?) => 102; +(...arg) => 103; +(...arg:number [] = []) => 104; + +// Non optional parameter following an optional one +(arg1 = 1, arg2) => 1; + +//// [fatarrowfunctionsOptionalArgsErrors1.js] +(function (arg1, arg2) { return 101; }); +(function () { + var arg = []; + for (var _i = 0; _i < arguments.length; _i++) { + arg[_i - 0] = arguments[_i]; + } + return 102; +}); +(function () { + var arg = []; + for (var _i = 0; _i < arguments.length; _i++) { + arg[_i - 0] = arguments[_i]; + } + return 103; +}); +(function () { + if (arg === void 0) { arg = []; } + var arg = []; + for (var _i = 0; _i < arguments.length; _i++) { + arg[_i - 0] = arguments[_i]; + } + return 104; +}); +// Non optional parameter following an optional one +(function (arg1, arg2) { + if (arg1 === void 0) { arg1 = 1; } + return 1; +}); diff --git a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors2.js b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors2.js new file mode 100644 index 00000000000..b51003b62df --- /dev/null +++ b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors2.js @@ -0,0 +1,13 @@ +//// [fatarrowfunctionsOptionalArgsErrors2.ts] +var tt1 = (a, (b, c)) => a+b+c; +var tt2 = ((a), b, c) => a+b+c; + +var tt3 = ((a)) => a; + +//// [fatarrowfunctionsOptionalArgsErrors2.js] +var tt1 = (a, (b, c)); +a + b + c; +var tt2 = ((a), b, c); +a + b + c; +var tt3 = ((a)); +a; diff --git a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors3.js b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors3.js new file mode 100644 index 00000000000..665c5244016 --- /dev/null +++ b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors3.js @@ -0,0 +1,12 @@ +//// [fatarrowfunctionsOptionalArgsErrors3.ts] +(...) => 105; + + +//// [fatarrowfunctionsOptionalArgsErrors3.js] +(function () { + var = []; + for (var _i = 0; _i < arguments.length; _i++) { + [_i - 0] = arguments[_i]; + } + return 105; +}); diff --git a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors4.js b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors4.js new file mode 100644 index 00000000000..dfd7e9f74dc --- /dev/null +++ b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors4.js @@ -0,0 +1,69 @@ +//// [fatarrowfunctionsOptionalArgsErrors4.ts] + false ? (arg?: number = 0) => 47 : null; + false ? ((arg?: number = 0) => 57) : null; + false ? null : (arg?: number = 0) => 67; + ((arg?:number = 1) => 0) + '' + ((arg?:number = 2) => 106); + + foo( + (a) => 110, + ((a) => 111), + (a) => { + return 112; + }, + (a? ) => 113, + (a, b? ) => 114, + (a: number) => 115, + (a: number = 0) => 116, + (a = 0) => 117, + (a?: number = 0) => 118, + (...a: number[]) => 119, + (a, b? = 0, ...c: number[]) => 120, + (a) => (b) => (c) => 121, + false? (a) => 0 : (b) => 122 + ); + +//// [fatarrowfunctionsOptionalArgsErrors4.js] +false ? function (arg) { + if (arg === void 0) { arg = 0; } + return 47; +} : null; +false ? (function (arg) { + if (arg === void 0) { arg = 0; } + return 57; +}) : null; +false ? null : function (arg) { + if (arg === void 0) { arg = 0; } + return 67; +}; +(function (arg) { + if (arg === void 0) { arg = 1; } + return 0; +}) + '' + (function (arg) { + if (arg === void 0) { arg = 2; } + return 106; +}); +foo(function (a) { return 110; }, (function (a) { return 111; }), function (a) { + return 112; +}, function (a) { return 113; }, function (a, b) { return 114; }, function (a) { return 115; }, function (a) { + if (a === void 0) { a = 0; } + return 116; +}, function (a) { + if (a === void 0) { a = 0; } + return 117; +}, function (a) { + if (a === void 0) { a = 0; } + return 118; +}, function () { + var a = []; + for (var _i = 0; _i < arguments.length; _i++) { + a[_i - 0] = arguments[_i]; + } + return 119; +}, function (a, b) { + if (b === void 0) { b = 0; } + var c = []; + for (var _i = 2; _i < arguments.length; _i++) { + c[_i - 2] = arguments[_i]; + } + return 120; +}, function (a) { return function (b) { return function (c) { return 121; }; }; }, false ? function (a) { return 0; } : function (b) { return 122; }); diff --git a/tests/baselines/reference/fieldAndGetterWithSameName.js b/tests/baselines/reference/fieldAndGetterWithSameName.js new file mode 100644 index 00000000000..64129ff9365 --- /dev/null +++ b/tests/baselines/reference/fieldAndGetterWithSameName.js @@ -0,0 +1,22 @@ +//// [fieldAndGetterWithSameName.ts] +export class C { + x: number; + get x(): number { return 1; } +} + +//// [fieldAndGetterWithSameName.js] +define(["require", "exports"], function (require, exports) { + var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "x", { + get: function () { + return 1; + }, + enumerable: true, + configurable: true + }); + return C; + })(); + exports.C = C; +}); diff --git a/tests/baselines/reference/for.js b/tests/baselines/reference/for.js new file mode 100644 index 00000000000..a77b68d8b6e --- /dev/null +++ b/tests/baselines/reference/for.js @@ -0,0 +1,56 @@ +//// [for.ts] +for (var i = 0; i < 10; i++) { // ok + var x1 = i; +} + +for (var j: number = 0; j < 10; j++) { // ok + var x2 = j; +} + +for (var k = 0; k < 10;) { // ok + k++; +} + +for (; i < 10;) { // ok + i++; +} + +for (; i > 1; i--) { // ok +} + +for (var l = 0; ; l++) { // ok + if (l > 10) { + break; + } +} + +for (; ;) { // ok +} + +for () { // error +} + +//// [for.js] +for (var i = 0; i < 10; i++) { + var x1 = i; +} +for (var j = 0; j < 10; j++) { + var x2 = j; +} +for (var k = 0; k < 10;) { + k++; +} +for (; i < 10;) { + i++; +} +for (; i > 1; i--) { +} +for (var l = 0;; l++) { + if (l > 10) { + break; + } +} +for (;;) { +} +for (;;) { +} diff --git a/tests/baselines/reference/functionAndPropertyNameConflict.js b/tests/baselines/reference/functionAndPropertyNameConflict.js new file mode 100644 index 00000000000..1368f8241d5 --- /dev/null +++ b/tests/baselines/reference/functionAndPropertyNameConflict.js @@ -0,0 +1,23 @@ +//// [functionAndPropertyNameConflict.ts] +class C65 { + public aaaaa() { } + public get aaaaa() { + return 1; + } +} + +//// [functionAndPropertyNameConflict.js] +var C65 = (function () { + function C65() { + } + C65.prototype.aaaaa = function () { + }; + Object.defineProperty(C65.prototype, "aaaaa", { + get: function () { + return 1; + }, + enumerable: true, + configurable: true + }); + return C65; +})(); diff --git a/tests/baselines/reference/functionOverloadErrorsSyntax.js b/tests/baselines/reference/functionOverloadErrorsSyntax.js new file mode 100644 index 00000000000..3706f4da744 --- /dev/null +++ b/tests/baselines/reference/functionOverloadErrorsSyntax.js @@ -0,0 +1,20 @@ +//// [functionOverloadErrorsSyntax.ts] +//Function overload signature with optional parameter followed by non-optional parameter +function fn4a(x?: number, y: string); +function fn4a() { } + +function fn4b(n: string, x?: number, y: string); +function fn4b() { } + +//Function overload signature with rest param followed by non-optional parameter +function fn5(x: string, ...y: any[], z: string); +function fn5() { } + + +//// [functionOverloadErrorsSyntax.js] +function fn4a() { +} +function fn4b() { +} +function fn5() { +} diff --git a/tests/baselines/reference/functionTypesLackingReturnTypes.js b/tests/baselines/reference/functionTypesLackingReturnTypes.js new file mode 100644 index 00000000000..10b447a838f --- /dev/null +++ b/tests/baselines/reference/functionTypesLackingReturnTypes.js @@ -0,0 +1,25 @@ +//// [functionTypesLackingReturnTypes.ts] + +// Error (no '=>') +function f(x: ()) { +} + +// Error (no '=>') +var g: (param); + +// Okay +var h: { () } + +// Okay +var i: { new () } + +//// [functionTypesLackingReturnTypes.js] +// Error (no '=>') +function f(x) { +} +// Error (no '=>') +var g; +// Okay +var h; +// Okay +var i; diff --git a/tests/baselines/reference/functionsMissingReturnStatementsAndExpressions.js b/tests/baselines/reference/functionsMissingReturnStatementsAndExpressions.js new file mode 100644 index 00000000000..ae8e7d9c918 --- /dev/null +++ b/tests/baselines/reference/functionsMissingReturnStatementsAndExpressions.js @@ -0,0 +1,237 @@ +//// [functionsMissingReturnStatementsAndExpressions.ts] + +function f1(): string { + // errors because there are no return statements +} + +function f2(): string { + // Permissible; returns undefined. + return; +} + +function f3(): string { + return "Okay, because this is a return expression."; +} + +function f4(): void { + // Fine since we are typed void. +} + +function f5(): void { + // Fine since we are typed void. + return; +} + +function f6(): void { + // Fine since we are typed void and return undefined + return undefined; +} + +function f7(): void { + // Fine since we are typed void and return null + return null; +} + +function f8(): void { + // Fine since are typed any. + return; +} + +function f9(): void { + // Fine since we are typed any and return undefined + return undefined; +} + +function f10(): void { + // Fine since we are typed any and return null + return null; +} + +function f11(): string { + // Fine since we consist of a single throw statement. + throw undefined; +} + +function f12(): void { + // Fine since we consist of a single throw statement. + throw undefined; +} + +function f13(): any { + // Fine since we consist of a single throw statement. + throw undefined; +} + +function f14(): number { + // Not fine, since we can *only* consist of a single throw statement + // if no return statements are present but we are annotated. + throw undefined; + throw null; +} + +function f15(): number { + // Fine, since we have a return statement somewhere. + throw undefined; + throw null; + return; +} + + +function f16() { + // Okay; not type annotated. +} + +function f17() { + // Okay; not type annotated. + return; +} + +function f18() { + return "Okay, not type annotated."; +} + + +class C { + public get m1() { + // Errors; get accessors must return a value. + } + + public get m2() { + // Permissible; returns undefined. + return; + } + + public get m3() { + return "Okay, because this is a return expression."; + } + + public get m4() { + // Fine since this consists of a single throw statement. + throw null; + } + + public get m5() { + // Not fine, since we can *only* consist of a single throw statement + // if no return statements are present but we are a get accessor. + throw null; + throw undefined. + } +} + +//// [functionsMissingReturnStatementsAndExpressions.js] +function f1() { + // errors because there are no return statements +} +function f2() { + // Permissible; returns undefined. + return; +} +function f3() { + return "Okay, because this is a return expression."; +} +function f4() { + // Fine since we are typed void. +} +function f5() { + // Fine since we are typed void. + return; +} +function f6() { + // Fine since we are typed void and return undefined + return undefined; +} +function f7() { + // Fine since we are typed void and return null + return null; +} +function f8() { + // Fine since are typed any. + return; +} +function f9() { + // Fine since we are typed any and return undefined + return undefined; +} +function f10() { + // Fine since we are typed any and return null + return null; +} +function f11() { + // Fine since we consist of a single throw statement. + throw undefined; +} +function f12() { + // Fine since we consist of a single throw statement. + throw undefined; +} +function f13() { + // Fine since we consist of a single throw statement. + throw undefined; +} +function f14() { + // Not fine, since we can *only* consist of a single throw statement + // if no return statements are present but we are annotated. + throw undefined; + throw null; +} +function f15() { + // Fine, since we have a return statement somewhere. + throw undefined; + throw null; + return; +} +function f16() { + // Okay; not type annotated. +} +function f17() { + // Okay; not type annotated. + return; +} +function f18() { + return "Okay, not type annotated."; +} +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "m1", { + get: function () { + // Errors; get accessors must return a value. + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(C.prototype, "m2", { + get: function () { + // Permissible; returns undefined. + return; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(C.prototype, "m3", { + get: function () { + return "Okay, because this is a return expression."; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(C.prototype, "m4", { + get: function () { + // Fine since this consists of a single throw statement. + throw null; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(C.prototype, "m5", { + get: function () { + // Not fine, since we can *only* consist of a single throw statement + // if no return statements are present but we are a get accessor. + throw null; + throw undefined.; + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/functionsWithModifiersInBlocks1.js b/tests/baselines/reference/functionsWithModifiersInBlocks1.js new file mode 100644 index 00000000000..1d381bccfe1 --- /dev/null +++ b/tests/baselines/reference/functionsWithModifiersInBlocks1.js @@ -0,0 +1,13 @@ +//// [functionsWithModifiersInBlocks1.ts] +{ + declare function f() { } + export function f() { } + declare export function f() { } +} + +//// [functionsWithModifiersInBlocks1.js] +{ + function f() { + } + exports.f = f; +} diff --git a/tests/baselines/reference/genericArrayExtenstions.js b/tests/baselines/reference/genericArrayExtenstions.js new file mode 100644 index 00000000000..774e512d48f --- /dev/null +++ b/tests/baselines/reference/genericArrayExtenstions.js @@ -0,0 +1,8 @@ +//// [genericArrayExtenstions.ts] +export declare class ObservableArray implements Array { // MS.Entertainment.ObservableArray +concat(...items: U[]): T[]; +concat(...items: T[]): T[]; +} + + +//// [genericArrayExtenstions.js] diff --git a/tests/baselines/reference/genericCallWithoutArgs.js b/tests/baselines/reference/genericCallWithoutArgs.js new file mode 100644 index 00000000000..abf947a7d3b --- /dev/null +++ b/tests/baselines/reference/genericCallWithoutArgs.js @@ -0,0 +1,10 @@ +//// [genericCallWithoutArgs.ts] +function f(x: X, y: Y) { +} + +f. + +//// [genericCallWithoutArgs.js] +function f(x, y) { +} +f(); diff --git a/tests/baselines/reference/genericCallsWithoutParens.js b/tests/baselines/reference/genericCallsWithoutParens.js new file mode 100644 index 00000000000..e51ed55224c --- /dev/null +++ b/tests/baselines/reference/genericCallsWithoutParens.js @@ -0,0 +1,21 @@ +//// [genericCallsWithoutParens.ts] +function f() { } +var r = f; // parse error + +class C { + foo: T; +} +var c = new C; // parse error + + + +//// [genericCallsWithoutParens.js] +function f() { +} +var r = f(); // parse error +var C = (function () { + function C() { + } + return C; +})(); +var c = new C(); // parse error diff --git a/tests/baselines/reference/genericConstructExpressionWithoutArgs.js b/tests/baselines/reference/genericConstructExpressionWithoutArgs.js new file mode 100644 index 00000000000..c3066de2721 --- /dev/null +++ b/tests/baselines/reference/genericConstructExpressionWithoutArgs.js @@ -0,0 +1,26 @@ +//// [genericConstructExpressionWithoutArgs.ts] +class B { } +var b = new B; // no error + +class C { + x: T; +} + +var c = new C // C +var c2 = new C // error, type params are actually part of the arg list so you need both + + +//// [genericConstructExpressionWithoutArgs.js] +var B = (function () { + function B() { + } + return B; +})(); +var b = new B; // no error +var C = (function () { + function C() { + } + return C; +})(); +var c = new C; // C +var c2 = new C(); // error, type params are actually part of the arg list so you need both diff --git a/tests/baselines/reference/genericGetter.js b/tests/baselines/reference/genericGetter.js new file mode 100644 index 00000000000..59425d8c13b --- /dev/null +++ b/tests/baselines/reference/genericGetter.js @@ -0,0 +1,26 @@ +//// [genericGetter.ts] +class C { + data: T; + get x(): T { + return this.data; + } +} + +var c = new C(); +var r: string = c.x; + +//// [genericGetter.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "x", { + get: function () { + return this.data; + }, + enumerable: true, + configurable: true + }); + return C; +})(); +var c = new C(); +var r = c.x; diff --git a/tests/baselines/reference/genericGetter2.js b/tests/baselines/reference/genericGetter2.js new file mode 100644 index 00000000000..9d39ce02d5f --- /dev/null +++ b/tests/baselines/reference/genericGetter2.js @@ -0,0 +1,28 @@ +//// [genericGetter2.ts] +class A { } + +class C { + data: A; + get x(): A { + return this.data; + } +} + +//// [genericGetter2.js] +var A = (function () { + function A() { + } + return A; +})(); +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "x", { + get: function () { + return this.data; + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/genericGetter3.js b/tests/baselines/reference/genericGetter3.js new file mode 100644 index 00000000000..1cb01c6f112 --- /dev/null +++ b/tests/baselines/reference/genericGetter3.js @@ -0,0 +1,33 @@ +//// [genericGetter3.ts] +class A { } + +class C { + data: A; + get x(): A { + return this.data; + } +} + +var c = new C(); +var r: string = c.x; + +//// [genericGetter3.js] +var A = (function () { + function A() { + } + return A; +})(); +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "x", { + get: function () { + return this.data; + }, + enumerable: true, + configurable: true + }); + return C; +})(); +var c = new C(); +var r = c.x; diff --git a/tests/baselines/reference/genericObjectCreationWithoutTypeArgs.js b/tests/baselines/reference/genericObjectCreationWithoutTypeArgs.js new file mode 100644 index 00000000000..75e85283aa9 --- /dev/null +++ b/tests/baselines/reference/genericObjectCreationWithoutTypeArgs.js @@ -0,0 +1,21 @@ +//// [genericObjectCreationWithoutTypeArgs.ts] +class SS{ + +} + +var x1 = new SS(); // OK +var x2 = new SS < number>; // Correctly give error +var x3 = new SS(); // OK +var x4 = new SS; // Should be allowed, but currently give error ('supplied parameters do not match any signature of the call target') + + +//// [genericObjectCreationWithoutTypeArgs.js] +var SS = (function () { + function SS() { + } + return SS; +})(); +var x1 = new SS(); // OK +var x2 = new SS(); // Correctly give error +var x3 = new SS(); // OK +var x4 = new SS; // Should be allowed, but currently give error ('supplied parameters do not match any signature of the call target') diff --git a/tests/baselines/reference/genericReturnTypeFromGetter1.js b/tests/baselines/reference/genericReturnTypeFromGetter1.js new file mode 100644 index 00000000000..208b12308e1 --- /dev/null +++ b/tests/baselines/reference/genericReturnTypeFromGetter1.js @@ -0,0 +1,27 @@ +//// [genericReturnTypeFromGetter1.ts] +export interface A { + new (dbSet: DbSet): T; +} +export class DbSet { + _entityType: A; + get entityType() { return this._entityType; } // used to ICE without return type annotation +} + + +//// [genericReturnTypeFromGetter1.js] +define(["require", "exports"], function (require, exports) { + var DbSet = (function () { + function DbSet() { + } + Object.defineProperty(DbSet.prototype, "entityType", { + get: function () { + return this._entityType; + } // used to ICE without return type annotation + , + enumerable: true, + configurable: true + }); + return DbSet; + })(); + exports.DbSet = DbSet; +}); diff --git a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.js b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.js new file mode 100644 index 00000000000..dbda6074830 --- /dev/null +++ b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.js @@ -0,0 +1,103 @@ +//// [genericTypeReferenceWithoutTypeArgument.ts] +// it is an error to use a generic type without type arguments +// all of these are errors + +class C { + foo: T; +} + +var c: C; + +var a: { x: C }; +var b: { (x: C): C }; +var d: { [x: C]: C }; + +var e = (x: C) => { var y: C; return y; } + +function f(x: C): C { var y: C; return y; } + +var g = function f(x: C): C { var y: C; return y; } + +class D extends C { +} + +interface I extends C {} + +module M { + export class E { foo: T } +} + +class D2 extends M.E { } +class D3 { } +interface I2 extends M.E { } + +function h(x: T) { } +function i(x: T) { } + +var j = null; +var k = null; + +//// [genericTypeReferenceWithoutTypeArgument.js] +// it is an error to use a generic type without type arguments +// all of these are errors +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function () { + function C() { + } + return C; +})(); +var c; +var a; +var b; +var d; +var e = function (x) { + var y; + return y; +}; +function f(x) { + var y; + return y; +} +var g = function f(x) { + var y; + return y; +}; +var D = (function (_super) { + __extends(D, _super); + function D() { + _super.apply(this, arguments); + } + return D; +})(C); +var M; +(function (M) { + var E = (function () { + function E() { + } + return E; + })(); + M.E = E; +})(M || (M = {})); +var D2 = (function (_super) { + __extends(D2, _super); + function D2() { + _super.apply(this, arguments); + } + return D2; +})(M.E); +var D3 = (function () { + function D3() { + } + return D3; +})(); +function h(x) { +} +function i(x) { +} +var j = null; +var k = null; diff --git a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument2.js b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument2.js new file mode 100644 index 00000000000..f6a22073702 --- /dev/null +++ b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument2.js @@ -0,0 +1,84 @@ +//// [genericTypeReferenceWithoutTypeArgument2.ts] +// it is an error to use a generic type without type arguments +// all of these are errors + +interface I { + foo: T; +} + +var c: I; + +var a: { x: I }; +var b: { (x: I): I }; +var d: { [x: I]: I }; + +var e = (x: I) => { var y: I; return y; } + +function f(x: I): I { var y: I; return y; } + +var g = function f(x: I): I { var y: I; return y; } + +class D extends I { +} + +interface U extends I {} + +module M { + export interface E { foo: T } +} + +class D2 extends M.C { } +interface D3 { } +interface I2 extends M.C { } + +function h(x: T) { } +function i(x: T) { } + +var j = null; +var k = null; + +//// [genericTypeReferenceWithoutTypeArgument2.js] +// it is an error to use a generic type without type arguments +// all of these are errors +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var c; +var a; +var b; +var d; +var e = function (x) { + var y; + return y; +}; +function f(x) { + var y; + return y; +} +var g = function f(x) { + var y; + return y; +}; +var D = (function (_super) { + __extends(D, _super); + function D() { + _super.apply(this, arguments); + } + return D; +})(I); +var D2 = (function (_super) { + __extends(D2, _super); + function D2() { + _super.apply(this, arguments); + } + return D2; +})(M.C); +function h(x) { +} +function i(x) { +} +var j = null; +var k = null; diff --git a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument3.js b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument3.js new file mode 100644 index 00000000000..a56ec43d7c3 --- /dev/null +++ b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument3.js @@ -0,0 +1,31 @@ +//// [genericTypeReferenceWithoutTypeArgument3.ts] +// it is an error to use a generic type without type arguments +// all of these are errors + +declare class C { + foo: T; +} + +declare var c: C; + +declare var a: { x: C }; +declare var b: { (x: C): C }; +declare var d: { [x: C]: C }; + +declare function f(x: C): C; + +declare class D extends C {} + +declare module M { + export class E { foo: T } +} + +declare class D2 extends M.C { } +declare class D3 { } + +declare function h(x: T); +declare function i(x: T); + +//// [genericTypeReferenceWithoutTypeArgument3.js] +// it is an error to use a generic type without type arguments +// all of these are errors diff --git a/tests/baselines/reference/getAccessorWithImpliedReturnTypeAndFunctionClassMerge.js b/tests/baselines/reference/getAccessorWithImpliedReturnTypeAndFunctionClassMerge.js new file mode 100644 index 00000000000..0211ce55119 --- /dev/null +++ b/tests/baselines/reference/getAccessorWithImpliedReturnTypeAndFunctionClassMerge.js @@ -0,0 +1,47 @@ +//// [getAccessorWithImpliedReturnTypeAndFunctionClassMerge.ts] +declare function _(value: Array): _; +declare function _(value: T): _; + +declare module _ { + export function each( + //list: List, + //iterator: ListIterator, + context?: any): void; + + interface ListIterator { + (value: T, index: number, list: T[]): TResult; + } +} + +declare class _ { + each(iterator: _.ListIterator, context?: any): void; +} + +module MyModule { + export class MyClass { + public get myGetter() { + var obj:any = {}; + + return obj; + } + } +} + +//// [getAccessorWithImpliedReturnTypeAndFunctionClassMerge.js] +var MyModule; +(function (MyModule) { + var MyClass = (function () { + function MyClass() { + } + Object.defineProperty(MyClass.prototype, "myGetter", { + get: function () { + var obj = {}; + return obj; + }, + enumerable: true, + configurable: true + }); + return MyClass; + })(); + MyModule.MyClass = MyClass; +})(MyModule || (MyModule = {})); diff --git a/tests/baselines/reference/getAndSetAsMemberNames.js b/tests/baselines/reference/getAndSetAsMemberNames.js new file mode 100644 index 00000000000..22f99920fb1 --- /dev/null +++ b/tests/baselines/reference/getAndSetAsMemberNames.js @@ -0,0 +1,66 @@ +//// [getAndSetAsMemberNames.ts] +class C1 { + set: boolean; + get = 1; +} +class C2 { + set; +} +class C3 { + set (x) { + return x + 1; + } +} +class C4 { + get: boolean = true; +} +class C5 { + public set: () => boolean = function () { return true; }; + get (): boolean { return true; } + set t(x) { } +} + + +//// [getAndSetAsMemberNames.js] +var C1 = (function () { + function C1() { + this.get = 1; + } + return C1; +})(); +var C2 = (function () { + function C2() { + } + return C2; +})(); +var C3 = (function () { + function C3() { + } + C3.prototype.set = function (x) { + return x + 1; + }; + return C3; +})(); +var C4 = (function () { + function C4() { + this.get = true; + } + return C4; +})(); +var C5 = (function () { + function C5() { + this.set = function () { + return true; + }; + } + C5.prototype.get = function () { + return true; + }; + Object.defineProperty(C5.prototype, "t", { + set: function (x) { + }, + enumerable: true, + configurable: true + }); + return C5; +})(); diff --git a/tests/baselines/reference/getAndSetNotIdenticalType.js b/tests/baselines/reference/getAndSetNotIdenticalType.js new file mode 100644 index 00000000000..7e77fc25d0b --- /dev/null +++ b/tests/baselines/reference/getAndSetNotIdenticalType.js @@ -0,0 +1,23 @@ +//// [getAndSetNotIdenticalType.ts] +class C { + get x(): number { + return 1; + } + set x(v: string) { } +} + +//// [getAndSetNotIdenticalType.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "x", { + get: function () { + return 1; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/getAndSetNotIdenticalType2.js b/tests/baselines/reference/getAndSetNotIdenticalType2.js new file mode 100644 index 00000000000..d73f07ec388 --- /dev/null +++ b/tests/baselines/reference/getAndSetNotIdenticalType2.js @@ -0,0 +1,41 @@ +//// [getAndSetNotIdenticalType2.ts] +class A { foo: T; } + +class C { + data: A; + get x(): A { + return this.data; + } + set x(v: A) { + this.data = v; + } +} + +var x = new C(); +var r = x.x; +x.x = r; + +//// [getAndSetNotIdenticalType2.js] +var A = (function () { + function A() { + } + return A; +})(); +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "x", { + get: function () { + return this.data; + }, + set: function (v) { + this.data = v; + }, + enumerable: true, + configurable: true + }); + return C; +})(); +var x = new C(); +var r = x.x; +x.x = r; diff --git a/tests/baselines/reference/getAndSetNotIdenticalType3.js b/tests/baselines/reference/getAndSetNotIdenticalType3.js new file mode 100644 index 00000000000..2f37a7cbfae --- /dev/null +++ b/tests/baselines/reference/getAndSetNotIdenticalType3.js @@ -0,0 +1,41 @@ +//// [getAndSetNotIdenticalType3.ts] +class A { foo: T; } + +class C { + data: A; + get x(): A { + return this.data; + } + set x(v: A) { + this.data = v; + } +} + +var x = new C(); +var r = x.x; +x.x = r; + +//// [getAndSetNotIdenticalType3.js] +var A = (function () { + function A() { + } + return A; +})(); +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "x", { + get: function () { + return this.data; + }, + set: function (v) { + this.data = v; + }, + enumerable: true, + configurable: true + }); + return C; +})(); +var x = new C(); +var r = x.x; +x.x = r; diff --git a/tests/baselines/reference/getEmitOutputWithEarlySyntacticErrors.baseline b/tests/baselines/reference/getEmitOutputWithEarlySyntacticErrors.baseline index a5d5d2eb9d7..889902d98a2 100644 --- a/tests/baselines/reference/getEmitOutputWithEarlySyntacticErrors.baseline +++ b/tests/baselines/reference/getEmitOutputWithEarlySyntacticErrors.baseline @@ -1,2 +1,5 @@ -EmitOutputStatus : AllOutputGenerationSkipped +EmitOutputStatus : JSGeneratedWithSemanticErrors +Filename : tests/cases/fourslash/inputFile1.js +// File contains early errors. All outputs should be skipped. +const uninitialized_const_error; diff --git a/tests/baselines/reference/getEmitOutputWithSyntacticErrorsForMultipleFiles2.baseline b/tests/baselines/reference/getEmitOutputWithSyntacticErrorsForMultipleFiles2.baseline index a5d5d2eb9d7..e1ed630f2f4 100644 --- a/tests/baselines/reference/getEmitOutputWithSyntacticErrorsForMultipleFiles2.baseline +++ b/tests/baselines/reference/getEmitOutputWithSyntacticErrorsForMultipleFiles2.baseline @@ -1,2 +1,8 @@ -EmitOutputStatus : AllOutputGenerationSkipped +EmitOutputStatus : Succeeded +Filename : out.js +// File to emit, does not contain syntactic errors, but --out is passed +// expected to not generate outputs because of the syntactic errors in the other file. +var noErrors = true; +// File not emitted, and contains syntactic errors +var syntactic = Error; diff --git a/tests/baselines/reference/getEmitOutputWithSyntaxErrors.baseline b/tests/baselines/reference/getEmitOutputWithSyntaxErrors.baseline index a5d5d2eb9d7..3353e1b9b9f 100644 --- a/tests/baselines/reference/getEmitOutputWithSyntaxErrors.baseline +++ b/tests/baselines/reference/getEmitOutputWithSyntaxErrors.baseline @@ -1,2 +1,4 @@ -EmitOutputStatus : AllOutputGenerationSkipped +EmitOutputStatus : Succeeded +Filename : tests/cases/fourslash/inputFile.js +var x; diff --git a/tests/baselines/reference/getsetReturnTypes.js b/tests/baselines/reference/getsetReturnTypes.js new file mode 100644 index 00000000000..55d7e9285b0 --- /dev/null +++ b/tests/baselines/reference/getsetReturnTypes.js @@ -0,0 +1,20 @@ +//// [getsetReturnTypes.ts] +function makePoint(x: number) { + return { + get x() { return x; } + } +}; +var x = makePoint(2).x; +var y: number = makePoint(2).x; + +//// [getsetReturnTypes.js] +function makePoint(x) { + return { + get x() { + return x; + } + }; +} +; +var x = makePoint(2).x; +var y = makePoint(2).x; diff --git a/tests/baselines/reference/getterMissingReturnError.js b/tests/baselines/reference/getterMissingReturnError.js new file mode 100644 index 00000000000..76566d9346e --- /dev/null +++ b/tests/baselines/reference/getterMissingReturnError.js @@ -0,0 +1,20 @@ +//// [getterMissingReturnError.ts] +class test { + public get p2(){ + + } +} + + +//// [getterMissingReturnError.js] +var test = (function () { + function test() { + } + Object.defineProperty(test.prototype, "p2", { + get: function () { + }, + enumerable: true, + configurable: true + }); + return test; +})(); diff --git a/tests/baselines/reference/getterThatThrowsShouldNotNeedReturn.js b/tests/baselines/reference/getterThatThrowsShouldNotNeedReturn.js new file mode 100644 index 00000000000..c48e5c9c6bc --- /dev/null +++ b/tests/baselines/reference/getterThatThrowsShouldNotNeedReturn.js @@ -0,0 +1,27 @@ +//// [getterThatThrowsShouldNotNeedReturn.ts] +class Greeter { + public get greet(): string { + throw ''; // should not raise an error + } + public greeting(): string { + throw ''; // should not raise an error + } +} + + +//// [getterThatThrowsShouldNotNeedReturn.js] +var Greeter = (function () { + function Greeter() { + } + Object.defineProperty(Greeter.prototype, "greet", { + get: function () { + throw ''; // should not raise an error + }, + enumerable: true, + configurable: true + }); + Greeter.prototype.greeting = function () { + throw ''; // should not raise an error + }; + return Greeter; +})(); diff --git a/tests/baselines/reference/gettersAndSetters.js b/tests/baselines/reference/gettersAndSetters.js new file mode 100644 index 00000000000..4c94cbc43db --- /dev/null +++ b/tests/baselines/reference/gettersAndSetters.js @@ -0,0 +1,98 @@ +//// [gettersAndSetters.ts] +// classes +class C { + public fooBack = ""; + static barBack:string = ""; + public bazBack = ""; + + public get Foo() { return this.fooBack;} // ok + public set Foo(foo:string) {this.fooBack = foo;} // ok + + static get Bar() {return C.barBack;} // ok + static set Bar(bar:string) {C.barBack = bar;} // ok + + public get = function() {} // ok + public set = function() {} // ok +} + +var c = new C(); + +var foo = c.Foo; +c.Foo = "foov"; + +var bar = C.Bar; +C.Bar = "barv"; + +var baz = c.Baz; +c.Baz = "bazv"; + +// The Foo accessors' return and param types should be contextually typed to the Foo field +var o : {Foo:number;} = {get Foo() {return 0;}, set Foo(val:number){val}}; // o + +var ofg = o.Foo; +o.Foo = 0; + + +interface I1 { + (n:number):number; +} + +var i:I1 = function (n) {return n;} + + +//// [gettersAndSetters.js] +// classes +var C = (function () { + function C() { + this.fooBack = ""; + this.bazBack = ""; + this.get = function () { + }; // ok + this.set = function () { + }; // ok + } + Object.defineProperty(C.prototype, "Foo", { + get: function () { + return this.fooBack; + } // ok + , + set: function (foo) { + this.fooBack = foo; + } // ok + , + enumerable: true, + configurable: true + }); + Object.defineProperty(C, "Bar", { + get: function () { + return C.barBack; + } // ok + , + set: function (bar) { + C.barBack = bar; + } // ok + , + enumerable: true, + configurable: true + }); + C.barBack = ""; + return C; +})(); +var c = new C(); +var foo = c.Foo; +c.Foo = "foov"; +var bar = C.Bar; +C.Bar = "barv"; +var baz = c.Baz; +c.Baz = "bazv"; +// The Foo accessors' return and param types should be contextually typed to the Foo field +var o = { get Foo() { + return 0; +}, set Foo(val) { + val; +} }; // o +var ofg = o.Foo; +o.Foo = 0; +var i = function (n) { + return n; +}; diff --git a/tests/baselines/reference/gettersAndSettersAccessibility.js b/tests/baselines/reference/gettersAndSettersAccessibility.js new file mode 100644 index 00000000000..9a7564ec96d --- /dev/null +++ b/tests/baselines/reference/gettersAndSettersAccessibility.js @@ -0,0 +1,23 @@ +//// [gettersAndSettersAccessibility.ts] +class C99 { + private get Baz():number { return 0; } + public set Baz(n:number) {} // error - accessors do not agree in visibility +} + + +//// [gettersAndSettersAccessibility.js] +var C99 = (function () { + function C99() { + } + Object.defineProperty(C99.prototype, "Baz", { + get: function () { + return 0; + }, + set: function (n) { + } // error - accessors do not agree in visibility + , + enumerable: true, + configurable: true + }); + return C99; +})(); diff --git a/tests/baselines/reference/gettersAndSettersErrors.js b/tests/baselines/reference/gettersAndSettersErrors.js new file mode 100644 index 00000000000..514a69b2513 --- /dev/null +++ b/tests/baselines/reference/gettersAndSettersErrors.js @@ -0,0 +1,62 @@ +//// [gettersAndSettersErrors.ts] +class C { + public get Foo() { return "foo";} // ok + public set Foo(foo:string) {} // ok + + public Foo = 0; // error - duplicate identifier Foo - confirmed + public get Goo(v:string):string {return null;} // error - getters must not have a parameter + public set Goo(v:string):string {} // error - setters must not specify a return type +} + +class E { + private get Baz():number { return 0; } + public set Baz(n:number) {} // error - accessors do not agree in visibility +} + + + + +//// [gettersAndSettersErrors.js] +var C = (function () { + function C() { + this.Foo = 0; // error - duplicate identifier Foo - confirmed + } + Object.defineProperty(C.prototype, "Foo", { + get: function () { + return "foo"; + } // ok + , + set: function (foo) { + } // ok + , + enumerable: true, + configurable: true + }); + Object.defineProperty(C.prototype, "Goo", { + get: function (v) { + return null; + } // error - getters must not have a parameter + , + set: function (v) { + } // error - setters must not specify a return type + , + enumerable: true, + configurable: true + }); + return C; +})(); +var E = (function () { + function E() { + } + Object.defineProperty(E.prototype, "Baz", { + get: function () { + return 0; + }, + set: function (n) { + } // error - accessors do not agree in visibility + , + enumerable: true, + configurable: true + }); + return E; +})(); diff --git a/tests/baselines/reference/gettersAndSettersTypesAgree.js b/tests/baselines/reference/gettersAndSettersTypesAgree.js new file mode 100644 index 00000000000..48c0ac1500c --- /dev/null +++ b/tests/baselines/reference/gettersAndSettersTypesAgree.js @@ -0,0 +1,48 @@ +//// [gettersAndSettersTypesAgree.ts] +class C { + public get Foo() { return "foo";} // ok + public set Foo(foo) {} // ok - type inferred from getter return statement + + public get Bar() { return "foo";} // ok + public set Bar(bar:string) {} // ok - type must be declared +} + +var o1 = {get Foo(){return 0;}, set Foo(val){}}; // ok - types agree (inference) +var o2 = {get Foo(){return 0;}, set Foo(val:number){}}; // ok - types agree + +//// [gettersAndSettersTypesAgree.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "Foo", { + get: function () { + return "foo"; + } // ok + , + set: function (foo) { + } // ok - type inferred from getter return statement + , + enumerable: true, + configurable: true + }); + Object.defineProperty(C.prototype, "Bar", { + get: function () { + return "foo"; + } // ok + , + set: function (bar) { + } // ok - type must be declared + , + enumerable: true, + configurable: true + }); + return C; +})(); +var o1 = { get Foo() { + return 0; +}, set Foo(val) { +} }; // ok - types agree (inference) +var o2 = { get Foo() { + return 0; +}, set Foo(val) { +} }; // ok - types agree diff --git a/tests/baselines/reference/giant.js b/tests/baselines/reference/giant.js new file mode 100644 index 00000000000..d5f17c9728f --- /dev/null +++ b/tests/baselines/reference/giant.js @@ -0,0 +1,1220 @@ +//// [giant.ts] + +/* + Prefixes + p -> public + r -> private + i -> import + e -> export + a -> ambient + t -> static + s -> set + g -> get + + MAX DEPTH 3 LEVELS +*/ +var V; +function F() { }; +class C { + constructor () { } + public pV; + private rV; + public pF() { } + private rF() { } + public pgF() { } + public get pgF() + public psF(param:any) { } + public set psF(param:any) + private rgF() { } + private get rgF() + private rsF(param:any) { } + private set rsF(param:any) + static tV; + static tF() { } + static tsF(param:any) { } + static set tsF(param:any) + static tgF() { } + static get tgF() +} +interface I { + //Call Signature + (); + (): number; + (p); + (p1: string); + (p2?: string); + (...p3: any[]); + (p4: string, p5?: string); + (p6: string, ...p7: any[]); + //(p8?: string, ...p9: any[]); + //(p10:string, p8?: string, ...p9: any[]); + + //Construct Signature + new (); + new (): number; + new (p: string); + new (p2?: string); + new (...p3: any[]); + new (p4: string, p5?: string); + new (p6: string, ...p7: any[]); + + //Index Signature + [p]; + [p1: string]; + [p2: string, p3: number]; + + //Property Signature + p; + p1?; + p2?: string; + + //Function Signature + p3(); + p4? (); + p5? (): void; + p6(pa1): void; + p7(pa1, pa2): void; + p7? (pa1, pa2): void; +} +module M { + var V; + function F() { }; + class C { + constructor () { } + public pV; + private rV; + public pF() { } + private rF() { } + public pgF() { } + public get pgF() + public psF(param:any) { } + public set psF(param:any) + private rgF() { } + private get rgF() + private rsF(param:any) { } + private set rsF(param:any) + static tV; + static tF() { } + static tsF(param:any) { } + static set tsF(param:any) + static tgF() { } + static get tgF() + } + interface I { + //Call Signature + (); + (): number; + (p); + (p1: string); + (p2?: string); + (...p3: any[]); + (p4: string, p5?: string); + (p6: string, ...p7: any[]); + //(p8?: string, ...p9: any[]); + //(p10:string, p8?: string, ...p9: any[]); + + //Construct Signature + new (); + new (): number; + new (p: string); + new (p2?: string); + new (...p3: any[]); + new (p4: string, p5?: string); + new (p6: string, ...p7: any[]); + + //Index Signature + [p]; + [p1: string]; + [p2: string, p3: number]; + + //Property Signature + p; + p1?; + p2?: string; + + //Function Signature + p3(); + p4? (); + p5? (): void; + p6(pa1): void; + p7(pa1, pa2): void; + p7? (pa1, pa2): void; + } + module M { + var V; + function F() { }; + class C { }; + interface I { }; + module M { }; + export var eV; + export function eF() { }; + export class eC { }; + export interface eI { }; + export module eM { }; + export declare var eaV; + export declare function eaF() { }; + export declare class eaC { }; + export declare module eaM { }; + } + export var eV; + export function eF() { }; + export class eC { + constructor () { } + public pV; + private rV; + public pF() { } + private rF() { } + public pgF() { } + public get pgF() + public psF(param:any) { } + public set psF(param:any) + private rgF() { } + private get rgF() + private rsF(param:any) { } + private set rsF(param:any) + static tV; + static tF() { } + static tsF(param:any) { } + static set tsF(param:any) + static tgF() { } + static get tgF() + } + export interface eI { + //Call Signature + (); + (): number; + (p); + (p1: string); + (p2?: string); + (...p3: any[]); + (p4: string, p5?: string); + (p6: string, ...p7: any[]); + //(p8?: string, ...p9: any[]); + //(p10:string, p8?: string, ...p9: any[]); + + //Construct Signature + new (); + new (): number; + new (p: string); + new (p2?: string); + new (...p3: any[]); + new (p4: string, p5?: string); + new (p6: string, ...p7: any[]); + + //Index Signature + [p]; + [p1: string]; + [p2: string, p3: number]; + + //Property Signature + p; + p1?; + p2?: string; + + //Function Signature + p3(); + p4? (); + p5? (): void; + p6(pa1): void; + p7(pa1, pa2): void; + p7? (pa1, pa2): void; + } + export module eM { + var V; + function F() { }; + class C { }; + interface I { }; + module M { }; + export var eV; + export function eF() { }; + export class eC { }; + export interface eI { }; + export module eM { }; + export declare var eaV; + export declare function eaF() { }; + export declare class eaC { }; + export declare module eaM { }; + } + export declare var eaV; + export declare function eaF() { }; + export declare class eaC { + constructor () { } + public pV; + private rV; + public pF() { } + private rF() { } + public pgF() { } + public get pgF() + public psF(param:any) { } + public set psF(param:any) + private rgF() { } + private get rgF() + private rsF(param:any) { } + private set rsF(param:any) + static tV; + static tF() { } + static tsF(param:any) { } + static set tsF(param:any) + static tgF() { } + static get tgF() + } + export declare module eaM { + var V; + function F() { }; + class C { } + interface I { } + module M { } + export var eV; + export function eF() { }; + export class eC { } + export interface eI { } + export module eM { } + } +} +export var eV; +export function eF() { }; +export class eC { + constructor () { } + public pV; + private rV; + public pF() { } + private rF() { } + public pgF() { } + public get pgF() + public psF(param:any) { } + public set psF(param:any) + private rgF() { } + private get rgF() + private rsF(param:any) { } + private set rsF(param:any) + static tV; + static tF() { } + static tsF(param:any) { } + static set tsF(param:any) + static tgF() { } + static get tgF() +} +export interface eI { + //Call Signature + (); + (): number; + (p); + (p1: string); + (p2?: string); + (...p3: any[]); + (p4: string, p5?: string); + (p6: string, ...p7: any[]); + //(p8?: string, ...p9: any[]); + //(p10:string, p8?: string, ...p9: any[]); + + //Construct Signature + new (); + new (): number; + new (p: string); + new (p2?: string); + new (...p3: any[]); + new (p4: string, p5?: string); + new (p6: string, ...p7: any[]); + + //Index Signature + [p]; + [p1: string]; + [p2: string, p3: number]; + + //Property Signature + p; + p1?; + p2?: string; + + //Function Signature + p3(); + p4? (); + p5? (): void; + p6(pa1): void; + p7(pa1, pa2): void; + p7? (pa1, pa2): void; +} +export module eM { + var V; + function F() { }; + class C { + constructor () { } + public pV; + private rV; + public pF() { } + private rF() { } + public pgF() { } + public get pgF() + public psF(param:any) { } + public set psF(param:any) + private rgF() { } + private get rgF() + private rsF(param:any) { } + private set rsF(param:any) + static tV; + static tF() { } + static tsF(param:any) { } + static set tsF(param:any) + static tgF() { } + static get tgF() + } + interface I { + //Call Signature + (); + (): number; + (p); + (p1: string); + (p2?: string); + (...p3: any[]); + (p4: string, p5?: string); + (p6: string, ...p7: any[]); + //(p8?: string, ...p9: any[]); + //(p10:string, p8?: string, ...p9: any[]); + + //Construct Signature + new (); + new (): number; + new (p: string); + new (p2?: string); + new (...p3: any[]); + new (p4: string, p5?: string); + new (p6: string, ...p7: any[]); + + //Index Signature + [p]; + [p1: string]; + [p2: string, p3: number]; + + //Property Signature + p; + p1?; + p2?: string; + + //Function Signature + p3(); + p4? (); + p5? (): void; + p6(pa1): void; + p7(pa1, pa2): void; + p7? (pa1, pa2): void; + } + module M { + var V; + function F() { }; + class C { }; + interface I { }; + module M { }; + export var eV; + export function eF() { }; + export class eC { }; + export interface eI { }; + export module eM { }; + export declare var eaV; + export declare function eaF() { }; + export declare class eaC { }; + export declare module eaM { }; + } + export var eV; + export function eF() { }; + export class eC { + constructor () { } + public pV; + private rV; + public pF() { } + private rF() { } + public pgF() { } + public get pgF() + public psF(param:any) { } + public set psF(param:any) + private rgF() { } + private get rgF() + private rsF(param:any) { } + private set rsF(param:any) + static tV; + static tF() { } + static tsF(param:any) { } + static set tsF(param:any) + static tgF() { } + static get tgF() + } + export interface eI { + //Call Signature + (); + (): number; + (p); + (p1: string); + (p2?: string); + (...p3: any[]); + (p4: string, p5?: string); + (p6: string, ...p7: any[]); + //(p8?: string, ...p9: any[]); + //(p10:string, p8?: string, ...p9: any[]); + + //Construct Signature + new (); + new (): number; + new (p: string); + new (p2?: string); + new (...p3: any[]); + new (p4: string, p5?: string); + new (p6: string, ...p7: any[]); + + //Index Signature + [p]; + [p1: string]; + [p2: string, p3: number]; + + //Property Signature + p; + p1?; + p2?: string; + + //Function Signature + p3(); + p4? (); + p5? (): void; + p6(pa1): void; + p7(pa1, pa2): void; + p7? (pa1, pa2): void; + } + export module eM { + var V; + function F() { }; + class C { }; + interface I { }; + module M { }; + export var eV; + export function eF() { }; + export class eC { }; + export interface eI { }; + export module eM { }; + export declare var eaV; + export declare function eaF() { }; + export declare class eaC { }; + export declare module eaM { }; + } + export declare var eaV; + export declare function eaF() { }; + export declare class eaC { + constructor () { } + public pV; + private rV; + public pF() { } + private rF() { } + public pgF() { } + public get pgF() + public psF(param:any) { } + public set psF(param:any) + private rgF() { } + private get rgF() + private rsF(param:any) { } + private set rsF(param:any) + static tV; + static tF() { } + static tsF(param:any) { } + static set tsF(param:any) + static tgF() { } + static get tgF() + } + export declare module eaM { + var V; + function F() { }; + class C { } + interface I { } + module M { } + export var eV; + export function eF() { }; + export class eC { } + export interface eI { } + export module eM { } + } +} +export declare var eaV; +export declare function eaF() { }; +export declare class eaC { + constructor () { } + public pV; + private rV; + public pF() { } + private rF() { } + public pgF() { } + public get pgF() + public psF(param:any) { } + public set psF(param:any) + private rgF() { } + private get rgF() + private rsF(param:any) { } + private set rsF(param:any) + static tV; + static tF() { } + static tsF(param:any) { } + static set tsF(param:any) + static tgF() { } + static get tgF() +} +export declare module eaM { + var V; + function F() { }; + class C { + constructor () { } + public pV; + private rV; + public pF() { } + static tV; + static tF() { } + } + interface I { + //Call Signature + (); + (): number; + (p: string); + (p2?: string); + (...p3: any[]); + (p4: string, p5?: string); + (p6: string, ...p7: any[]); + //(p8?: string, ...p9: any[]); + //(p10:string, p8?: string, ...p9: any[]); + + //Construct Signature + new (); + new (): number; + new (p: string); + new (p2?: string); + new (...p3: any[]); + new (p4: string, p5?: string); + new (p6: string, ...p7: any[]); + + //Index Signature + [p]; + [p1: string]; + [p2: string, p3: number]; + + //Property Signature + p; + p1?; + p2?: string; + + //Function Signature + p3(); + p4? (); + p5? (): void; + p6(pa1): void; + p7(pa1, pa2): void; + p7? (pa1, pa2): void; + } + module M { + var V; + function F() { }; + class C { } + interface I { } + module M { } + export var eV; + export function eF() { }; + export class eC { } + export interface eI { } + export module eM { } + export declare var eaV + export declare function eaF() { }; + export declare class eaC { } + export declare module eaM { } + } + export var eV; + export function eF() { }; + export class eC { + constructor () { } + public pV; + private rV; + public pF() { } + static tV + static tF() { } + } + export interface eI { + //Call Signature + (); + (): number; + (p); + (p1: string); + (p2?: string); + (...p3: any[]); + (p4: string, p5?: string); + (p6: string, ...p7: any[]); + //(p8?: string, ...p9: any[]); + //(p10:string, p8?: string, ...p9: any[]); + + //Construct Signature + new (); + new (): number; + new (p: string); + new (p2?: string); + new (...p3: any[]); + new (p4: string, p5?: string); + new (p6: string, ...p7: any[]); + + //Index Signature + [p]; + [p1: string]; + [p2: string, p3: number]; + + //Property Signature + p; + p1?; + p2?: string; + + //Function Signature + p3(); + p4? (); + p5? (): void; + p6(pa1): void; + p7(pa1, pa2): void; + p7? (pa1, pa2): void; + } + export module eM { + var V; + function F() { }; + class C { } + module M { } + export var eV; + export function eF() { }; + export class eC { } + export interface eI { } + export module eM { } + } +} + +//// [giant.js] +define(["require", "exports"], function (require, exports) { + /* + Prefixes + p -> public + r -> private + i -> import + e -> export + a -> ambient + t -> static + s -> set + g -> get + + MAX DEPTH 3 LEVELS + */ + var V; + function F() { + } + ; + var C = (function () { + function C() { + } + C.prototype.pF = function () { + }; + C.prototype.rF = function () { + }; + C.prototype.pgF = function () { + }; + Object.defineProperty(C.prototype, "pgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + C.prototype.psF = function (param) { + }; + Object.defineProperty(C.prototype, "psF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + C.prototype.rgF = function () { + }; + Object.defineProperty(C.prototype, "rgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + C.prototype.rsF = function (param) { + }; + Object.defineProperty(C.prototype, "rsF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + C.tF = function () { + }; + C.tsF = function (param) { + }; + Object.defineProperty(C, "tsF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + C.tgF = function () { + }; + Object.defineProperty(C, "tgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + return C; + })(); + var M; + (function (_M) { + var V; + function F() { + } + ; + var C = (function () { + function C() { + } + C.prototype.pF = function () { + }; + C.prototype.rF = function () { + }; + C.prototype.pgF = function () { + }; + Object.defineProperty(C.prototype, "pgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + C.prototype.psF = function (param) { + }; + Object.defineProperty(C.prototype, "psF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + C.prototype.rgF = function () { + }; + Object.defineProperty(C.prototype, "rgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + C.prototype.rsF = function (param) { + }; + Object.defineProperty(C.prototype, "rsF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + C.tF = function () { + }; + C.tsF = function (param) { + }; + Object.defineProperty(C, "tsF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + C.tgF = function () { + }; + Object.defineProperty(C, "tgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + return C; + })(); + var M; + (function (M) { + var V; + function F() { + } + ; + var C = (function () { + function C() { + } + return C; + })(); + ; + ; + ; + M.eV; + function eF() { + } + M.eF = eF; + ; + var eC = (function () { + function eC() { + } + return eC; + })(); + M.eC = eC; + ; + ; + ; + ; + ; + ; + })(M || (M = {})); + _M.eV; + function eF() { + } + _M.eF = eF; + ; + var eC = (function () { + function eC() { + } + eC.prototype.pF = function () { + }; + eC.prototype.rF = function () { + }; + eC.prototype.pgF = function () { + }; + Object.defineProperty(eC.prototype, "pgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + eC.prototype.psF = function (param) { + }; + Object.defineProperty(eC.prototype, "psF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + eC.prototype.rgF = function () { + }; + Object.defineProperty(eC.prototype, "rgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + eC.prototype.rsF = function (param) { + }; + Object.defineProperty(eC.prototype, "rsF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + eC.tF = function () { + }; + eC.tsF = function (param) { + }; + Object.defineProperty(eC, "tsF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + eC.tgF = function () { + }; + Object.defineProperty(eC, "tgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + return eC; + })(); + _M.eC = eC; + var eM; + (function (eM) { + var V; + function F() { + } + ; + var C = (function () { + function C() { + } + return C; + })(); + ; + ; + ; + eM.eV; + function eF() { + } + eM.eF = eF; + ; + var eC = (function () { + function eC() { + } + return eC; + })(); + eM.eC = eC; + ; + ; + ; + ; + ; + ; + })(eM = _M.eM || (_M.eM = {})); + ; + })(M || (M = {})); + exports.eV; + function eF() { + } + exports.eF = eF; + ; + var eC = (function () { + function eC() { + } + eC.prototype.pF = function () { + }; + eC.prototype.rF = function () { + }; + eC.prototype.pgF = function () { + }; + Object.defineProperty(eC.prototype, "pgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + eC.prototype.psF = function (param) { + }; + Object.defineProperty(eC.prototype, "psF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + eC.prototype.rgF = function () { + }; + Object.defineProperty(eC.prototype, "rgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + eC.prototype.rsF = function (param) { + }; + Object.defineProperty(eC.prototype, "rsF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + eC.tF = function () { + }; + eC.tsF = function (param) { + }; + Object.defineProperty(eC, "tsF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + eC.tgF = function () { + }; + Object.defineProperty(eC, "tgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + return eC; + })(); + exports.eC = eC; + var eM; + (function (_eM) { + var V; + function F() { + } + ; + var C = (function () { + function C() { + } + C.prototype.pF = function () { + }; + C.prototype.rF = function () { + }; + C.prototype.pgF = function () { + }; + Object.defineProperty(C.prototype, "pgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + C.prototype.psF = function (param) { + }; + Object.defineProperty(C.prototype, "psF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + C.prototype.rgF = function () { + }; + Object.defineProperty(C.prototype, "rgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + C.prototype.rsF = function (param) { + }; + Object.defineProperty(C.prototype, "rsF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + C.tF = function () { + }; + C.tsF = function (param) { + }; + Object.defineProperty(C, "tsF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + C.tgF = function () { + }; + Object.defineProperty(C, "tgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + return C; + })(); + var M; + (function (M) { + var V; + function F() { + } + ; + var C = (function () { + function C() { + } + return C; + })(); + ; + ; + ; + M.eV; + function eF() { + } + M.eF = eF; + ; + var eC = (function () { + function eC() { + } + return eC; + })(); + M.eC = eC; + ; + ; + ; + ; + ; + ; + })(M || (M = {})); + _eM.eV; + function eF() { + } + _eM.eF = eF; + ; + var eC = (function () { + function eC() { + } + eC.prototype.pF = function () { + }; + eC.prototype.rF = function () { + }; + eC.prototype.pgF = function () { + }; + Object.defineProperty(eC.prototype, "pgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + eC.prototype.psF = function (param) { + }; + Object.defineProperty(eC.prototype, "psF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + eC.prototype.rgF = function () { + }; + Object.defineProperty(eC.prototype, "rgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + eC.prototype.rsF = function (param) { + }; + Object.defineProperty(eC.prototype, "rsF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + eC.tF = function () { + }; + eC.tsF = function (param) { + }; + Object.defineProperty(eC, "tsF", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + eC.tgF = function () { + }; + Object.defineProperty(eC, "tgF", { + get: function () { + }, + enumerable: true, + configurable: true + }); + return eC; + })(); + _eM.eC = eC; + var eM; + (function (eM) { + var V; + function F() { + } + ; + var C = (function () { + function C() { + } + return C; + })(); + ; + ; + ; + eM.eV; + function eF() { + } + eM.eF = eF; + ; + var eC = (function () { + function eC() { + } + return eC; + })(); + eM.eC = eC; + ; + ; + ; + ; + ; + ; + })(eM = _eM.eM || (_eM.eM = {})); + ; + })(eM = exports.eM || (exports.eM = {})); + ; +}); diff --git a/tests/baselines/reference/illegalModifiersOnClassElements.js b/tests/baselines/reference/illegalModifiersOnClassElements.js new file mode 100644 index 00000000000..b9a40fa6aa0 --- /dev/null +++ b/tests/baselines/reference/illegalModifiersOnClassElements.js @@ -0,0 +1,14 @@ +//// [illegalModifiersOnClassElements.ts] +class C { + declare foo = 1; + export bar = 1; +} + +//// [illegalModifiersOnClassElements.js] +var C = (function () { + function C() { + this.foo = 1; + this.bar = 1; + } + return C; +})(); diff --git a/tests/baselines/reference/illegalSuperCallsInConstructor.js b/tests/baselines/reference/illegalSuperCallsInConstructor.js new file mode 100644 index 00000000000..b978af1a609 --- /dev/null +++ b/tests/baselines/reference/illegalSuperCallsInConstructor.js @@ -0,0 +1,56 @@ +//// [illegalSuperCallsInConstructor.ts] +class Base { + x: string; +} + +class Derived extends Base { + constructor() { + var r2 = () => super(); + var r3 = () => { super(); } + var r4 = function () { super(); } + var r5 = { + get foo() { + super(); + return 1; + }, + set foo(v: number) { + super(); + } + } + } +} + +//// [illegalSuperCallsInConstructor.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var Base = (function () { + function Base() { + } + return Base; +})(); +var Derived = (function (_super) { + __extends(Derived, _super); + function Derived() { + var r2 = function () { return _super.call(this); }; + var r3 = function () { + _super.call(this); + }; + var r4 = function () { + _super.call(this); + }; + var r5 = { + get foo() { + _super.call(this); + return 1; + }, + set foo(v) { + _super.call(this); + } + }; + } + return Derived; +})(Base); diff --git a/tests/baselines/reference/implementClausePrecedingExtends.js b/tests/baselines/reference/implementClausePrecedingExtends.js new file mode 100644 index 00000000000..e8f0b96f485 --- /dev/null +++ b/tests/baselines/reference/implementClausePrecedingExtends.js @@ -0,0 +1,23 @@ +//// [implementClausePrecedingExtends.ts] +class C { foo: number } +class D implements C extends C { } + +//// [implementClausePrecedingExtends.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function () { + function C() { + } + return C; +})(); +var D = (function (_super) { + __extends(D, _super); + function D() { + _super.apply(this, arguments); + } + return D; +})(C); diff --git a/tests/baselines/reference/implementsClauseAlreadySeen.js b/tests/baselines/reference/implementsClauseAlreadySeen.js new file mode 100644 index 00000000000..84823c13fa8 --- /dev/null +++ b/tests/baselines/reference/implementsClauseAlreadySeen.js @@ -0,0 +1,21 @@ +//// [implementsClauseAlreadySeen.ts] +class C { + +} +class D implements C implements C { + baz() { } +} + +//// [implementsClauseAlreadySeen.js] +var C = (function () { + function C() { + } + return C; +})(); +var D = (function () { + function D() { + } + D.prototype.baz = function () { + }; + return D; +})(); diff --git a/tests/baselines/reference/implicitAnyCastedValue.js b/tests/baselines/reference/implicitAnyCastedValue.js new file mode 100644 index 00000000000..be6bd1bfef3 --- /dev/null +++ b/tests/baselines/reference/implicitAnyCastedValue.js @@ -0,0 +1,163 @@ +//// [implicitAnyCastedValue.ts] +var x = function () { + return 0; // this should not be an error +} + +function foo() { + return "hello world"; // this should not be an error +} + +class C { + bar = null; // this should be an error + foo = undefined; // this should be an error + public get tempVar() { + return 0; // this should not be an error + } + + public returnBarWithCase() { // this should not be an error + return this.bar; + } + + public returnFooWithCase() { + return this.foo; // this should not be an error + } +} + +class C1 { + getValue = null; // this should be an error + + public get castedGet() { + return this.getValue; // this should not be an error + } + + public get notCastedGet() { + return this.getValue; // this should not be an error + } +} + +function castedNull() { + return null; // this should not be an error +} + +function notCastedNull() { + return null; // this should be an error +} + +function returnTypeBar(): any { + return null; // this should not be an error +} + +function undefinedBar() { + return undefined; // this should not be an error +} + +function multipleRets1(x) { // this should not be an error + if (x) { + return 0; + } + else { + return null; + } +} + +function multipleRets2(x) { // this should not be an error + if (x) { + return null; + } + else if (x == 1) { + return 0; + } + else { + return undefined; + } +} + +// this should not be an error +var bar1 = null; +var bar2 = undefined; +var bar3 = 0; +var array = [null, undefined]; + +//// [implicitAnyCastedValue.js] +var x = function () { + return 0; // this should not be an error +}; +function foo() { + return "hello world"; // this should not be an error +} +var C = (function () { + function C() { + this.bar = null; // this should be an error + this.foo = undefined; // this should be an error + } + Object.defineProperty(C.prototype, "tempVar", { + get: function () { + return 0; // this should not be an error + }, + enumerable: true, + configurable: true + }); + C.prototype.returnBarWithCase = function () { + return this.bar; + }; + C.prototype.returnFooWithCase = function () { + return this.foo; // this should not be an error + }; + return C; +})(); +var C1 = (function () { + function C1() { + this.getValue = null; // this should be an error + } + Object.defineProperty(C1.prototype, "castedGet", { + get: function () { + return this.getValue; // this should not be an error + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(C1.prototype, "notCastedGet", { + get: function () { + return this.getValue; // this should not be an error + }, + enumerable: true, + configurable: true + }); + return C1; +})(); +function castedNull() { + return null; // this should not be an error +} +function notCastedNull() { + return null; // this should be an error +} +function returnTypeBar() { + return null; // this should not be an error +} +function undefinedBar() { + return undefined; // this should not be an error +} +function multipleRets1(x) { + if (x) { + return 0; + } + else { + return null; + } +} +function multipleRets2(x) { + if (x) { + return null; + } + else if (x == 1) { + return 0; + } + else { + return undefined; + } +} +// this should not be an error +var bar1 = null; +var bar2 = undefined; +var bar3 = 0; +var array = [null, undefined]; diff --git a/tests/baselines/reference/implicitAnyGetAndSetAccessorWithAnyReturnType.js b/tests/baselines/reference/implicitAnyGetAndSetAccessorWithAnyReturnType.js new file mode 100644 index 00000000000..ac3b5e66493 --- /dev/null +++ b/tests/baselines/reference/implicitAnyGetAndSetAccessorWithAnyReturnType.js @@ -0,0 +1,67 @@ +//// [implicitAnyGetAndSetAccessorWithAnyReturnType.ts] +// these should be errors +class GetAndSet { + getAndSet = null; // error at "getAndSet" + public get haveGetAndSet() { // this should not be an error + return this.getAndSet; + } + + // this shouldn't be an error + public set haveGetAndSet(value) { // error at "value" + this.getAndSet = value; + } +} + +class SetterOnly { + public set haveOnlySet(newXValue) { // error at "haveOnlySet, newXValue" + } +} + +class GetterOnly { + public get haveOnlyGet() { // error at "haveOnlyGet" + return null; + } +} + +//// [implicitAnyGetAndSetAccessorWithAnyReturnType.js] +// these should be errors +var GetAndSet = (function () { + function GetAndSet() { + this.getAndSet = null; // error at "getAndSet" + } + Object.defineProperty(GetAndSet.prototype, "haveGetAndSet", { + get: function () { + return this.getAndSet; + }, + // this shouldn't be an error + set: function (value) { + this.getAndSet = value; + }, + enumerable: true, + configurable: true + }); + return GetAndSet; +})(); +var SetterOnly = (function () { + function SetterOnly() { + } + Object.defineProperty(SetterOnly.prototype, "haveOnlySet", { + set: function (newXValue) { + }, + enumerable: true, + configurable: true + }); + return SetterOnly; +})(); +var GetterOnly = (function () { + function GetterOnly() { + } + Object.defineProperty(GetterOnly.prototype, "haveOnlyGet", { + get: function () { + return null; + }, + enumerable: true, + configurable: true + }); + return GetterOnly; +})(); diff --git a/tests/baselines/reference/implicitAnyInAmbientDeclaration.js b/tests/baselines/reference/implicitAnyInAmbientDeclaration.js new file mode 100644 index 00000000000..7807f8fc1ee --- /dev/null +++ b/tests/baselines/reference/implicitAnyInAmbientDeclaration.js @@ -0,0 +1,16 @@ +//// [implicitAnyInAmbientDeclaration.ts] +module Test { + declare class C { + public publicMember; // this should be an error + private privateMember; // this should not be an error + + public publicFunction(x); // this should be an error + private privateFunction(privateParam); // this should not be an error + private constructor(privateParam); + } +} + +//// [implicitAnyInAmbientDeclaration.js] +var Test; +(function (Test) { +})(Test || (Test = {})); diff --git a/tests/baselines/reference/importAliasAnExternalModuleInsideAnInternalModule.js b/tests/baselines/reference/importAliasAnExternalModuleInsideAnInternalModule.js new file mode 100644 index 00000000000..35992b86fec --- /dev/null +++ b/tests/baselines/reference/importAliasAnExternalModuleInsideAnInternalModule.js @@ -0,0 +1,31 @@ +//// [tests/cases/compiler/importAliasAnExternalModuleInsideAnInternalModule.ts] //// + +//// [importAliasAnExternalModuleInsideAnInternalModule_file0.ts] +export module m { + export function foo() { } +} + +//// [importAliasAnExternalModuleInsideAnInternalModule_file1.ts] +import r = require('importAliasAnExternalModuleInsideAnInternalModule_file0'); +module m_private { + //import r2 = require('m'); // would be error + export import C = r; // no error + C.m.foo(); +} + + +//// [importAliasAnExternalModuleInsideAnInternalModule_file0.js] +var m; +(function (m) { + function foo() { + } + m.foo = foo; +})(m = exports.m || (exports.m = {})); +//// [importAliasAnExternalModuleInsideAnInternalModule_file1.js] +var r = require('importAliasAnExternalModuleInsideAnInternalModule_file0'); +var m_private; +(function (m_private) { + //import r2 = require('m'); // would be error + m_private.C = r; // no error + m_private.C.m.foo(); +})(m_private || (m_private = {})); diff --git a/tests/baselines/reference/importDeclRefereingExternalModuleWithNoResolve.js b/tests/baselines/reference/importDeclRefereingExternalModuleWithNoResolve.js new file mode 100644 index 00000000000..34a662d6451 --- /dev/null +++ b/tests/baselines/reference/importDeclRefereingExternalModuleWithNoResolve.js @@ -0,0 +1,8 @@ +//// [importDeclRefereingExternalModuleWithNoResolve.ts] +import b = require("externalModule"); +declare module "m1" { + import im2 = require("externalModule"); +} + + +//// [importDeclRefereingExternalModuleWithNoResolve.js] diff --git a/tests/baselines/reference/importDeclWithClassModifiers.js b/tests/baselines/reference/importDeclWithClassModifiers.js new file mode 100644 index 00000000000..c8aefe03bab --- /dev/null +++ b/tests/baselines/reference/importDeclWithClassModifiers.js @@ -0,0 +1,15 @@ +//// [importDeclWithClassModifiers.ts] +module x { + interface c { + } +} +export public import a = x.c; +export private import b = x.c; +export static import c = x.c; +var b: a; + + +//// [importDeclWithClassModifiers.js] +define(["require", "exports"], function (require, exports) { + var b; +}); diff --git a/tests/baselines/reference/importDeclWithDeclareModifier.js b/tests/baselines/reference/importDeclWithDeclareModifier.js new file mode 100644 index 00000000000..3c80e47a90f --- /dev/null +++ b/tests/baselines/reference/importDeclWithDeclareModifier.js @@ -0,0 +1,11 @@ +//// [importDeclWithDeclareModifier.ts] +module x { + interface c { + } +} +declare export import a = x.c; +var b: a; + + +//// [importDeclWithDeclareModifier.js] +var b; diff --git a/tests/baselines/reference/importDeclWithDeclareModifierInAmbientContext.js b/tests/baselines/reference/importDeclWithDeclareModifierInAmbientContext.js new file mode 100644 index 00000000000..a268c8a0987 --- /dev/null +++ b/tests/baselines/reference/importDeclWithDeclareModifierInAmbientContext.js @@ -0,0 +1,12 @@ +//// [importDeclWithDeclareModifierInAmbientContext.ts] +declare module "m" { + module x { + interface c { + } + } + declare export import a = x.c; + var b: a; +} + + +//// [importDeclWithDeclareModifierInAmbientContext.js] diff --git a/tests/baselines/reference/importDeclarationInModuleDeclaration1.js b/tests/baselines/reference/importDeclarationInModuleDeclaration1.js new file mode 100644 index 00000000000..46a62fd0584 --- /dev/null +++ b/tests/baselines/reference/importDeclarationInModuleDeclaration1.js @@ -0,0 +1,6 @@ +//// [importDeclarationInModuleDeclaration1.ts] +module m2 { + import m3 = require("use_glo_M1_public"); +} + +//// [importDeclarationInModuleDeclaration1.js] diff --git a/tests/baselines/reference/importInsideModule.js b/tests/baselines/reference/importInsideModule.js new file mode 100644 index 00000000000..b0ba16fa850 --- /dev/null +++ b/tests/baselines/reference/importInsideModule.js @@ -0,0 +1,17 @@ +//// [tests/cases/compiler/importInsideModule.ts] //// + +//// [importInsideModule_file1.ts] +export var x = 1; + +//// [importInsideModule_file2.ts] +export module myModule { + import foo = require("importInsideModule_file1"); + var a = foo.x; +} + +//// [importInsideModule_file2.js] +var myModule; +(function (myModule) { + var foo = require("importInsideModule_file1"); + var a = foo.x; +})(myModule = exports.myModule || (exports.myModule = {})); diff --git a/tests/baselines/reference/importNonStringLiteral.js b/tests/baselines/reference/importNonStringLiteral.js new file mode 100644 index 00000000000..52ef5a10a67 --- /dev/null +++ b/tests/baselines/reference/importNonStringLiteral.js @@ -0,0 +1,7 @@ +//// [importNonStringLiteral.ts] +var x = "filename"; +import foo = require(x); // invalid + + +//// [importNonStringLiteral.js] +var x = "filename"; diff --git a/tests/baselines/reference/incompleteDottedExpressionAtEOF.js b/tests/baselines/reference/incompleteDottedExpressionAtEOF.js new file mode 100644 index 00000000000..9a51c206683 --- /dev/null +++ b/tests/baselines/reference/incompleteDottedExpressionAtEOF.js @@ -0,0 +1,7 @@ +//// [incompleteDottedExpressionAtEOF.ts] +// used to leak __missing into error message +var p2 = window. + +//// [incompleteDottedExpressionAtEOF.js] +// used to leak __missing into error message +var p2 = window.; diff --git a/tests/baselines/reference/incompleteObjectLiteral1.js b/tests/baselines/reference/incompleteObjectLiteral1.js new file mode 100644 index 00000000000..ecdbe86604a --- /dev/null +++ b/tests/baselines/reference/incompleteObjectLiteral1.js @@ -0,0 +1,7 @@ +//// [incompleteObjectLiteral1.ts] +var tt = { aa; } +var x = tt; + +//// [incompleteObjectLiteral1.js] +var tt = { aa: }; +var x = tt; diff --git a/tests/baselines/reference/incrementAndDecrement.js b/tests/baselines/reference/incrementAndDecrement.js new file mode 100644 index 00000000000..96794e3c956 --- /dev/null +++ b/tests/baselines/reference/incrementAndDecrement.js @@ -0,0 +1,123 @@ +//// [incrementAndDecrement.ts] +enum E { A, B, C }; +var x = 4; +var e = E.B; +var a: any; +var w = window; + +// Assign to expression++ +x++ = 4; // Error + +// Assign to expression-- +x-- = 5; // Error + +// Assign to++expression +++x = 4; // Error + +// Assign to--expression +--x = 5; // Error + +// Pre and postfix++ on number +x++; +x--; +++x; +--x; +++x++; // Error +--x--; // Error +++x--; // Error +--x++; // Error + +// Pre and postfix++ on enum +e++; +e--; +++e; +--e; +++e++; // Error +--e--; // Error +++e--; // Error +--e++; // Error + +// Pre and postfix++ on value of type 'any' +a++; +a--; +++a; +--a; +++a++; // Error +--a--; // Error +++a--; // Error +--a++; // Error + + +// Pre and postfix++ on other types +w++; // Error +w--; // Error +++w; // Error +--w; // Error +++w++; // Error +--w--; // Error +++w--; // Error +--w++; // Error + + + + +//// [incrementAndDecrement.js] +var E; +(function (E) { + E[E["A"] = 0] = "A"; + E[E["B"] = 1] = "B"; + E[E["C"] = 2] = "C"; +})(E || (E = {})); +; +var x = 4; +var e = 1 /* B */; +var a; +var w = window; +// Assign to expression++ +x++; +4; // Error +// Assign to expression-- +x--; +5; // Error +// Assign to++expression +++x; +4; // Error +// Assign to--expression +--x; +5; // Error +// Pre and postfix++ on number +x++; +x--; +++x; +--x; +++x++; // Error +--x--; // Error +++x--; // Error +--x++; // Error +// Pre and postfix++ on enum +e++; +e--; +++e; +--e; +++e++; // Error +--e--; // Error +++e--; // Error +--e++; // Error +// Pre and postfix++ on value of type 'any' +a++; +a--; +++a; +--a; +++a++; // Error +--a--; // Error +++a--; // Error +--a++; // Error +// Pre and postfix++ on other types +w++; // Error +w--; // Error +++w; // Error +--w; // Error +++w++; // Error +--w--; // Error +++w--; // Error +--w++; // Error diff --git a/tests/baselines/reference/indexSignatureMustHaveTypeAnnotation.js b/tests/baselines/reference/indexSignatureMustHaveTypeAnnotation.js new file mode 100644 index 00000000000..f586a19bf0e --- /dev/null +++ b/tests/baselines/reference/indexSignatureMustHaveTypeAnnotation.js @@ -0,0 +1,28 @@ +//// [indexSignatureMustHaveTypeAnnotation.ts] +interface I { + // Used to be indexer, now it is a computed property + [x]: string; + [x: string]; +} + +class C { + // Used to be indexer, now it is a computed property + [x]: string + +} + +class C2 { + [x: string] +} + +//// [indexSignatureMustHaveTypeAnnotation.js] +var C = (function () { + function C() { + } + return C; +})(); +var C2 = (function () { + function C2() { + } + return C2; +})(); diff --git a/tests/baselines/reference/indexSignatureTypeCheck.js b/tests/baselines/reference/indexSignatureTypeCheck.js new file mode 100644 index 00000000000..02676348bec --- /dev/null +++ b/tests/baselines/reference/indexSignatureTypeCheck.js @@ -0,0 +1,24 @@ +//// [indexSignatureTypeCheck.ts] +interface IPropertySet { + + [index: string]: any; + +} + + +var ps: IPropertySet = null; +var index: any = "hello"; +ps[index] = 12; + + +interface indexErrors { + [p2?: string]; + [...p3: any[]]; + [p4: string, p5?: string]; + [p6: string, ...p7: any[]]; +} + +//// [indexSignatureTypeCheck.js] +var ps = null; +var index = "hello"; +ps[index] = 12; diff --git a/tests/baselines/reference/indexSignatureTypeCheck2.js b/tests/baselines/reference/indexSignatureTypeCheck2.js new file mode 100644 index 00000000000..6dcc0f392a5 --- /dev/null +++ b/tests/baselines/reference/indexSignatureTypeCheck2.js @@ -0,0 +1,25 @@ +//// [indexSignatureTypeCheck2.ts] +class IPropertySet { + [index: string]: any +} + +var ps: IPropertySet = null; +var index: any = "hello"; +ps[index] = 12; + +interface indexErrors { + [p2?: string]; + [...p3: any[]]; + [p4: string, p5?: string]; + [p6: string, ...p7: any[]]; +} + +//// [indexSignatureTypeCheck2.js] +var IPropertySet = (function () { + function IPropertySet() { + } + return IPropertySet; +})(); +var ps = null; +var index = "hello"; +ps[index] = 12; diff --git a/tests/baselines/reference/indexSignatureWithAccessibilityModifier.js b/tests/baselines/reference/indexSignatureWithAccessibilityModifier.js new file mode 100644 index 00000000000..798fef924b9 --- /dev/null +++ b/tests/baselines/reference/indexSignatureWithAccessibilityModifier.js @@ -0,0 +1,15 @@ +//// [indexSignatureWithAccessibilityModifier.ts] +interface I { + [public x: string]: string; +} + +class C { + [public x: string]: string +} + +//// [indexSignatureWithAccessibilityModifier.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/indexSignatureWithInitializer.js b/tests/baselines/reference/indexSignatureWithInitializer.js new file mode 100644 index 00000000000..490033dde0f --- /dev/null +++ b/tests/baselines/reference/indexSignatureWithInitializer.js @@ -0,0 +1,16 @@ +//// [indexSignatureWithInitializer.ts] +// These used to be indexers, now they are computed properties +interface I { + [x = '']: string; +} + +class C { + [x = 0]: string +} + +//// [indexSignatureWithInitializer.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/indexSignatureWithInitializer1.js b/tests/baselines/reference/indexSignatureWithInitializer1.js new file mode 100644 index 00000000000..16852fd4174 --- /dev/null +++ b/tests/baselines/reference/indexSignatureWithInitializer1.js @@ -0,0 +1,11 @@ +//// [indexSignatureWithInitializer1.ts] +class C { + [a: number = 1]: number; +} + +//// [indexSignatureWithInitializer1.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/indexSignatureWithoutTypeAnnotation1.js b/tests/baselines/reference/indexSignatureWithoutTypeAnnotation1.js new file mode 100644 index 00000000000..bef6af37931 --- /dev/null +++ b/tests/baselines/reference/indexSignatureWithoutTypeAnnotation1.js @@ -0,0 +1,11 @@ +//// [indexSignatureWithoutTypeAnnotation1.ts] +class C { + [a: number]; +} + +//// [indexSignatureWithoutTypeAnnotation1.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/indexTypeCheck.js b/tests/baselines/reference/indexTypeCheck.js new file mode 100644 index 00000000000..6e74111a357 --- /dev/null +++ b/tests/baselines/reference/indexTypeCheck.js @@ -0,0 +1,87 @@ +//// [indexTypeCheck.ts] +interface Red { + [n:number]; // ok + [s:string]; // ok +} + +interface Blue { + [n:number]: any; // ok + [s:string]: any; // ok +} + +interface Yellow { + [n:number]: Red; // ok + [s:string]: Red; // ok +} + +interface Orange { + [n:number]: number; // ok + [s:string]: string; // error +} + +interface Green { + [n:number]: Orange; // error + [s:string]: Yellow; // ok +} + +interface Cyan { + [n:number]: number; // error + [s:string]: string; // ok +} + +interface Purple { + [n:number, s:string]; // error +} + +interface Magenta { + [p:Purple]; // error +} + +var yellow: Yellow; +var blue: Blue; +var s = "some string"; + +yellow[5]; // ok +yellow["hue"]; // ok +yellow[{}]; // ok + +s[0]; // error +s["s"]; // ok +s[{}]; // ok + +yellow[blue]; // error + +var x:number[]; +x[0]; + +class Benchmark { + + public results: { [x:string]: any; } = <{ [x:string]: any; }>{}; + + public addTimingFor(name: string, timing: number) { + this.results[name] = this.results[name]; + } +} + +//// [indexTypeCheck.js] +var yellow; +var blue; +var s = "some string"; +yellow[5]; // ok +yellow["hue"]; // ok +yellow[{}]; // ok +s[0]; // error +s["s"]; // ok +s[{}]; // ok +yellow[blue]; // error +var x; +x[0]; +var Benchmark = (function () { + function Benchmark() { + this.results = {}; + } + Benchmark.prototype.addTimingFor = function (name, timing) { + this.results[name] = this.results[name]; + }; + return Benchmark; +})(); diff --git a/tests/baselines/reference/indexWithoutParamType.js b/tests/baselines/reference/indexWithoutParamType.js new file mode 100644 index 00000000000..0ea3e8f897f --- /dev/null +++ b/tests/baselines/reference/indexWithoutParamType.js @@ -0,0 +1,5 @@ +//// [indexWithoutParamType.ts] +var y: { []; } // Error + +//// [indexWithoutParamType.js] +var y; // Error diff --git a/tests/baselines/reference/indexWithoutParamType2.js b/tests/baselines/reference/indexWithoutParamType2.js new file mode 100644 index 00000000000..4197b0596ec --- /dev/null +++ b/tests/baselines/reference/indexWithoutParamType2.js @@ -0,0 +1,12 @@ +//// [indexWithoutParamType2.ts] +class C { + // Used to be indexer, now it is a computed property + [x]: string +} + +//// [indexWithoutParamType2.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/indexerAsOptional.js b/tests/baselines/reference/indexerAsOptional.js new file mode 100644 index 00000000000..509e3890ec8 --- /dev/null +++ b/tests/baselines/reference/indexerAsOptional.js @@ -0,0 +1,17 @@ +//// [indexerAsOptional.ts] +interface indexSig { + //Index signatures can't be optional + [idx?: number]: any; //err +} + +class indexSig2 { + //Index signatures can't be optional + [idx?: number]: any //err +} + +//// [indexerAsOptional.js] +var indexSig2 = (function () { + function indexSig2() { + } + return indexSig2; +})(); diff --git a/tests/baselines/reference/indexerSignatureWithRestParam.js b/tests/baselines/reference/indexerSignatureWithRestParam.js new file mode 100644 index 00000000000..8a7defb049c --- /dev/null +++ b/tests/baselines/reference/indexerSignatureWithRestParam.js @@ -0,0 +1,15 @@ +//// [indexerSignatureWithRestParam.ts] +interface I { + [...x]: string; +} + +class C { + [...x]: string +} + +//// [indexerSignatureWithRestParam.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/inferSetterParamType.js b/tests/baselines/reference/inferSetterParamType.js new file mode 100644 index 00000000000..c0be3a5c394 --- /dev/null +++ b/tests/baselines/reference/inferSetterParamType.js @@ -0,0 +1,49 @@ +//// [inferSetterParamType.ts] +class Foo { + + get bar() { + return 0; + } + set bar(n) { // should not be an error - infer number + } +} + +class Foo2 { + + get bar() { + return 0; // should be an error - can't coerce infered return type to match setter annotated type + } + set bar(n:string) { + } +} + + +//// [inferSetterParamType.js] +var Foo = (function () { + function Foo() { + } + Object.defineProperty(Foo.prototype, "bar", { + get: function () { + return 0; + }, + set: function (n) { + }, + enumerable: true, + configurable: true + }); + return Foo; +})(); +var Foo2 = (function () { + function Foo2() { + } + Object.defineProperty(Foo2.prototype, "bar", { + get: function () { + return 0; // should be an error - can't coerce infered return type to match setter annotated type + }, + set: function (n) { + }, + enumerable: true, + configurable: true + }); + return Foo2; +})(); diff --git a/tests/baselines/reference/infinitelyExpandingOverloads.js b/tests/baselines/reference/infinitelyExpandingOverloads.js new file mode 100644 index 00000000000..1e84eba27cf --- /dev/null +++ b/tests/baselines/reference/infinitelyExpandingOverloads.js @@ -0,0 +1,52 @@ +//// [infinitelyExpandingOverloads.ts] +interface KnockoutSubscription2 { + target: KnockoutObservableBase2; +} +interface KnockoutObservableBase2 { + subscribe(callback: (newValue: T) => void, target?: any, topic?: string): KnockoutSubscription2; +} +interface ValidationPlacement2 { + initialize(validatable: Validatable2): void; +} +interface Validatable2 { + validators: KnockoutObservableBase2>; +} +class Validator2 { + private _subscription: KnockoutSubscription2; +} +class ViewModel { + public validationPlacements: Array> = new Array>(); +} +class Widget { + constructor(viewModelType: new () => ViewModel); // Shouldnt error on this overload + constructor(viewModelType: new () => ViewModel) { + } + public get options(): ViewModel { + return null; + } +} + +//// [infinitelyExpandingOverloads.js] +var Validator2 = (function () { + function Validator2() { + } + return Validator2; +})(); +var ViewModel = (function () { + function ViewModel() { + this.validationPlacements = new Array(); + } + return ViewModel; +})(); +var Widget = (function () { + function Widget(viewModelType) { + } + Object.defineProperty(Widget.prototype, "options", { + get: function () { + return null; + }, + enumerable: true, + configurable: true + }); + return Widget; +})(); diff --git a/tests/baselines/reference/inheritanceMemberAccessorOverridingAccessor.js b/tests/baselines/reference/inheritanceMemberAccessorOverridingAccessor.js new file mode 100644 index 00000000000..d1eb53c4ec7 --- /dev/null +++ b/tests/baselines/reference/inheritanceMemberAccessorOverridingAccessor.js @@ -0,0 +1,56 @@ +//// [inheritanceMemberAccessorOverridingAccessor.ts] +class a { + get x() { + return "20"; + } + set x(aValue: string) { + + } +} + +class b extends a { + get x() { + return "20"; + } + set x(aValue: string) { + + } +} + +//// [inheritanceMemberAccessorOverridingAccessor.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var a = (function () { + function a() { + } + Object.defineProperty(a.prototype, "x", { + get: function () { + return "20"; + }, + set: function (aValue) { + }, + enumerable: true, + configurable: true + }); + return a; +})(); +var b = (function (_super) { + __extends(b, _super); + function b() { + _super.apply(this, arguments); + } + Object.defineProperty(b.prototype, "x", { + get: function () { + return "20"; + }, + set: function (aValue) { + }, + enumerable: true, + configurable: true + }); + return b; +})(a); diff --git a/tests/baselines/reference/inheritanceMemberAccessorOverridingMethod.js b/tests/baselines/reference/inheritanceMemberAccessorOverridingMethod.js new file mode 100644 index 00000000000..d234eb89582 --- /dev/null +++ b/tests/baselines/reference/inheritanceMemberAccessorOverridingMethod.js @@ -0,0 +1,47 @@ +//// [inheritanceMemberAccessorOverridingMethod.ts] +class a { + x() { + return "20"; + } +} + +class b extends a { + get x() { + return "20"; + } + set x(aValue: string) { + + } +} + +//// [inheritanceMemberAccessorOverridingMethod.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var a = (function () { + function a() { + } + a.prototype.x = function () { + return "20"; + }; + return a; +})(); +var b = (function (_super) { + __extends(b, _super); + function b() { + _super.apply(this, arguments); + } + Object.defineProperty(b.prototype, "x", { + get: function () { + return "20"; + }, + set: function (aValue) { + }, + enumerable: true, + configurable: true + }); + return b; +})(a); diff --git a/tests/baselines/reference/inheritanceMemberAccessorOverridingProperty.js b/tests/baselines/reference/inheritanceMemberAccessorOverridingProperty.js new file mode 100644 index 00000000000..b307f3bfedb --- /dev/null +++ b/tests/baselines/reference/inheritanceMemberAccessorOverridingProperty.js @@ -0,0 +1,42 @@ +//// [inheritanceMemberAccessorOverridingProperty.ts] +class a { + x: string; +} + +class b extends a { + get x() { + return "20"; + } + set x(aValue: string) { + + } +} + +//// [inheritanceMemberAccessorOverridingProperty.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var a = (function () { + function a() { + } + return a; +})(); +var b = (function (_super) { + __extends(b, _super); + function b() { + _super.apply(this, arguments); + } + Object.defineProperty(b.prototype, "x", { + get: function () { + return "20"; + }, + set: function (aValue) { + }, + enumerable: true, + configurable: true + }); + return b; +})(a); diff --git a/tests/baselines/reference/inheritanceMemberFuncOverridingAccessor.js b/tests/baselines/reference/inheritanceMemberFuncOverridingAccessor.js new file mode 100644 index 00000000000..e05ed9633cc --- /dev/null +++ b/tests/baselines/reference/inheritanceMemberFuncOverridingAccessor.js @@ -0,0 +1,47 @@ +//// [inheritanceMemberFuncOverridingAccessor.ts] +class a { + get x() { + return "20"; + } + set x(aValue: string) { + + } +} + +class b extends a { + x() { + return "20"; + } +} + +//// [inheritanceMemberFuncOverridingAccessor.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var a = (function () { + function a() { + } + Object.defineProperty(a.prototype, "x", { + get: function () { + return "20"; + }, + set: function (aValue) { + }, + enumerable: true, + configurable: true + }); + return a; +})(); +var b = (function (_super) { + __extends(b, _super); + function b() { + _super.apply(this, arguments); + } + b.prototype.x = function () { + return "20"; + }; + return b; +})(a); diff --git a/tests/baselines/reference/inheritanceMemberPropertyOverridingAccessor.js b/tests/baselines/reference/inheritanceMemberPropertyOverridingAccessor.js new file mode 100644 index 00000000000..7d92b494416 --- /dev/null +++ b/tests/baselines/reference/inheritanceMemberPropertyOverridingAccessor.js @@ -0,0 +1,44 @@ +//// [inheritanceMemberPropertyOverridingAccessor.ts] +class a { + private __x: () => string; + get x() { + return this.__x; + } + set x(aValue: () => string) { + this.__x = aValue; + } +} + +class b extends a { + x: () => string; +} + +//// [inheritanceMemberPropertyOverridingAccessor.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var a = (function () { + function a() { + } + Object.defineProperty(a.prototype, "x", { + get: function () { + return this.__x; + }, + set: function (aValue) { + this.__x = aValue; + }, + enumerable: true, + configurable: true + }); + return a; +})(); +var b = (function (_super) { + __extends(b, _super); + function b() { + _super.apply(this, arguments); + } + return b; +})(a); diff --git a/tests/baselines/reference/inheritanceStaticAccessorOverridingAccessor.js b/tests/baselines/reference/inheritanceStaticAccessorOverridingAccessor.js new file mode 100644 index 00000000000..f7ed912d030 --- /dev/null +++ b/tests/baselines/reference/inheritanceStaticAccessorOverridingAccessor.js @@ -0,0 +1,56 @@ +//// [inheritanceStaticAccessorOverridingAccessor.ts] +class a { + static get x() { + return "20"; + } + static set x(aValue: string) { + + } +} + +class b extends a { + static get x() { + return "20"; + } + static set x(aValue: string) { + + } +} + +//// [inheritanceStaticAccessorOverridingAccessor.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var a = (function () { + function a() { + } + Object.defineProperty(a, "x", { + get: function () { + return "20"; + }, + set: function (aValue) { + }, + enumerable: true, + configurable: true + }); + return a; +})(); +var b = (function (_super) { + __extends(b, _super); + function b() { + _super.apply(this, arguments); + } + Object.defineProperty(b, "x", { + get: function () { + return "20"; + }, + set: function (aValue) { + }, + enumerable: true, + configurable: true + }); + return b; +})(a); diff --git a/tests/baselines/reference/inheritanceStaticAccessorOverridingMethod.js b/tests/baselines/reference/inheritanceStaticAccessorOverridingMethod.js new file mode 100644 index 00000000000..dbef001740e --- /dev/null +++ b/tests/baselines/reference/inheritanceStaticAccessorOverridingMethod.js @@ -0,0 +1,47 @@ +//// [inheritanceStaticAccessorOverridingMethod.ts] +class a { + static x() { + return "20"; + } +} + +class b extends a { + static get x() { + return "20"; + } + static set x(aValue: string) { + + } +} + +//// [inheritanceStaticAccessorOverridingMethod.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var a = (function () { + function a() { + } + a.x = function () { + return "20"; + }; + return a; +})(); +var b = (function (_super) { + __extends(b, _super); + function b() { + _super.apply(this, arguments); + } + Object.defineProperty(b, "x", { + get: function () { + return "20"; + }, + set: function (aValue) { + }, + enumerable: true, + configurable: true + }); + return b; +})(a); diff --git a/tests/baselines/reference/inheritanceStaticAccessorOverridingProperty.js b/tests/baselines/reference/inheritanceStaticAccessorOverridingProperty.js new file mode 100644 index 00000000000..3536ca8accb --- /dev/null +++ b/tests/baselines/reference/inheritanceStaticAccessorOverridingProperty.js @@ -0,0 +1,42 @@ +//// [inheritanceStaticAccessorOverridingProperty.ts] +class a { + static x: string; +} + +class b extends a { + static get x() { + return "20"; + } + static set x(aValue: string) { + + } +} + +//// [inheritanceStaticAccessorOverridingProperty.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var a = (function () { + function a() { + } + return a; +})(); +var b = (function (_super) { + __extends(b, _super); + function b() { + _super.apply(this, arguments); + } + Object.defineProperty(b, "x", { + get: function () { + return "20"; + }, + set: function (aValue) { + }, + enumerable: true, + configurable: true + }); + return b; +})(a); diff --git a/tests/baselines/reference/inheritanceStaticFuncOverridingAccessor.js b/tests/baselines/reference/inheritanceStaticFuncOverridingAccessor.js new file mode 100644 index 00000000000..b3cc7d3461e --- /dev/null +++ b/tests/baselines/reference/inheritanceStaticFuncOverridingAccessor.js @@ -0,0 +1,47 @@ +//// [inheritanceStaticFuncOverridingAccessor.ts] +class a { + static get x() { + return "20"; + } + static set x(aValue: string) { + + } +} + +class b extends a { + static x() { + return "20"; + } +} + +//// [inheritanceStaticFuncOverridingAccessor.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var a = (function () { + function a() { + } + Object.defineProperty(a, "x", { + get: function () { + return "20"; + }, + set: function (aValue) { + }, + enumerable: true, + configurable: true + }); + return a; +})(); +var b = (function (_super) { + __extends(b, _super); + function b() { + _super.apply(this, arguments); + } + b.x = function () { + return "20"; + }; + return b; +})(a); diff --git a/tests/baselines/reference/inheritanceStaticFuncOverridingAccessorOfFuncType.js b/tests/baselines/reference/inheritanceStaticFuncOverridingAccessorOfFuncType.js new file mode 100644 index 00000000000..bb77561153e --- /dev/null +++ b/tests/baselines/reference/inheritanceStaticFuncOverridingAccessorOfFuncType.js @@ -0,0 +1,42 @@ +//// [inheritanceStaticFuncOverridingAccessorOfFuncType.ts] +class a { + static get x(): () => string { + return null; + } +} + +class b extends a { + static x() { + return "20"; + } +} + +//// [inheritanceStaticFuncOverridingAccessorOfFuncType.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var a = (function () { + function a() { + } + Object.defineProperty(a, "x", { + get: function () { + return null; + }, + enumerable: true, + configurable: true + }); + return a; +})(); +var b = (function (_super) { + __extends(b, _super); + function b() { + _super.apply(this, arguments); + } + b.x = function () { + return "20"; + }; + return b; +})(a); diff --git a/tests/baselines/reference/inheritanceStaticPropertyOverridingAccessor.js b/tests/baselines/reference/inheritanceStaticPropertyOverridingAccessor.js new file mode 100644 index 00000000000..da3a42eafe1 --- /dev/null +++ b/tests/baselines/reference/inheritanceStaticPropertyOverridingAccessor.js @@ -0,0 +1,42 @@ +//// [inheritanceStaticPropertyOverridingAccessor.ts] +class a { + static get x(): () => string { + return null;; + } + static set x(aValue: () => string) { + } +} + +class b extends a { + static x: () => string; +} + +//// [inheritanceStaticPropertyOverridingAccessor.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var a = (function () { + function a() { + } + Object.defineProperty(a, "x", { + get: function () { + return null; + ; + }, + set: function (aValue) { + }, + enumerable: true, + configurable: true + }); + return a; +})(); +var b = (function (_super) { + __extends(b, _super); + function b() { + _super.apply(this, arguments); + } + return b; +})(a); diff --git a/tests/baselines/reference/initializerReferencingConstructorLocals.js b/tests/baselines/reference/initializerReferencingConstructorLocals.js new file mode 100644 index 00000000000..f382b5b7010 --- /dev/null +++ b/tests/baselines/reference/initializerReferencingConstructorLocals.js @@ -0,0 +1,43 @@ +//// [initializerReferencingConstructorLocals.ts] +// Initializer expressions for instance member variables are evaluated in the scope of the class constructor body but are not permitted to reference parameters or local variables of the constructor. + +class C { + a = z; // error + b: typeof z; // error + c = this.z; // error + d: typeof this.z; // error + constructor(x) { + z = 1; + } +} + +class D { + a = z; // error + b: typeof z; // error + c = this.z; // error + d: typeof this.z; // error + constructor(x: T) { + z = 1; + } +} + +//// [initializerReferencingConstructorLocals.js] +// Initializer expressions for instance member variables are evaluated in the scope of the class constructor body but are not permitted to reference parameters or local variables of the constructor. +var C = (function () { + function C(x) { + this.a = z; // error + this.c = this.z; // error + this.d = this.z; // error + z = 1; + } + return C; +})(); +var D = (function () { + function D(x) { + this.a = z; // error + this.c = this.z; // error + this.d = this.z; // error + z = 1; + } + return D; +})(); diff --git a/tests/baselines/reference/initializerReferencingConstructorParameters.js b/tests/baselines/reference/initializerReferencingConstructorParameters.js new file mode 100644 index 00000000000..8314d5b7155 --- /dev/null +++ b/tests/baselines/reference/initializerReferencingConstructorParameters.js @@ -0,0 +1,58 @@ +//// [initializerReferencingConstructorParameters.ts] +// Initializer expressions for instance member variables are evaluated in the scope of the class constructor body but are not permitted to reference parameters or local variables of the constructor. + +class C { + a = x; // error + b: typeof x; // error + constructor(x) { } +} + +class D { + a = x; // error + b: typeof x; // error + constructor(public x) { } +} + +class E { + a = this.x; // ok + b: typeof this.x; // error + constructor(public x) { } +} + +class F { + a = this.x; // ok + b = x; // error + constructor(public x: T) { } +} + +//// [initializerReferencingConstructorParameters.js] +// Initializer expressions for instance member variables are evaluated in the scope of the class constructor body but are not permitted to reference parameters or local variables of the constructor. +var C = (function () { + function C(x) { + this.a = x; // error + } + return C; +})(); +var D = (function () { + function D(x) { + this.x = x; + this.a = x; // error + } + return D; +})(); +var E = (function () { + function E(x) { + this.x = x; + this.a = this.x; // ok + this.b = this.x; // error + } + return E; +})(); +var F = (function () { + function F(x) { + this.x = x; + this.a = this.x; // ok + this.b = x; // error + } + return F; +})(); diff --git a/tests/baselines/reference/initializersInDeclarations.js b/tests/baselines/reference/initializersInDeclarations.js new file mode 100644 index 00000000000..0506c72fc56 --- /dev/null +++ b/tests/baselines/reference/initializersInDeclarations.js @@ -0,0 +1,23 @@ +//// [initializersInDeclarations.ts] + +// Errors: Initializers & statements in declaration file + +declare class Foo { + name = "test"; + "some prop" = 42; + fn(): boolean { + return false; + } +} + +declare var x = []; +declare var y = {}; + +declare module M1 { + while(true); + + export var v1 = () => false; +} + +//// [initializersInDeclarations.js] +// Errors: Initializers & statements in declaration file diff --git a/tests/baselines/reference/innerModExport1.js b/tests/baselines/reference/innerModExport1.js new file mode 100644 index 00000000000..d61e79f2396 --- /dev/null +++ b/tests/baselines/reference/innerModExport1.js @@ -0,0 +1,45 @@ +//// [innerModExport1.ts] +module Outer { + + // inner mod 1 + var non_export_var: number; + module { + var non_export_var = 0; + export var export_var = 1; + + function NonExportFunc() { return 0; } + + export function ExportFunc() { return 0; } + } + + export var outer_var_export = 0; + export function outerFuncExport() { return 0; } + +} + +Outer.ExportFunc(); + +//// [innerModExport1.js] +var Outer; +(function (Outer) { + // inner mod 1 + var non_export_var; + module; + { + var non_export_var = 0; + Outer.export_var = 1; + function NonExportFunc() { + return 0; + } + function ExportFunc() { + return 0; + } + Outer.ExportFunc = ExportFunc; + } + Outer.outer_var_export = 0; + function outerFuncExport() { + return 0; + } + Outer.outerFuncExport = outerFuncExport; +})(Outer || (Outer = {})); +Outer.ExportFunc(); diff --git a/tests/baselines/reference/innerModExport2.js b/tests/baselines/reference/innerModExport2.js new file mode 100644 index 00000000000..26399879e6d --- /dev/null +++ b/tests/baselines/reference/innerModExport2.js @@ -0,0 +1,47 @@ +//// [innerModExport2.ts] +module Outer { + + // inner mod 1 + var non_export_var: number; + module { + var non_export_var = 0; + export var export_var = 1; + + function NonExportFunc() { return 0; } + + export function ExportFunc() { return 0; } + } + var export_var: number; + + export var outer_var_export = 0; + export function outerFuncExport() { return 0; } + +} + +Outer.NonExportFunc(); + +//// [innerModExport2.js] +var Outer; +(function (Outer) { + // inner mod 1 + var non_export_var; + module; + { + var non_export_var = 0; + Outer.export_var = 1; + function NonExportFunc() { + return 0; + } + function ExportFunc() { + return 0; + } + Outer.ExportFunc = ExportFunc; + } + var export_var; + Outer.outer_var_export = 0; + function outerFuncExport() { + return 0; + } + Outer.outerFuncExport = outerFuncExport; +})(Outer || (Outer = {})); +Outer.NonExportFunc(); diff --git a/tests/baselines/reference/instancePropertiesInheritedIntoClassType.js b/tests/baselines/reference/instancePropertiesInheritedIntoClassType.js new file mode 100644 index 00000000000..eca12f7b1ae --- /dev/null +++ b/tests/baselines/reference/instancePropertiesInheritedIntoClassType.js @@ -0,0 +1,121 @@ +//// [instancePropertiesInheritedIntoClassType.ts] +module NonGeneric { + class C { + x: string; + get y() { + return 1; + } + set y(v) { } + fn() { return this; } + constructor(public a: number, private b: number) { } + } + + class D extends C { e: string; } + + var d = new D(1, 2); + var r = d.fn(); + var r2 = r.x; + var r3 = r.y; + r.y = 4; + var r6 = d.y(); // error + +} + +module Generic { + class C { + x: T; + get y() { + return null; + } + set y(v: U) { } + fn() { return this; } + constructor(public a: T, private b: U) { } + } + + class D extends C { e: T; } + + var d = new D(1, ''); + var r = d.fn(); + var r2 = r.x; + var r3 = r.y; + r.y = ''; + var r6 = d.y(); // error +} + +//// [instancePropertiesInheritedIntoClassType.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var NonGeneric; +(function (NonGeneric) { + var C = (function () { + function C(a, b) { + this.a = a; + this.b = b; + } + Object.defineProperty(C.prototype, "y", { + get: function () { + return 1; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + C.prototype.fn = function () { + return this; + }; + return C; + })(); + var D = (function (_super) { + __extends(D, _super); + function D() { + _super.apply(this, arguments); + } + return D; + })(C); + var d = new D(1, 2); + var r = d.fn(); + var r2 = r.x; + var r3 = r.y; + r.y = 4; + var r6 = d.y(); // error +})(NonGeneric || (NonGeneric = {})); +var Generic; +(function (Generic) { + var C = (function () { + function C(a, b) { + this.a = a; + this.b = b; + } + Object.defineProperty(C.prototype, "y", { + get: function () { + return null; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + C.prototype.fn = function () { + return this; + }; + return C; + })(); + var D = (function (_super) { + __extends(D, _super); + function D() { + _super.apply(this, arguments); + } + return D; + })(C); + var d = new D(1, ''); + var r = d.fn(); + var r2 = r.x; + var r3 = r.y; + r.y = ''; + var r6 = d.y(); // error +})(Generic || (Generic = {})); diff --git a/tests/baselines/reference/instancePropertyInClassType.js b/tests/baselines/reference/instancePropertyInClassType.js new file mode 100644 index 00000000000..b2df44db6f0 --- /dev/null +++ b/tests/baselines/reference/instancePropertyInClassType.js @@ -0,0 +1,97 @@ +//// [instancePropertyInClassType.ts] +module NonGeneric { + class C { + x: string; + get y() { + return 1; + } + set y(v) { } + fn() { return this; } + constructor(public a: number, private b: number) { } + } + + var c = new C(1, 2); + var r = c.fn(); + var r2 = r.x; + var r3 = r.y; + r.y = 4; + var r6 = c.y(); // error + +} + +module Generic { + class C { + x: T; + get y() { + return null; + } + set y(v: U) { } + fn() { return this; } + constructor(public a: T, private b: U) { } + } + + var c = new C(1, ''); + var r = c.fn(); + var r2 = r.x; + var r3 = r.y; + r.y = ''; + var r6 = c.y(); // error +} + +//// [instancePropertyInClassType.js] +var NonGeneric; +(function (NonGeneric) { + var C = (function () { + function C(a, b) { + this.a = a; + this.b = b; + } + Object.defineProperty(C.prototype, "y", { + get: function () { + return 1; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + C.prototype.fn = function () { + return this; + }; + return C; + })(); + var c = new C(1, 2); + var r = c.fn(); + var r2 = r.x; + var r3 = r.y; + r.y = 4; + var r6 = c.y(); // error +})(NonGeneric || (NonGeneric = {})); +var Generic; +(function (Generic) { + var C = (function () { + function C(a, b) { + this.a = a; + this.b = b; + } + Object.defineProperty(C.prototype, "y", { + get: function () { + return null; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + C.prototype.fn = function () { + return this; + }; + return C; + })(); + var c = new C(1, ''); + var r = c.fn(); + var r2 = r.x; + var r3 = r.y; + r.y = ''; + var r6 = c.y(); // error +})(Generic || (Generic = {})); diff --git a/tests/baselines/reference/instantiateTypeParameter.js b/tests/baselines/reference/instantiateTypeParameter.js new file mode 100644 index 00000000000..7dcf77366bc --- /dev/null +++ b/tests/baselines/reference/instantiateTypeParameter.js @@ -0,0 +1,7 @@ +//// [instantiateTypeParameter.ts] +interface Foo { + var x: T<>; +} + +//// [instantiateTypeParameter.js] +var x; diff --git a/tests/baselines/reference/intTypeCheck.js b/tests/baselines/reference/intTypeCheck.js new file mode 100644 index 00000000000..41f648610b5 --- /dev/null +++ b/tests/baselines/reference/intTypeCheck.js @@ -0,0 +1,348 @@ +//// [intTypeCheck.ts] +interface i1 { + //Property Signatures + p; + p1?; + p2?: string; + p3(); + p4? (); + p5? (): void; + p6(pa1): void; + p7? (pa1, pa2): void; +} +interface i2 { + //Call Signatures + (); + (): number; + (p); + (p1: string); + (p2?: string); + (...p3: any[]); + (p4: string, p5?: string); + (p6: string, ...p7: any[]); +} +interface i3 { + //Construct Signatures + new (); + new (): number; + new (p: string); + new (p2?: string); + new (...p3: any[]); + new (p4: string, p5?: string); + new (p6: string, ...p7: any[]); +} +interface i4 { + // Used to be indexer, now it is a computed property + [p]; + //Index Signatures + [p1: string]; + [p2: string, p3: number]; +} +interface i5 extends i1 { } +interface i6 extends i2 { } +interface i7 extends i3 { } +interface i8 extends i4 { } +interface i9 { } + +class Base { foo() { } } + +interface i11 { + //Call Signatures + (); + (): number; + (p); + (p1: string); + (p2?: string); + (...p3: any[]); + (p4: string, p5?: string); + (p6: string, ...p7: any[]); + //(p8?: string, ...p9: any[]); + //(p10:string, p8?: string, ...p9: any[]); + + //Construct Signatures + new (); + new (): number; + new (p: string); + new (p2?: string); + new (...p3: any[]); + new (p4: string, p5?: string); + new (p6: string, ...p7: any[]); + + // Used to be indexer, now it is a computed property + [p]; + //Index Signatures + [p1: string]; + [p2: string, p3: number]; + + //Property Signatures + p; + p1?; + p2?: string; + p3(); + p4? (); + p5? (): void; + p6(pa1): void; + p7(pa1, pa2): void; + p7? (pa1, pa2): void; +} + +var anyVar: any; +// +// Property signatures +// +var obj0: i1; +var obj1: i1 = { + p: null, + p3: function ():any { return 0; }, + p6: function (pa1):any { return 0; }, + p7: function (pa1, pa2):any { return 0; } +}; +var obj2: i1 = new Object(); +var obj3: i1 = new obj0; +var obj4: i1 = new Base; +var obj5: i1 = null; +var obj6: i1 = function () { }; +//var obj7: i1 = function foo() { }; +var obj8: i1 = anyVar; +var obj9: i1 = new anyVar; +var obj10: i1 = new {}; +// +// Call signatures +// +var obj11: i2; +var obj12: i2 = {}; +var obj13: i2 = new Object(); +var obj14: i2 = new obj11; +var obj15: i2 = new Base; +var obj16: i2 = null; +var obj17: i2 = function ():any { return 0; }; +//var obj18: i2 = function foo() { }; +var obj19: i2 = anyVar; +var obj20: i2 = new anyVar; +var obj21: i2 = new {}; +// +// Construct Signatures +// +var obj22: i3; +var obj23: i3 = {}; +var obj24: i3 = new Object(); +var obj25: i3 = new obj22; +var obj26: i3 = new Base; +var obj27: i3 = null; +var obj28: i3 = function () { }; +//var obj29: i3 = function foo() { }; +var obj30: i3 = anyVar; +var obj31: i3 = new anyVar; +var obj32: i3 = new {}; +// +// Index Signatures +// +var obj33: i4; +var obj34: i4 = {}; +var obj35: i4 = new Object(); +var obj36: i4 = new obj33; +var obj37: i4 = new Base; +var obj38: i4 = null; +var obj39: i4 = function () { }; +//var obj40: i4 = function foo() { }; +var obj41: i4 = anyVar; +var obj42: i4 = new anyVar; +var obj43: i4 = new {}; +// +// Interface Derived I1 +// +var obj44: i5; +var obj45: i5 = {}; +var obj46: i5 = new Object(); +var obj47: i5 = new obj44; +var obj48: i5 = new Base; +var obj49: i5 = null; +var obj50: i5 = function () { }; +//var obj51: i5 = function foo() { }; +var obj52: i5 = anyVar; +var obj53: i5 = new anyVar; +var obj54: i5 = new {}; +// +// Interface Derived I2 +// +var obj55: i6; +var obj56: i6 = {}; +var obj57: i6 = new Object(); +var obj58: i6 = new obj55; +var obj59: i6 = new Base; +var obj60: i6 = null; +var obj61: i6 = function () { }; +//var obj62: i6 = function foo() { }; +var obj63: i6 = anyVar; +var obj64: i6 = new anyVar; +var obj65: i6 = new {}; +// +// Interface Derived I3 +// +var obj66: i7; +var obj67: i7 = {}; +var obj68: i7 = new Object(); +var obj69: i7 = new obj66; +var obj70: i7 = new Base; +var obj71: i7 = null; +var obj72: i7 = function () { }; +//var obj73: i7 = function foo() { }; +var obj74: i7 = anyVar; +var obj75: i7 = new anyVar; +var obj76: i7 = new {}; +// +// Interface Derived I4 +// +var obj77: i8; +var obj78: i8 = {}; +var obj79: i8 = new Object(); +var obj80: i8 = new obj77; +var obj81: i8 = new Base; +var obj82: i8 = null; +var obj83: i8 = function () { }; +//var obj84: i8 = function foo() { }; +var obj85: i8 = anyVar; +var obj86: i8 = new anyVar; +var obj87: i8 = new {}; + +//// [intTypeCheck.js] +var Base = (function () { + function Base() { + } + Base.prototype.foo = function () { + }; + return Base; +})(); +var anyVar; +// +// Property signatures +// +var obj0; +var obj1 = { + p: null, + p3: function () { + return 0; + }, + p6: function (pa1) { + return 0; + }, + p7: function (pa1, pa2) { + return 0; + } +}; +var obj2 = new Object(); +var obj3 = new obj0; +var obj4 = new Base; +var obj5 = null; +var obj6 = function () { +}; +//var obj7: i1 = function foo() { }; +var obj8 = anyVar; +var obj9 = new < i1 > anyVar; +var obj10 = new {}; +// +// Call signatures +// +var obj11; +var obj12 = {}; +var obj13 = new Object(); +var obj14 = new obj11; +var obj15 = new Base; +var obj16 = null; +var obj17 = function () { + return 0; +}; +//var obj18: i2 = function foo() { }; +var obj19 = anyVar; +var obj20 = new < i2 > anyVar; +var obj21 = new {}; +// +// Construct Signatures +// +var obj22; +var obj23 = {}; +var obj24 = new Object(); +var obj25 = new obj22; +var obj26 = new Base; +var obj27 = null; +var obj28 = function () { +}; +//var obj29: i3 = function foo() { }; +var obj30 = anyVar; +var obj31 = new < i3 > anyVar; +var obj32 = new {}; +// +// Index Signatures +// +var obj33; +var obj34 = {}; +var obj35 = new Object(); +var obj36 = new obj33; +var obj37 = new Base; +var obj38 = null; +var obj39 = function () { +}; +//var obj40: i4 = function foo() { }; +var obj41 = anyVar; +var obj42 = new < i4 > anyVar; +var obj43 = new {}; +// +// Interface Derived I1 +// +var obj44; +var obj45 = {}; +var obj46 = new Object(); +var obj47 = new obj44; +var obj48 = new Base; +var obj49 = null; +var obj50 = function () { +}; +//var obj51: i5 = function foo() { }; +var obj52 = anyVar; +var obj53 = new < i5 > anyVar; +var obj54 = new {}; +// +// Interface Derived I2 +// +var obj55; +var obj56 = {}; +var obj57 = new Object(); +var obj58 = new obj55; +var obj59 = new Base; +var obj60 = null; +var obj61 = function () { +}; +//var obj62: i6 = function foo() { }; +var obj63 = anyVar; +var obj64 = new < i6 > anyVar; +var obj65 = new {}; +// +// Interface Derived I3 +// +var obj66; +var obj67 = {}; +var obj68 = new Object(); +var obj69 = new obj66; +var obj70 = new Base; +var obj71 = null; +var obj72 = function () { +}; +//var obj73: i7 = function foo() { }; +var obj74 = anyVar; +var obj75 = new < i7 > anyVar; +var obj76 = new {}; +// +// Interface Derived I4 +// +var obj77; +var obj78 = {}; +var obj79 = new Object(); +var obj80 = new obj77; +var obj81 = new Base; +var obj82 = null; +var obj83 = function () { +}; +//var obj84: i8 = function foo() { }; +var obj85 = anyVar; +var obj86 = new < i8 > anyVar; +var obj87 = new {}; diff --git a/tests/baselines/reference/interfaceDeclaration4.js b/tests/baselines/reference/interfaceDeclaration4.js new file mode 100644 index 00000000000..576479c2beb --- /dev/null +++ b/tests/baselines/reference/interfaceDeclaration4.js @@ -0,0 +1,73 @@ +//// [interfaceDeclaration4.ts] +// Import this module when test harness supports external modules. Also remove the internal module below. +// import Foo = require("interfaceDeclaration5") +module Foo { + export interface I1 { item: string; } + export class C1 { } +} + +class C1 implements Foo.I1 { + public item:string; +} + +// Allowed +interface I2 extends Foo.I1 { + item:string; +} + +// Negative Case +interface I3 extends Foo.I1 { + item:number; +} + +interface I4 extends Foo.I1 { + token:string; +} + +// Err - not implemented item +class C2 implements I4 { + public token: string; +} + +interface I5 extends Foo { } + +// Negative case +interface I6 extends Foo.C1 { } + +class C3 implements Foo.I1 { } + +// Negative case +interface Foo.I1 { } + + +//// [interfaceDeclaration4.js] +// Import this module when test harness supports external modules. Also remove the internal module below. +// import Foo = require("interfaceDeclaration5") +var Foo; +(function (Foo) { + var C1 = (function () { + function C1() { + } + return C1; + })(); + Foo.C1 = C1; +})(Foo || (Foo = {})); +var C1 = (function () { + function C1() { + } + return C1; +})(); +// Err - not implemented item +var C2 = (function () { + function C2() { + } + return C2; +})(); +var C3 = (function () { + function C3() { + } + return C3; +})(); +I1; +{ +} diff --git a/tests/baselines/reference/interfaceExtendingClass.js b/tests/baselines/reference/interfaceExtendingClass.js new file mode 100644 index 00000000000..39db7460915 --- /dev/null +++ b/tests/baselines/reference/interfaceExtendingClass.js @@ -0,0 +1,42 @@ +//// [interfaceExtendingClass.ts] +class Foo { + x: string; + y() { } + get Z() { + return 1; + } + [x: string]: Object; +} + +interface I extends Foo { +} + +var i: I; +var r1 = i.x; +var r2 = i.y(); +var r3 = i.Z; + +var f: Foo = i; +i = f; + +//// [interfaceExtendingClass.js] +var Foo = (function () { + function Foo() { + } + Foo.prototype.y = function () { + }; + Object.defineProperty(Foo.prototype, "Z", { + get: function () { + return 1; + }, + enumerable: true, + configurable: true + }); + return Foo; +})(); +var i; +var r1 = i.x; +var r2 = i.y(); +var r3 = i.Z; +var f = i; +i = f; diff --git a/tests/baselines/reference/interfaceExtendingClass2.js b/tests/baselines/reference/interfaceExtendingClass2.js new file mode 100644 index 00000000000..b0958717aa8 --- /dev/null +++ b/tests/baselines/reference/interfaceExtendingClass2.js @@ -0,0 +1,34 @@ +//// [interfaceExtendingClass2.ts] +class Foo { + x: string; + y() { } + get Z() { + return 1; + } + [x: string]: Object; +} + +interface I2 extends Foo { // error + a: { + toString: () => { + return 1; + }; + } + +//// [interfaceExtendingClass2.js] +var Foo = (function () { + function Foo() { + } + Foo.prototype.y = function () { + }; + Object.defineProperty(Foo.prototype, "Z", { + get: function () { + return 1; + }, + enumerable: true, + configurable: true + }); + return Foo; +})(); +return 1; +; diff --git a/tests/baselines/reference/interfaceImplementation5.js b/tests/baselines/reference/interfaceImplementation5.js new file mode 100644 index 00000000000..667c5f045ec --- /dev/null +++ b/tests/baselines/reference/interfaceImplementation5.js @@ -0,0 +1,110 @@ +//// [interfaceImplementation5.ts] +interface I1 { + getset1:number; +} + +class C1 implements I1 { + public get getset1(){return 1;} +} + +class C2 implements I1 { + public set getset1(baz:number){} +} + +class C3 implements I1 { + public get getset1(){return 1;} + public set getset1(baz:number){} +} + +class C4 implements I1 { + public get getset1(){var x:any; return x;} +} + +class C5 implements I1 { + public set getset1(baz:any){} +} + +class C6 implements I1 { + public set getset1(baz:any){} + public get getset1(){var x:any; return x;} +} + + + +//// [interfaceImplementation5.js] +var C1 = (function () { + function C1() { + } + Object.defineProperty(C1.prototype, "getset1", { + get: function () { + return 1; + }, + enumerable: true, + configurable: true + }); + return C1; +})(); +var C2 = (function () { + function C2() { + } + Object.defineProperty(C2.prototype, "getset1", { + set: function (baz) { + }, + enumerable: true, + configurable: true + }); + return C2; +})(); +var C3 = (function () { + function C3() { + } + Object.defineProperty(C3.prototype, "getset1", { + get: function () { + return 1; + }, + set: function (baz) { + }, + enumerable: true, + configurable: true + }); + return C3; +})(); +var C4 = (function () { + function C4() { + } + Object.defineProperty(C4.prototype, "getset1", { + get: function () { + var x; + return x; + }, + enumerable: true, + configurable: true + }); + return C4; +})(); +var C5 = (function () { + function C5() { + } + Object.defineProperty(C5.prototype, "getset1", { + set: function (baz) { + }, + enumerable: true, + configurable: true + }); + return C5; +})(); +var C6 = (function () { + function C6() { + } + Object.defineProperty(C6.prototype, "getset1", { + get: function () { + var x; + return x; + }, + set: function (baz) { + }, + enumerable: true, + configurable: true + }); + return C6; +})(); diff --git a/tests/baselines/reference/interfaceMayNotBeExtendedWitACall.js b/tests/baselines/reference/interfaceMayNotBeExtendedWitACall.js new file mode 100644 index 00000000000..a283722d6ad --- /dev/null +++ b/tests/baselines/reference/interfaceMayNotBeExtendedWitACall.js @@ -0,0 +1,11 @@ +//// [interfaceMayNotBeExtendedWitACall.ts] +interface color {} + +interface blue extends color() { // error + +} + + +//// [interfaceMayNotBeExtendedWitACall.js] +(function () { +}); diff --git a/tests/baselines/reference/interfaceNaming1.js b/tests/baselines/reference/interfaceNaming1.js new file mode 100644 index 00000000000..e16f186379b --- /dev/null +++ b/tests/baselines/reference/interfaceNaming1.js @@ -0,0 +1,11 @@ +//// [interfaceNaming1.ts] +interface { } +interface interface{ } +interface & { } + + +//// [interfaceNaming1.js] +interface; +{ +} +interface & {}; diff --git a/tests/baselines/reference/interfaceThatInheritsFromItself.js b/tests/baselines/reference/interfaceThatInheritsFromItself.js new file mode 100644 index 00000000000..59794dc40c7 --- /dev/null +++ b/tests/baselines/reference/interfaceThatInheritsFromItself.js @@ -0,0 +1,16 @@ +//// [interfaceThatInheritsFromItself.ts] +interface Foo extends Foo { // error +} + +interface Foo2 extends Foo2 { // error +} + +interface Foo3 extends Foo3 { // error +} + +interface Bar implements Bar { // error +} + + + +//// [interfaceThatInheritsFromItself.js] diff --git a/tests/baselines/reference/interfaceWithAccessibilityModifiers.js b/tests/baselines/reference/interfaceWithAccessibilityModifiers.js new file mode 100644 index 00000000000..bd29d319466 --- /dev/null +++ b/tests/baselines/reference/interfaceWithAccessibilityModifiers.js @@ -0,0 +1,9 @@ +//// [interfaceWithAccessibilityModifiers.ts] +// Errors +interface Foo { + public a: any; + private b: any; + protected c: any; +} + +//// [interfaceWithAccessibilityModifiers.js] diff --git a/tests/baselines/reference/interfaceWithImplements1.js b/tests/baselines/reference/interfaceWithImplements1.js new file mode 100644 index 00000000000..bc8ccba8192 --- /dev/null +++ b/tests/baselines/reference/interfaceWithImplements1.js @@ -0,0 +1,7 @@ +//// [interfaceWithImplements1.ts] +interface IFoo { } + +interface IBar implements IFoo { +} + +//// [interfaceWithImplements1.js] diff --git a/tests/baselines/reference/interfaceWithPrivateMember.js b/tests/baselines/reference/interfaceWithPrivateMember.js new file mode 100644 index 00000000000..24c2cf9ecf5 --- /dev/null +++ b/tests/baselines/reference/interfaceWithPrivateMember.js @@ -0,0 +1,19 @@ +//// [interfaceWithPrivateMember.ts] +// interfaces do not permit private members, these are errors + +interface I { + private x: string; +} + +interface I2 { + private y: T; +} + +var x: { + private y: string; +} + +//// [interfaceWithPrivateMember.js] +// interfaces do not permit private members, these are errors +var x; +y: string; diff --git a/tests/baselines/reference/interfacesWithPredefinedTypesAsNames.js b/tests/baselines/reference/interfacesWithPredefinedTypesAsNames.js new file mode 100644 index 00000000000..b79dfc12a04 --- /dev/null +++ b/tests/baselines/reference/interfacesWithPredefinedTypesAsNames.js @@ -0,0 +1,9 @@ +//// [interfacesWithPredefinedTypesAsNames.ts] +interface any { } +interface number { } +interface string { } +interface boolean { } +interface void {} + +//// [interfacesWithPredefinedTypesAsNames.js] +void {}; diff --git a/tests/baselines/reference/invalidBinaryIntegerLiteralAndOctalIntegerLiteral.js b/tests/baselines/reference/invalidBinaryIntegerLiteralAndOctalIntegerLiteral.js new file mode 100644 index 00000000000..a46af16763d --- /dev/null +++ b/tests/baselines/reference/invalidBinaryIntegerLiteralAndOctalIntegerLiteral.js @@ -0,0 +1,17 @@ +//// [invalidBinaryIntegerLiteralAndOctalIntegerLiteral.ts] +// Error +var binary = 0b21010; +var binary1 = 0B21010; +var octal = 0o81010; +var octal = 0O91010; + +//// [invalidBinaryIntegerLiteralAndOctalIntegerLiteral.js] +// Error +var binary = 0; +21010; +var binary1 = 0; +21010; +var octal = 0; +81010; +var octal = 0; +91010; diff --git a/tests/baselines/reference/invalidDoWhileBreakStatements.js b/tests/baselines/reference/invalidDoWhileBreakStatements.js new file mode 100644 index 00000000000..e6617ef98cd --- /dev/null +++ b/tests/baselines/reference/invalidDoWhileBreakStatements.js @@ -0,0 +1,70 @@ +//// [invalidDoWhileBreakStatements.ts] +// All errors + +// naked break not allowed +break; + +// non-existent label +ONE: +do break TWO; while (true) + +// break from inside function +TWO: +do { + var x = () => { + break TWO; + } +}while (true) + +THREE: +do { + var fn = function () { + break THREE; + } +}while (true) + +// break forward +do { + break FIVE; + FIVE: + do { } while (true) +}while (true) + +// label on non-loop statement +NINE: +var y = 12; + +do { + break NINE; +}while (true) + +//// [invalidDoWhileBreakStatements.js] +// All errors +// naked break not allowed +break; +// non-existent label +ONE: do + break TWO; +while (true); +// break from inside function +TWO: do { + var x = function () { + break TWO; + }; +} while (true); +THREE: do { + var fn = function () { + break THREE; + }; +} while (true); +// break forward +do { + break FIVE; + FIVE: do { + } while (true); +} while (true); +// label on non-loop statement +NINE: var y = 12; +do { + break NINE; +} while (true); diff --git a/tests/baselines/reference/invalidDoWhileContinueStatements.js b/tests/baselines/reference/invalidDoWhileContinueStatements.js new file mode 100644 index 00000000000..d32ccfe0074 --- /dev/null +++ b/tests/baselines/reference/invalidDoWhileContinueStatements.js @@ -0,0 +1,70 @@ +//// [invalidDoWhileContinueStatements.ts] +// All errors + +// naked continue not allowed +continue; + +// non-existent label +ONE: +do continue TWO; while (true) + +// continue from inside function +TWO: +do { + var x = () => { + continue TWO; + } +}while (true) + +THREE: +do { + var fn = function () { + continue THREE; + } +}while (true) + +// continue forward +do { + continue FIVE; + FIVE: + do { } while (true) +}while (true) + +// label on non-loop statement +NINE: +var y = 12; + +do { + continue NINE; +}while (true) + +//// [invalidDoWhileContinueStatements.js] +// All errors +// naked continue not allowed +continue; +// non-existent label +ONE: do + continue TWO; +while (true); +// continue from inside function +TWO: do { + var x = function () { + continue TWO; + }; +} while (true); +THREE: do { + var fn = function () { + continue THREE; + }; +} while (true); +// continue forward +do { + continue FIVE; + FIVE: do { + } while (true); +} while (true); +// label on non-loop statement +NINE: var y = 12; +do { + continue NINE; +} while (true); diff --git a/tests/baselines/reference/invalidForBreakStatements.js b/tests/baselines/reference/invalidForBreakStatements.js new file mode 100644 index 00000000000..abcd078ff2d --- /dev/null +++ b/tests/baselines/reference/invalidForBreakStatements.js @@ -0,0 +1,68 @@ +//// [invalidForBreakStatements.ts] +// All errors + +// naked break not allowed +break; + +// non-existent label +ONE: +for(;;) break TWO; + +// break from inside function +TWO: +for(;;) { + var x = () => { + break TWO; + } +} + +THREE: +for(;;) { + var fn = function () { + break THREE; + } +} + +// break forward +for(;;) { + break FIVE; + FIVE: + for (; ;) { } +} +// label on non-loop statement +NINE: +var y = 12; + +for(;;) { + break NINE; +} + +//// [invalidForBreakStatements.js] +// All errors +// naked break not allowed +break; +// non-existent label +ONE: for (;;) + break TWO; +// break from inside function +TWO: for (;;) { + var x = function () { + break TWO; + }; +} +THREE: for (;;) { + var fn = function () { + break THREE; + }; +} +// break forward +for (;;) { + break FIVE; + FIVE: for (;;) { + } +} +// label on non-loop statement +NINE: var y = 12; +for (;;) { + break NINE; +} diff --git a/tests/baselines/reference/invalidForContinueStatements.js b/tests/baselines/reference/invalidForContinueStatements.js new file mode 100644 index 00000000000..af0eba2a59a --- /dev/null +++ b/tests/baselines/reference/invalidForContinueStatements.js @@ -0,0 +1,68 @@ +//// [invalidForContinueStatements.ts] +// All errors + +// naked continue not allowed +continue; + +// non-existent label +ONE: +for(;;) continue TWO; + +// continue from inside function +TWO: +for(;;) { + var x = () => { + continue TWO; + } +} + +THREE: +for(;;) { + var fn = function () { + continue THREE; + } +} + +// continue forward +for(;;) { + continue FIVE; + FIVE: + for (; ;) { } +} +// label on non-loop statement +NINE: +var y = 12; + +for(;;) { + continue NINE; +} + +//// [invalidForContinueStatements.js] +// All errors +// naked continue not allowed +continue; +// non-existent label +ONE: for (;;) + continue TWO; +// continue from inside function +TWO: for (;;) { + var x = function () { + continue TWO; + }; +} +THREE: for (;;) { + var fn = function () { + continue THREE; + }; +} +// continue forward +for (;;) { + continue FIVE; + FIVE: for (;;) { + } +} +// label on non-loop statement +NINE: var y = 12; +for (;;) { + continue NINE; +} diff --git a/tests/baselines/reference/invalidForInBreakStatements.js b/tests/baselines/reference/invalidForInBreakStatements.js new file mode 100644 index 00000000000..bf383613c3b --- /dev/null +++ b/tests/baselines/reference/invalidForInBreakStatements.js @@ -0,0 +1,69 @@ +//// [invalidForInBreakStatements.ts] +// All errors + +// naked break not allowed +break; + +// non-existent label +ONE: +for (var x in {}) break TWO; + +// break from inside function +TWO: +for (var x in {}) { + var fn = () => { + break TWO; + } +} + +THREE: +for (var x in {}) { + var fn = function () { + break THREE; + } +} + +// break forward +for (var x in {}) { + break FIVE; + FIVE: + for (var x in {}) { } +} + +// label on non-loop statement +NINE: +var y = 12; + +for (var x in {}) { + break NINE; +} + +//// [invalidForInBreakStatements.js] +// All errors +// naked break not allowed +break; +// non-existent label +ONE: for (var x in {}) + break TWO; +// break from inside function +TWO: for (var x in {}) { + var fn = function () { + break TWO; + }; +} +THREE: for (var x in {}) { + var fn = function () { + break THREE; + }; +} +// break forward +for (var x in {}) { + break FIVE; + FIVE: for (var x in {}) { + } +} +// label on non-loop statement +NINE: var y = 12; +for (var x in {}) { + break NINE; +} diff --git a/tests/baselines/reference/invalidForInContinueStatements.js b/tests/baselines/reference/invalidForInContinueStatements.js new file mode 100644 index 00000000000..d40dbd80ca0 --- /dev/null +++ b/tests/baselines/reference/invalidForInContinueStatements.js @@ -0,0 +1,69 @@ +//// [invalidForInContinueStatements.ts] +// All errors + +// naked continue not allowed +continue; + +// non-existent label +ONE: +for (var x in {}) continue TWO; + +// continue from inside function +TWO: +for (var x in {}) { + var fn = () => { + continue TWO; + } +} + +THREE: +for (var x in {}) { + var fn = function () { + continue THREE; + } +} + +// continue forward +for (var x in {}) { + continue FIVE; + FIVE: + for (var x in {}) { } +} + +// label on non-loop statement +NINE: +var y = 12; + +for (var x in {}) { + continue NINE; +} + +//// [invalidForInContinueStatements.js] +// All errors +// naked continue not allowed +continue; +// non-existent label +ONE: for (var x in {}) + continue TWO; +// continue from inside function +TWO: for (var x in {}) { + var fn = function () { + continue TWO; + }; +} +THREE: for (var x in {}) { + var fn = function () { + continue THREE; + }; +} +// continue forward +for (var x in {}) { + continue FIVE; + FIVE: for (var x in {}) { + } +} +// label on non-loop statement +NINE: var y = 12; +for (var x in {}) { + continue NINE; +} diff --git a/tests/baselines/reference/invalidModuleWithStatementsOfEveryKind.js b/tests/baselines/reference/invalidModuleWithStatementsOfEveryKind.js new file mode 100644 index 00000000000..077d7ddbcdc --- /dev/null +++ b/tests/baselines/reference/invalidModuleWithStatementsOfEveryKind.js @@ -0,0 +1,235 @@ +//// [invalidModuleWithStatementsOfEveryKind.ts] +// All of these should be an error + +module Y { + public class A { s: string } + + public class BB extends A { + id: number; + } +} + +module Y2 { + public class AA { s: T } + public interface I { id: number } + + public class B extends AA implements I { id: number } +} + +module Y3 { + public module Module { + class A { s: string } + } +} + +module Y4 { + public enum Color { Blue, Red } +} + +module YY { + private class A { s: string } + + private class BB extends A { + id: number; + } +} + +module YY2 { + private class AA { s: T } + private interface I { id: number } + + private class B extends AA implements I { id: number } +} + +module YY3 { + private module Module { + class A { s: string } + } +} + +module YY4 { + private enum Color { Blue, Red } +} + + +module YYY { + static class A { s: string } + + static class BB extends A { + id: number; + } +} + +module YYY2 { + static class AA { s: T } + static interface I { id: number } + + static class B extends AA implements I { id: number } +} + +module YYY3 { + static module Module { + class A { s: string } + } +} + +module YYY4 { + static enum Color { Blue, Red } +} + + +//// [invalidModuleWithStatementsOfEveryKind.js] +// All of these should be an error +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var Y; +(function (Y) { + var A = (function () { + function A() { + } + return A; + })(); + var BB = (function (_super) { + __extends(BB, _super); + function BB() { + _super.apply(this, arguments); + } + return BB; + })(A); +})(Y || (Y = {})); +var Y2; +(function (Y2) { + var AA = (function () { + function AA() { + } + return AA; + })(); + var B = (function (_super) { + __extends(B, _super); + function B() { + _super.apply(this, arguments); + } + return B; + })(AA); +})(Y2 || (Y2 = {})); +var Y3; +(function (Y3) { + var Module; + (function (Module) { + var A = (function () { + function A() { + } + return A; + })(); + })(Module || (Module = {})); +})(Y3 || (Y3 = {})); +var Y4; +(function (Y4) { + var Color; + (function (Color) { + Color[Color["Blue"] = 0] = "Blue"; + Color[Color["Red"] = 1] = "Red"; + })(Color || (Color = {})); +})(Y4 || (Y4 = {})); +var YY; +(function (YY) { + var A = (function () { + function A() { + } + return A; + })(); + var BB = (function (_super) { + __extends(BB, _super); + function BB() { + _super.apply(this, arguments); + } + return BB; + })(A); +})(YY || (YY = {})); +var YY2; +(function (YY2) { + var AA = (function () { + function AA() { + } + return AA; + })(); + var B = (function (_super) { + __extends(B, _super); + function B() { + _super.apply(this, arguments); + } + return B; + })(AA); +})(YY2 || (YY2 = {})); +var YY3; +(function (YY3) { + var Module; + (function (Module) { + var A = (function () { + function A() { + } + return A; + })(); + })(Module || (Module = {})); +})(YY3 || (YY3 = {})); +var YY4; +(function (YY4) { + var Color; + (function (Color) { + Color[Color["Blue"] = 0] = "Blue"; + Color[Color["Red"] = 1] = "Red"; + })(Color || (Color = {})); +})(YY4 || (YY4 = {})); +var YYY; +(function (YYY) { + var A = (function () { + function A() { + } + return A; + })(); + var BB = (function (_super) { + __extends(BB, _super); + function BB() { + _super.apply(this, arguments); + } + return BB; + })(A); +})(YYY || (YYY = {})); +var YYY2; +(function (YYY2) { + var AA = (function () { + function AA() { + } + return AA; + })(); + var B = (function (_super) { + __extends(B, _super); + function B() { + _super.apply(this, arguments); + } + return B; + })(AA); +})(YYY2 || (YYY2 = {})); +var YYY3; +(function (YYY3) { + var Module; + (function (Module) { + var A = (function () { + function A() { + } + return A; + })(); + })(Module || (Module = {})); +})(YYY3 || (YYY3 = {})); +var YYY4; +(function (YYY4) { + var Color; + (function (Color) { + Color[Color["Blue"] = 0] = "Blue"; + Color[Color["Red"] = 1] = "Red"; + })(Color || (Color = {})); +})(YYY4 || (YYY4 = {})); diff --git a/tests/baselines/reference/invalidModuleWithVarStatements.js b/tests/baselines/reference/invalidModuleWithVarStatements.js new file mode 100644 index 00000000000..4014709d361 --- /dev/null +++ b/tests/baselines/reference/invalidModuleWithVarStatements.js @@ -0,0 +1,58 @@ +//// [invalidModuleWithVarStatements.ts] +// All of these should be an error + +module Y { + public var x: number = 0; +} + +module Y2 { + public function fn(x: string) { } +} + +module Y4 { + static var x: number = 0; +} + +module YY { + static function fn(x: string) { } +} + +module YY2 { + private var x: number = 0; +} + + +module YY3 { + private function fn(x: string) { } +} + + +//// [invalidModuleWithVarStatements.js] +// All of these should be an error +var Y; +(function (Y) { + var x = 0; +})(Y || (Y = {})); +var Y2; +(function (Y2) { + function fn(x) { + } +})(Y2 || (Y2 = {})); +var Y4; +(function (Y4) { + var x = 0; +})(Y4 || (Y4 = {})); +var YY; +(function (YY) { + function fn(x) { + } +})(YY || (YY = {})); +var YY2; +(function (YY2) { + var x = 0; +})(YY2 || (YY2 = {})); +var YY3; +(function (YY3) { + function fn(x) { + } +})(YY3 || (YY3 = {})); diff --git a/tests/baselines/reference/invalidReferenceSyntax1.js b/tests/baselines/reference/invalidReferenceSyntax1.js new file mode 100644 index 00000000000..39ecf8e6ab4 --- /dev/null +++ b/tests/baselines/reference/invalidReferenceSyntax1.js @@ -0,0 +1,13 @@ +//// [invalidReferenceSyntax1.ts] +/// +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/invalidSwitchContinueStatement.js b/tests/baselines/reference/invalidSwitchContinueStatement.js new file mode 100644 index 00000000000..759056ce3e5 --- /dev/null +++ b/tests/baselines/reference/invalidSwitchContinueStatement.js @@ -0,0 +1,15 @@ +//// [invalidSwitchContinueStatement.ts] +// continue is not allowed in a switch statement + +switch (12) { + case 5: + continue; +} + + +//// [invalidSwitchContinueStatement.js] +// continue is not allowed in a switch statement +switch (12) { + case 5: + continue; +} diff --git a/tests/baselines/reference/invalidThrowStatement.js b/tests/baselines/reference/invalidThrowStatement.js new file mode 100644 index 00000000000..4b794ab3d51 --- /dev/null +++ b/tests/baselines/reference/invalidThrowStatement.js @@ -0,0 +1,9 @@ +//// [invalidThrowStatement.ts] +throw; + +export throw null; + + +//// [invalidThrowStatement.js] +throw ; +throw null; diff --git a/tests/baselines/reference/invalidTripleSlashReference.js b/tests/baselines/reference/invalidTripleSlashReference.js new file mode 100644 index 00000000000..c0dcec0d23c --- /dev/null +++ b/tests/baselines/reference/invalidTripleSlashReference.js @@ -0,0 +1,12 @@ +//// [invalidTripleSlashReference.ts] +/// +/// + +// this test doesn't actually give the errors you want due to the way the compiler reports errors +var x = 1; + +//// [invalidTripleSlashReference.js] +/// +/// +// this test doesn't actually give the errors you want due to the way the compiler reports errors +var x = 1; diff --git a/tests/baselines/reference/invalidTryStatements.js b/tests/baselines/reference/invalidTryStatements.js new file mode 100644 index 00000000000..8afadf41b4d --- /dev/null +++ b/tests/baselines/reference/invalidTryStatements.js @@ -0,0 +1,36 @@ +//// [invalidTryStatements.ts] +function fn() { + try { + } catch (x) { + var x: string; // ensure x is 'Any' + } + + // no type annotation allowed + try { } catch (z: any) { } + try { } catch (a: number) { } + try { } catch (y: string) { } +} + + + +//// [invalidTryStatements.js] +function fn() { + try { + } + catch (x) { + var x; // ensure x is 'Any' + } + // no type annotation allowed + try { + } + catch (z) { + } + try { + } + catch (a) { + } + try { + } + catch (y) { + } +} diff --git a/tests/baselines/reference/invalidTryStatements2.js b/tests/baselines/reference/invalidTryStatements2.js new file mode 100644 index 00000000000..d2ef92ac831 --- /dev/null +++ b/tests/baselines/reference/invalidTryStatements2.js @@ -0,0 +1,68 @@ +//// [invalidTryStatements2.ts] +function fn() { + try { + } catch { // syntax error, missing '(x)' + } + + catch(x) { } // error missing try + + finally{ } // potential error; can be absorbed by the 'catch' +} + +function fn2() { + finally { } // error missing try + catch (x) { } // error missing try + + // no error + try { + } + finally { + } + + // error missing try + finally { + } + + // error missing try + catch (x) { + } +} + +//// [invalidTryStatements2.js] +function fn() { + try { + } + catch () { + } + try { + } + catch (x) { + } // error missing try + finally { + } // potential error; can be absorbed by the 'catch' +} +function fn2() { + try { + } + finally { + } // error missing try + try { + } // error missing try + catch (x) { + } // error missing try + // no error + try { + } + finally { + } + // error missing try + try { + } + finally { + } + // error missing try + try { + } + catch (x) { + } +} diff --git a/tests/baselines/reference/invalidTypeOfTarget.js b/tests/baselines/reference/invalidTypeOfTarget.js new file mode 100644 index 00000000000..88128d15e85 --- /dev/null +++ b/tests/baselines/reference/invalidTypeOfTarget.js @@ -0,0 +1,20 @@ +//// [invalidTypeOfTarget.ts] +var x1: typeof {}; +var x2: typeof (): void; +var x3: typeof 1; +var x4: typeof ''; +var x5: typeof []; +var x6: typeof null; +var x7: typeof function f() { }; +var x8: typeof /123/; + +//// [invalidTypeOfTarget.js] +var x1 = {}; +var x2 = ; +var x3 = 1; +var x4 = ''; +var x5; +var x6 = null; +var x7 = function f() { +}; +var x8 = /123/; diff --git a/tests/baselines/reference/invalidUnicodeEscapeSequance.js b/tests/baselines/reference/invalidUnicodeEscapeSequance.js new file mode 100644 index 00000000000..06c7af443e0 --- /dev/null +++ b/tests/baselines/reference/invalidUnicodeEscapeSequance.js @@ -0,0 +1,5 @@ +//// [invalidUnicodeEscapeSequance.ts] +var arg\u003 + +//// [invalidUnicodeEscapeSequance.js] +var arg, u003; diff --git a/tests/baselines/reference/invalidUnicodeEscapeSequance2.js b/tests/baselines/reference/invalidUnicodeEscapeSequance2.js new file mode 100644 index 00000000000..06714db3f7e --- /dev/null +++ b/tests/baselines/reference/invalidUnicodeEscapeSequance2.js @@ -0,0 +1,5 @@ +//// [invalidUnicodeEscapeSequance2.ts] +var arg\uxxxx + +//// [invalidUnicodeEscapeSequance2.js] +var arg, uxxxx; diff --git a/tests/baselines/reference/invalidUnicodeEscapeSequance3.js b/tests/baselines/reference/invalidUnicodeEscapeSequance3.js new file mode 100644 index 00000000000..b6b0307bbe6 --- /dev/null +++ b/tests/baselines/reference/invalidUnicodeEscapeSequance3.js @@ -0,0 +1,6 @@ +//// [invalidUnicodeEscapeSequance3.ts] +a\u + +//// [invalidUnicodeEscapeSequance3.js] +a; +u; diff --git a/tests/baselines/reference/invalidUnicodeEscapeSequance4.js b/tests/baselines/reference/invalidUnicodeEscapeSequance4.js new file mode 100644 index 00000000000..014ebb6eead --- /dev/null +++ b/tests/baselines/reference/invalidUnicodeEscapeSequance4.js @@ -0,0 +1,7 @@ +//// [invalidUnicodeEscapeSequance4.ts] +var a\u0031; // a1 is a valid identifier +var \u0031a; // 1a is an invalid identifier + +//// [invalidUnicodeEscapeSequance4.js] +var a\u0031; // a1 is a valid identifier +var u0031a; // 1a is an invalid identifier diff --git a/tests/baselines/reference/invalidWhileBreakStatements.js b/tests/baselines/reference/invalidWhileBreakStatements.js new file mode 100644 index 00000000000..a8e261f036c --- /dev/null +++ b/tests/baselines/reference/invalidWhileBreakStatements.js @@ -0,0 +1,69 @@ +//// [invalidWhileBreakStatements.ts] +// All errors + +// naked break not allowed +break; + +// non-existent label +ONE: +while (true) break TWO; + +// break from inside function +TWO: +while (true){ + var x = () => { + break TWO; + } +} + +THREE: +while (true) { + var fn = function () { + break THREE; + } +} + +// break forward +while (true) { + break FIVE; + FIVE: + while (true) { } +} + +// label on non-loop statement +NINE: +var y = 12; + +while (true) { + break NINE; +} + +//// [invalidWhileBreakStatements.js] +// All errors +// naked break not allowed +break; +// non-existent label +ONE: while (true) + break TWO; +// break from inside function +TWO: while (true) { + var x = function () { + break TWO; + }; +} +THREE: while (true) { + var fn = function () { + break THREE; + }; +} +// break forward +while (true) { + break FIVE; + FIVE: while (true) { + } +} +// label on non-loop statement +NINE: var y = 12; +while (true) { + break NINE; +} diff --git a/tests/baselines/reference/invalidWhileContinueStatements.js b/tests/baselines/reference/invalidWhileContinueStatements.js new file mode 100644 index 00000000000..544314bf68d --- /dev/null +++ b/tests/baselines/reference/invalidWhileContinueStatements.js @@ -0,0 +1,69 @@ +//// [invalidWhileContinueStatements.ts] +// All errors + +// naked continue not allowed +continue; + +// non-existent label +ONE: +while (true) continue TWO; + +// continue from inside function +TWO: +while (true){ + var x = () => { + continue TWO; + } +} + +THREE: +while (true) { + var fn = function () { + continue THREE; + } +} + +// continue forward +while (true) { + continue FIVE; + FIVE: + while (true) { } +} + +// label on non-loop statement +NINE: +var y = 12; + +while (true) { + continue NINE; +} + +//// [invalidWhileContinueStatements.js] +// All errors +// naked continue not allowed +continue; +// non-existent label +ONE: while (true) + continue TWO; +// continue from inside function +TWO: while (true) { + var x = function () { + continue TWO; + }; +} +THREE: while (true) { + var fn = function () { + continue THREE; + }; +} +// continue forward +while (true) { + continue FIVE; + FIVE: while (true) { + } +} +// label on non-loop statement +NINE: var y = 12; +while (true) { + continue NINE; +} diff --git a/tests/baselines/reference/letAsIdentifierInStrictMode.js b/tests/baselines/reference/letAsIdentifierInStrictMode.js new file mode 100644 index 00000000000..e844bc1d1dc --- /dev/null +++ b/tests/baselines/reference/letAsIdentifierInStrictMode.js @@ -0,0 +1,17 @@ +//// [letAsIdentifierInStrictMode.ts] +"use strict"; +var let = 10; +var a = 10; +let = 30; +let +a; + +//// [letAsIdentifierInStrictMode.js] +"use strict"; +var ; +let ; +10; +var a = 10; +let ; +30; +let a; diff --git a/tests/baselines/reference/letDeclarations-es5-1.js b/tests/baselines/reference/letDeclarations-es5-1.js new file mode 100644 index 00000000000..24c2c62e58f --- /dev/null +++ b/tests/baselines/reference/letDeclarations-es5-1.js @@ -0,0 +1,15 @@ +//// [letDeclarations-es5-1.ts] + let l1; + let l2: number; + let l3, l4, l5 :string, l6; + let l7 = false; + let l8: number = 23; + let l9 = 0, l10 :string = "", l11 = null; + +//// [letDeclarations-es5-1.js] +let l1; +let l2; +let l3, l4, l5, l6; +let l7 = false; +let l8 = 23; +let l9 = 0, l10 = "", l11 = null; diff --git a/tests/baselines/reference/letDeclarations-es5.js b/tests/baselines/reference/letDeclarations-es5.js new file mode 100644 index 00000000000..d5d1d96d350 --- /dev/null +++ b/tests/baselines/reference/letDeclarations-es5.js @@ -0,0 +1,26 @@ +//// [letDeclarations-es5.ts] + +let l1; +let l2: number; +let l3, l4, l5 :string, l6; + +let l7 = false; +let l8: number = 23; +let l9 = 0, l10 :string = "", l11 = null; + +for(let l11 in {}) { } + +for(let l12 = 0; l12 < 9; l12++) { } + + +//// [letDeclarations-es5.js] +let l1; +let l2; +let l3, l4, l5, l6; +let l7 = false; +let l8 = 23; +let l9 = 0, l10 = "", l11 = null; +for (let l11 in {}) { +} +for (let l12 = 0; l12 < 9; l12++) { +} diff --git a/tests/baselines/reference/letDeclarations-invalidContexts.js b/tests/baselines/reference/letDeclarations-invalidContexts.js new file mode 100644 index 00000000000..f8c3bb04bdb --- /dev/null +++ b/tests/baselines/reference/letDeclarations-invalidContexts.js @@ -0,0 +1,57 @@ +//// [letDeclarations-invalidContexts.ts] + +// Errors, let must be defined inside a block +if (true) + let l1 = 0; +else + let l2 = 0; + +while (true) + let l3 = 0; + +do + let l4 = 0; +while (true); + +var obj; +with (obj) + let l5 = 0; + +for (var i = 0; i < 10; i++) + let l6 = 0; + +for (var i2 in {}) + let l7 = 0; + +if (true) + label: let l8 = 0; + +while (false) + label2: label3: label4: let l9 = 0; + + + + + +//// [letDeclarations-invalidContexts.js] +// Errors, let must be defined inside a block +if (true) + let l1 = 0; +else + let l2 = 0; +while (true) + let l3 = 0; +do + let l4 = 0; +while (true); +var obj; +with (obj) + let l5 = 0; +for (var i = 0; i < 10; i++) + let l6 = 0; +for (var i2 in {}) + let l7 = 0; +if (true) + label: let l8 = 0; +while (false) + label2: label3: label4: let l9 = 0; diff --git a/tests/baselines/reference/letDeclarations-scopes-duplicates.js b/tests/baselines/reference/letDeclarations-scopes-duplicates.js new file mode 100644 index 00000000000..c7d2ef9863a --- /dev/null +++ b/tests/baselines/reference/letDeclarations-scopes-duplicates.js @@ -0,0 +1,140 @@ +//// [letDeclarations-scopes-duplicates.ts] + +// Errors: redeclaration +let var1 = 0; +let var1 = 0; // error + +let var2 = 0; +const var2 = 0; + +const var3 = 0; +let var3 = 0; + +const var4 = 0; +const var4 = 0; + +var var5 = 0; +let var5 = 0; + +let var6 = 0; +var var6 = 0; + +{ + let var7 = 0; + let var7 = 0; + { + let var8 = 0; + const var8 = 0; + } +} + +switch (0) { + default: + let var9 = 0; + let var9 = 0; +} + +try { + const var10 = 0; + const var10 = 0; +} +catch (e) { + let var11 = 0; + let var11 = 0; +} + +function F1() { + let var12; + let var12; +} + +// OK +var var20 = 0; + +var var20 = 0 +{ + let var20 = 0; + { + let var20 = 0; + } +} + +switch (0) { + default: + let var20 = 0; +} + +try { + let var20 = 0; +} +catch (e) { + let var20 = 0; +} + +function F() { + let var20; +} + + + +//// [letDeclarations-scopes-duplicates.js] +// Errors: redeclaration +let var1 = 0; +let var1 = 0; // error +let var2 = 0; +const var2 = 0; +const var3 = 0; +let var3 = 0; +const var4 = 0; +const var4 = 0; +var var5 = 0; +let var5 = 0; +let var6 = 0; +var var6 = 0; +{ + let var7 = 0; + let var7 = 0; + { + let var8 = 0; + const var8 = 0; + } +} +switch (0) { + default: + let var9 = 0; + let var9 = 0; +} +try { + const var10 = 0; + const var10 = 0; +} +catch (e) { + let var11 = 0; + let var11 = 0; +} +function F1() { + let var12; + let var12; +} +// OK +var var20 = 0; +var var20 = 0; +{ + let var20 = 0; + { + let var20 = 0; + } +} +switch (0) { + default: + let var20 = 0; +} +try { + let var20 = 0; +} +catch (e) { + let var20 = 0; +} +function F() { + let var20; +} diff --git a/tests/baselines/reference/letDeclarations-scopes-duplicates2.js b/tests/baselines/reference/letDeclarations-scopes-duplicates2.js new file mode 100644 index 00000000000..9b35bd81c76 --- /dev/null +++ b/tests/baselines/reference/letDeclarations-scopes-duplicates2.js @@ -0,0 +1,13 @@ +//// [tests/cases/compiler/letDeclarations-scopes-duplicates2.ts] //// + +//// [file1.ts] + +let var1 = 0; + +//// [file2.ts] +let var1 = 0; + +//// [file1.js] +let var1 = 0; +//// [file2.js] +let var1 = 0; diff --git a/tests/baselines/reference/letDeclarations-scopes-duplicates3.js b/tests/baselines/reference/letDeclarations-scopes-duplicates3.js new file mode 100644 index 00000000000..e74caf37219 --- /dev/null +++ b/tests/baselines/reference/letDeclarations-scopes-duplicates3.js @@ -0,0 +1,13 @@ +//// [tests/cases/compiler/letDeclarations-scopes-duplicates3.ts] //// + +//// [file1.ts] + +let var1 = 0; + +//// [file2.ts] +const var1 = 0; + +//// [file1.js] +let var1 = 0; +//// [file2.js] +const var1 = 0; diff --git a/tests/baselines/reference/letDeclarations-scopes-duplicates4.js b/tests/baselines/reference/letDeclarations-scopes-duplicates4.js new file mode 100644 index 00000000000..ac338e31c72 --- /dev/null +++ b/tests/baselines/reference/letDeclarations-scopes-duplicates4.js @@ -0,0 +1,13 @@ +//// [tests/cases/compiler/letDeclarations-scopes-duplicates4.ts] //// + +//// [file1.ts] + +const var1 = 0; + +//// [file2.ts] +let var1 = 0; + +//// [file1.js] +const var1 = 0; +//// [file2.js] +let var1 = 0; diff --git a/tests/baselines/reference/letDeclarations-scopes-duplicates5.js b/tests/baselines/reference/letDeclarations-scopes-duplicates5.js new file mode 100644 index 00000000000..2424c91ab90 --- /dev/null +++ b/tests/baselines/reference/letDeclarations-scopes-duplicates5.js @@ -0,0 +1,13 @@ +//// [tests/cases/compiler/letDeclarations-scopes-duplicates5.ts] //// + +//// [file1.ts] + +const var1 = 0; + +//// [file2.ts] +const var1 = 0; + +//// [file1.js] +const var1 = 0; +//// [file2.js] +const var1 = 0; diff --git a/tests/baselines/reference/letDeclarations-scopes-duplicates6.js b/tests/baselines/reference/letDeclarations-scopes-duplicates6.js new file mode 100644 index 00000000000..24edc0b7bde --- /dev/null +++ b/tests/baselines/reference/letDeclarations-scopes-duplicates6.js @@ -0,0 +1,13 @@ +//// [tests/cases/compiler/letDeclarations-scopes-duplicates6.ts] //// + +//// [file1.ts] + +var var1 = 0; + +//// [file2.ts] +let var1 = 0; + +//// [file1.js] +var var1 = 0; +//// [file2.js] +let var1 = 0; diff --git a/tests/baselines/reference/letDeclarations-scopes-duplicates7.js b/tests/baselines/reference/letDeclarations-scopes-duplicates7.js new file mode 100644 index 00000000000..4cbc359e2c2 --- /dev/null +++ b/tests/baselines/reference/letDeclarations-scopes-duplicates7.js @@ -0,0 +1,13 @@ +//// [tests/cases/compiler/letDeclarations-scopes-duplicates7.ts] //// + +//// [file1.ts] + +let var1 = 0; + +//// [file2.ts] +var var1 = 0; + +//// [file1.js] +let var1 = 0; +//// [file2.js] +var var1 = 0; diff --git a/tests/baselines/reference/letDeclarations-scopes.js b/tests/baselines/reference/letDeclarations-scopes.js index dbe18311eff..fc721807994 100644 --- a/tests/baselines/reference/letDeclarations-scopes.js +++ b/tests/baselines/reference/letDeclarations-scopes.js @@ -239,7 +239,7 @@ function F() { let l = 0; n = l; } -var F2 = function () { +var F2 = () => { let l = 0; n = l; }; @@ -289,7 +289,7 @@ var o = { let l = 0; n = l; }, - f2: function () { + f2: () => { let l = 0; n = l; } diff --git a/tests/baselines/reference/letDeclarations-useBeforeDefinition.js b/tests/baselines/reference/letDeclarations-useBeforeDefinition.js new file mode 100644 index 00000000000..be1f9a127f4 --- /dev/null +++ b/tests/baselines/reference/letDeclarations-useBeforeDefinition.js @@ -0,0 +1,24 @@ +//// [letDeclarations-useBeforeDefinition.ts] + +{ + l1; + let l1; +} + +var v1; +{ + v1; + let v1 = 0; +} + + +//// [letDeclarations-useBeforeDefinition.js] +{ + l1; + let l1; +} +var v1; +{ + v1; + let v1 = 0; +} diff --git a/tests/baselines/reference/letDeclarations-useBeforeDefinition2.js b/tests/baselines/reference/letDeclarations-useBeforeDefinition2.js new file mode 100644 index 00000000000..35560edd1c8 --- /dev/null +++ b/tests/baselines/reference/letDeclarations-useBeforeDefinition2.js @@ -0,0 +1,12 @@ +//// [tests/cases/compiler/letDeclarations-useBeforeDefinition2.ts] //// + +//// [file1.ts] + +l; + +//// [file2.ts] +const l = 0; + +//// [out.js] +l; +const l = 0; diff --git a/tests/baselines/reference/letDeclarations-validContexts.js b/tests/baselines/reference/letDeclarations-validContexts.js index ee821794b12..f6d404135f6 100644 --- a/tests/baselines/reference/letDeclarations-validContexts.js +++ b/tests/baselines/reference/letDeclarations-validContexts.js @@ -206,7 +206,7 @@ let l18 = 0; function F() { let l19 = 0; } -var F2 = function () { +var F2 = () => { let l20 = 0; }; var F3 = function () { @@ -246,7 +246,7 @@ var o = { f() { let l28 = 0; }, - f2: function () { + f2: () => { let l29 = 0; } }; diff --git a/tests/baselines/reference/libMembers.js b/tests/baselines/reference/libMembers.js new file mode 100644 index 00000000000..38d1356ccc3 --- /dev/null +++ b/tests/baselines/reference/libMembers.js @@ -0,0 +1,36 @@ +//// [libMembers.ts] +var s="hello"; +s.substring(0); +s.substring(3,4); +s.subby(12); // error unresolved +String.fromCharCode(12); +module M { + export class C { + } + var a=new C[]; + a.length; + a.push(new C()); + (new C()).prototype; +} + + + +//// [libMembers.js] +var s = "hello"; +s.substring(0); +s.substring(3, 4); +s.subby(12); // error unresolved +String.fromCharCode(12); +var M; +(function (M) { + var C = (function () { + function C() { + } + return C; + })(); + M.C = C; + var a = new C[]; + a.length; + a.push(new C()); + (new C()).prototype; +})(M || (M = {})); diff --git a/tests/baselines/reference/literals.js b/tests/baselines/reference/literals.js new file mode 100644 index 00000000000..b92e11c13ce --- /dev/null +++ b/tests/baselines/reference/literals.js @@ -0,0 +1,74 @@ +//// [literals.ts] + +//typeof null is Null +//typeof true is Boolean +//typeof false is Boolean +//typeof numeric literal is Number +//typeof string literal is String +//typeof regex literal is Regex + +var nu = null / null; +var u = undefined / undefined; + +var b: boolean; +var b = true; +var b = false; + +var n: number; +var n = 1; +var n = 1.0; +var n = 1e4; +var n = 001; // Error in ES5 +var n = 0x1; +var n = -1; +var n = -1.0; +var n = -1e-4; +var n = -003; // Error in ES5 +var n = -0x1; + +var s: string; +var s = ''; +var s = ""; +var s = 'foo\ + bar'; +var s = "foo\ + bar"; + +var r: RegExp; +var r = /what/; +var r = /\\\\/; + + +//// [literals.js] +//typeof null is Null +//typeof true is Boolean +//typeof false is Boolean +//typeof numeric literal is Number +//typeof string literal is String +//typeof regex literal is Regex +var nu = null / null; +var u = undefined / undefined; +var b; +var b = true; +var b = false; +var n; +var n = 1; +var n = 1.0; +var n = 1e4; +var n = 001; // Error in ES5 +var n = 0x1; +var n = -1; +var n = -1.0; +var n = -1e-4; +var n = -003; // Error in ES5 +var n = -0x1; +var s; +var s = ''; +var s = ""; +var s = 'foo\ + bar'; +var s = "foo\ + bar"; +var r; +var r = /what/; +var r = /\\\\/; diff --git a/tests/baselines/reference/logicalNotOperatorInvalidOperations.js b/tests/baselines/reference/logicalNotOperatorInvalidOperations.js new file mode 100644 index 00000000000..7b16f2ef36f --- /dev/null +++ b/tests/baselines/reference/logicalNotOperatorInvalidOperations.js @@ -0,0 +1,23 @@ +//// [logicalNotOperatorInvalidOperations.ts] +// Unary operator ! +var b: number; + +// operand before ! +var BOOLEAN1 = b!; //expect error + +// miss parentheses +var BOOLEAN2 = !b + b; + +// miss an operand +var BOOLEAN3 =!; + +//// [logicalNotOperatorInvalidOperations.js] +// Unary operator ! +var b; +// operand before ! +var BOOLEAN1 = b; +!; //expect error +// miss parentheses +var BOOLEAN2 = !b + b; +// miss an operand +var BOOLEAN3 = !; diff --git a/tests/baselines/reference/mergedModuleDeclarationCodeGen.js b/tests/baselines/reference/mergedModuleDeclarationCodeGen.js new file mode 100644 index 00000000000..88b949dd920 --- /dev/null +++ b/tests/baselines/reference/mergedModuleDeclarationCodeGen.js @@ -0,0 +1,42 @@ +//// [mergedModuleDeclarationCodeGen.ts] +export module X { + export module Y { + class A { + constructor(Y: any) { + new B(); + } + } + } +} +export module X { + export module Y { + export class B { + } + } +} + +//// [mergedModuleDeclarationCodeGen.js] +var X; +(function (X) { + var Y; + (function (_Y) { + var A = (function () { + function A(Y) { + new _Y.B(); + } + return A; + })(); + })(Y = X.Y || (X.Y = {})); +})(X = exports.X || (exports.X = {})); +var X; +(function (X) { + var Y; + (function (Y) { + var B = (function () { + function B() { + } + return B; + })(); + Y.B = B; + })(Y = X.Y || (X.Y = {})); +})(X = exports.X || (exports.X = {})); diff --git a/tests/baselines/reference/methodInAmbientClass1.js b/tests/baselines/reference/methodInAmbientClass1.js new file mode 100644 index 00000000000..73b79b3464c --- /dev/null +++ b/tests/baselines/reference/methodInAmbientClass1.js @@ -0,0 +1,7 @@ +//// [methodInAmbientClass1.ts] + declare class Foo { + fn(): boolean { + } + } + +//// [methodInAmbientClass1.js] diff --git a/tests/baselines/reference/missingArgument1.js b/tests/baselines/reference/missingArgument1.js new file mode 100644 index 00000000000..eed0d9b11d6 --- /dev/null +++ b/tests/baselines/reference/missingArgument1.js @@ -0,0 +1,5 @@ +//// [missingArgument1.ts] +foo(a,,b); + +//// [missingArgument1.js] +foo(a, , b); diff --git a/tests/baselines/reference/modifierOnParameter1.js b/tests/baselines/reference/modifierOnParameter1.js new file mode 100644 index 00000000000..69b54a09384 --- /dev/null +++ b/tests/baselines/reference/modifierOnParameter1.js @@ -0,0 +1,11 @@ +//// [modifierOnParameter1.ts] +class C { + constructor(declare p) { } +} + +//// [modifierOnParameter1.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/modifiersOnInterfaceIndexSignature1.js b/tests/baselines/reference/modifiersOnInterfaceIndexSignature1.js new file mode 100644 index 00000000000..1e91071e36a --- /dev/null +++ b/tests/baselines/reference/modifiersOnInterfaceIndexSignature1.js @@ -0,0 +1,6 @@ +//// [modifiersOnInterfaceIndexSignature1.ts] +interface I { + public [a: string]: number; +} + +//// [modifiersOnInterfaceIndexSignature1.js] diff --git a/tests/baselines/reference/moduleKeywordRepeatError.js b/tests/baselines/reference/moduleKeywordRepeatError.js new file mode 100644 index 00000000000..8ec656f22ae --- /dev/null +++ b/tests/baselines/reference/moduleKeywordRepeatError.js @@ -0,0 +1,10 @@ +//// [moduleKeywordRepeatError.ts] +// "module.module { }" should raise a syntax error + +module.module { } + +//// [moduleKeywordRepeatError.js] +// "module.module { }" should raise a syntax error +module.module; +{ +} diff --git a/tests/baselines/reference/moduleProperty1.js b/tests/baselines/reference/moduleProperty1.js new file mode 100644 index 00000000000..3848203a66f --- /dev/null +++ b/tests/baselines/reference/moduleProperty1.js @@ -0,0 +1,26 @@ +//// [moduleProperty1.ts] +module M { + var x=10; // variable local to this module body + var y=x; // property visible only in module + export var z=y; // property visible to any code +} + +module M2 { + var x = 10; // variable local to this module body + private y = x; // can't use private in modules + export var z = y; // property visible to any code +} + +//// [moduleProperty1.js] +var M; +(function (M) { + var x = 10; // variable local to this module body + var y = x; // property visible only in module + M.z = y; // property visible to any code +})(M || (M = {})); +var M2; +(function (M2) { + var x = 10; // variable local to this module body + y = x; // can't use private in modules + M2.z = y; // property visible to any code +})(M2 || (M2 = {})); diff --git a/tests/baselines/reference/moduleScoping.js b/tests/baselines/reference/moduleScoping.js new file mode 100644 index 00000000000..cbe435e570c --- /dev/null +++ b/tests/baselines/reference/moduleScoping.js @@ -0,0 +1,40 @@ +//// [tests/cases/conformance/externalModules/moduleScoping.ts] //// + +//// [file1.ts] +var v1 = "sausages"; // Global scope + +//// [file2.ts] +var v2 = 42; // Global scope +var v4 = () => 5; + +//// [file3.ts] +export var v3 = true; +var v2 = [1,2,3]; // Module scope. Should not appear in global scope + +//// [file4.ts] +import file3 = require('./file3'); +var t1 = v1; +var t2 = v2; +var t3 = file3.v3; +var v4 = {a: true, b: NaN}; // Should shadow global v2 in this module + +//// [file5.ts] +var x = v2; // Should be global v2 of type number again + + +//// [file1.js] +var v1 = "sausages"; // Global scope +//// [file2.js] +var v2 = 42; // Global scope +var v4 = function () { return 5; }; +//// [file3.js] +exports.v3 = true; +var v2 = [1, 2, 3]; // Module scope. Should not appear in global scope +//// [file4.js] +var file3 = require('./file3'); +var t1 = v1; +var t2 = v2; +var t3 = file3.v3; +var v4 = { a: true, b: NaN }; // Should shadow global v2 in this module +//// [file5.js] +var x = v2; // Should be global v2 of type number again diff --git a/tests/baselines/reference/moduledecl.js b/tests/baselines/reference/moduledecl.js new file mode 100644 index 00000000000..9be1b116a5e --- /dev/null +++ b/tests/baselines/reference/moduledecl.js @@ -0,0 +1,378 @@ +//// [moduledecl.ts] +module a { +} + +module b.a { +} + +module c.a.b { + import ma = a; +} + +module mImport { + import d = a; + import e = b.a; + import d1 = a; + import e1 = b.a; +} + +module m0 { + function f1() { + } + + function f2(s: string); + function f2(n: number); + function f2(ns: any) { + } + + class c1 { + public a : ()=>string; + private b: ()=>number; + private static s1; + public static s2; + } + + interface i1 { + () : Object; + [n: number]: c1; + } + + import m2 = a; + import m3 = b; + import m4 = b.a; + import m5 = c; + import m6 = c.a; + import m7 = c.a.b; +} + +module m1 { + export function f1() { + } + + export function f2(s: string); + export function f2(n: number); + export function f2(ns: any) { + } + + export class c1 { + public a: () =>string; + private b: () =>number; + private static s1; + public static s2; + + public d() { + return "Hello"; + } + + public e: { x: number; y: string; }; + constructor (public n, public n2: number, private n3, private n4: string) { + } + } + + export interface i1 { + () : Object; + [n: number]: c1; + } + + import m2 = a; + import m3 = b; + import m4 = b.a; + import m5 = c; + import m6 = c.a; + import m7 = c.a.b; +} + +module m { + export module m2 { + var a = 10; + export var b: number; + } + + export module m3 { + export var c: number; + } +} + +module m { + + export module m25 { + export module m5 { + export var c: number; + } + } +} + +module m13 { + export module m4 { + export module m2 { + export module m3 { + export var c: number; + } + } + + export function f() { + return 20; + } + } +} + +declare module m4 { + export var b; +} + +declare module m5 { + export var c; +} + +declare module m43 { + export var b; +} + +declare module m55 { + export var c; +} + +declare module "m3" { + export var b: number; +} + +module exportTests { + export class C1_public { + private f2() { + return 30; + } + + public f3() { + return "string"; + } + } + class C2_private { + private f2() { + return 30; + } + + public f3() { + return "string"; + } + } + + export class C3_public { + private getC2_private() { + return new C2_private(); + } + private setC2_private(arg: C2_private) { + } + private get c2() { + return new C2_private(); + } + public getC1_public() { + return new C1_public(); + } + public setC1_public(arg: C1_public) { + } + public get c1() { + return new C1_public(); + } + } +} + +declare module mAmbient { + class C { + public myProp: number; + } + + function foo() : C; + var aVar: C; + interface B { + x: number; + y: C; + } + enum e { + x, + y, + z + } + + module m3 { + class C { + public myProp: number; + } + + function foo(): C; + var aVar: C; + interface B { + x: number; + y: C; + } + enum e { + x, + y, + z + } + } +} + +function foo() { + return mAmbient.foo(); +} + +var cVar = new mAmbient.C(); +var aVar = mAmbient.aVar; +var bB: mAmbient.B; +var eVar: mAmbient.e; + +function m3foo() { + return mAmbient.m3.foo(); +} + +var m3cVar = new mAmbient.m3.C(); +var m3aVar = mAmbient.m3.aVar; +var m3bB: mAmbient.m3.B; +var m3eVar: mAmbient.m3.e; + + + +//// [moduledecl.js] +var m0; +(function (m0) { + function f1() { + } + function f2(ns) { + } + var c1 = (function () { + function c1() { + } + return c1; + })(); +})(m0 || (m0 = {})); +var m1; +(function (m1) { + function f1() { + } + m1.f1 = f1; + function f2(ns) { + } + m1.f2 = f2; + var c1 = (function () { + function c1(n, n2, n3, n4) { + this.n = n; + this.n2 = n2; + this.n3 = n3; + this.n4 = n4; + } + c1.prototype.d = function () { + return "Hello"; + }; + return c1; + })(); + m1.c1 = c1; +})(m1 || (m1 = {})); +var m; +(function (m) { + var m2; + (function (m2) { + var a = 10; + m2.b; + })(m2 = m.m2 || (m.m2 = {})); + var m3; + (function (m3) { + m3.c; + })(m3 = m.m3 || (m.m3 = {})); +})(m || (m = {})); +var m; +(function (m) { + var m25; + (function (m25) { + var m5; + (function (m5) { + m5.c; + })(m5 = m25.m5 || (m25.m5 = {})); + })(m25 = m.m25 || (m.m25 = {})); +})(m || (m = {})); +var m13; +(function (m13) { + var m4; + (function (m4) { + var m2; + (function (m2) { + var m3; + (function (m3) { + m3.c; + })(m3 = m2.m3 || (m2.m3 = {})); + })(m2 = m4.m2 || (m4.m2 = {})); + function f() { + return 20; + } + m4.f = f; + })(m4 = m13.m4 || (m13.m4 = {})); +})(m13 || (m13 = {})); +var exportTests; +(function (exportTests) { + var C1_public = (function () { + function C1_public() { + } + C1_public.prototype.f2 = function () { + return 30; + }; + C1_public.prototype.f3 = function () { + return "string"; + }; + return C1_public; + })(); + exportTests.C1_public = C1_public; + var C2_private = (function () { + function C2_private() { + } + C2_private.prototype.f2 = function () { + return 30; + }; + C2_private.prototype.f3 = function () { + return "string"; + }; + return C2_private; + })(); + var C3_public = (function () { + function C3_public() { + } + C3_public.prototype.getC2_private = function () { + return new C2_private(); + }; + C3_public.prototype.setC2_private = function (arg) { + }; + Object.defineProperty(C3_public.prototype, "c2", { + get: function () { + return new C2_private(); + }, + enumerable: true, + configurable: true + }); + C3_public.prototype.getC1_public = function () { + return new C1_public(); + }; + C3_public.prototype.setC1_public = function (arg) { + }; + Object.defineProperty(C3_public.prototype, "c1", { + get: function () { + return new C1_public(); + }, + enumerable: true, + configurable: true + }); + return C3_public; + })(); + exportTests.C3_public = C3_public; +})(exportTests || (exportTests = {})); +function foo() { + return mAmbient.foo(); +} +var cVar = new mAmbient.C(); +var aVar = mAmbient.aVar; +var bB; +var eVar; +function m3foo() { + return mAmbient.m3.foo(); +} +var m3cVar = new mAmbient.m3.C(); +var m3aVar = mAmbient.m3.aVar; +var m3bB; +var m3eVar; diff --git a/tests/baselines/reference/multipleClassPropertyModifiers.js b/tests/baselines/reference/multipleClassPropertyModifiers.js new file mode 100644 index 00000000000..7dec786c447 --- /dev/null +++ b/tests/baselines/reference/multipleClassPropertyModifiers.js @@ -0,0 +1,14 @@ +//// [multipleClassPropertyModifiers.ts] +class C { + public static p1; + static public p2; + private static p3; + static private p4; +} + +//// [multipleClassPropertyModifiers.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/multipleClassPropertyModifiersErrors.js b/tests/baselines/reference/multipleClassPropertyModifiersErrors.js new file mode 100644 index 00000000000..191476e9a62 --- /dev/null +++ b/tests/baselines/reference/multipleClassPropertyModifiersErrors.js @@ -0,0 +1,17 @@ +//// [multipleClassPropertyModifiersErrors.ts] +class C { + public public p1; + private private p2; + static static p3; + public private p4; + private public p5; + public static p6; + private static p7; +} + +//// [multipleClassPropertyModifiersErrors.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/multipleInheritance.js b/tests/baselines/reference/multipleInheritance.js new file mode 100644 index 00000000000..9cab77f3dba --- /dev/null +++ b/tests/baselines/reference/multipleInheritance.js @@ -0,0 +1,121 @@ +//// [multipleInheritance.ts] +class B1 { + public x; +} + +class B2 { + public x; +} + +class C extends B1, B2 { // duplicate member +} + +class D1 extends B1 { +} + +class D2 extends B2 { +} + +class E extends D1, D2 { // nope, duplicate member +} + +class N { + public y:number; +} + +class ND extends N { // any is assignable to number + public y; +} + +class Good { + public f:() => number = function() { return 0; } + public g() { return 0; } +} + +class Baad extends Good { + public f(): number { return 0; } + public g(n:number) { return 0; } +} + + +//// [multipleInheritance.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var B1 = (function () { + function B1() { + } + return B1; +})(); +var B2 = (function () { + function B2() { + } + return B2; +})(); +var C = (function (_super) { + __extends(C, _super); + function C() { + _super.apply(this, arguments); + } + return C; +})(B1); +var D1 = (function (_super) { + __extends(D1, _super); + function D1() { + _super.apply(this, arguments); + } + return D1; +})(B1); +var D2 = (function (_super) { + __extends(D2, _super); + function D2() { + _super.apply(this, arguments); + } + return D2; +})(B2); +var E = (function (_super) { + __extends(E, _super); + function E() { + _super.apply(this, arguments); + } + return E; +})(D1); +var N = (function () { + function N() { + } + return N; +})(); +var ND = (function (_super) { + __extends(ND, _super); + function ND() { + _super.apply(this, arguments); + } + return ND; +})(N); +var Good = (function () { + function Good() { + this.f = function () { + return 0; + }; + } + Good.prototype.g = function () { + return 0; + }; + return Good; +})(); +var Baad = (function (_super) { + __extends(Baad, _super); + function Baad() { + _super.apply(this, arguments); + } + Baad.prototype.f = function () { + return 0; + }; + Baad.prototype.g = function (n) { + return 0; + }; + return Baad; +})(Good); diff --git a/tests/baselines/reference/negateOperatorInvalidOperations.js b/tests/baselines/reference/negateOperatorInvalidOperations.js new file mode 100644 index 00000000000..d7aa6154eb2 --- /dev/null +++ b/tests/baselines/reference/negateOperatorInvalidOperations.js @@ -0,0 +1,25 @@ +//// [negateOperatorInvalidOperations.ts] +// Unary operator - + +// operand before - +var NUMBER1 = var NUMBER-; //expect error + +// invalid expressions +var NUMBER2 = -(null - undefined); +var NUMBER3 = -(null - null); +var NUMBER4 = -(undefined - undefined); + +// miss operand +var NUMBER =-; + +//// [negateOperatorInvalidOperations.js] +// Unary operator - +// operand before - +var NUMBER1 = ; +var NUMBER = -; //expect error +// invalid expressions +var NUMBER2 = -(null - undefined); +var NUMBER3 = -(null - null); +var NUMBER4 = -(undefined - undefined); +// miss operand +var NUMBER = -; diff --git a/tests/baselines/reference/nestedClassDeclaration.js b/tests/baselines/reference/nestedClassDeclaration.js new file mode 100644 index 00000000000..c7f0ffe34fc --- /dev/null +++ b/tests/baselines/reference/nestedClassDeclaration.js @@ -0,0 +1,42 @@ +//// [nestedClassDeclaration.ts] +// nested classes are not allowed + +class C { + x: string; + class C2 { + } +} + +function foo() { + class C3 { + } +} + +var x = { + class C4 { + } +} + + +//// [nestedClassDeclaration.js] +// nested classes are not allowed +var C = (function () { + function C() { + } + return C; +})(); +var C2 = (function () { + function C2() { + } + return C2; +})(); +function foo() { +} +var C3 = (function () { + function C3() { + } + return C3; +})(); +var x = { + class: C4 +}, _a = void 0; diff --git a/tests/baselines/reference/newExpressionWithCast.js b/tests/baselines/reference/newExpressionWithCast.js new file mode 100644 index 00000000000..6ce025a4267 --- /dev/null +++ b/tests/baselines/reference/newExpressionWithCast.js @@ -0,0 +1,29 @@ +//// [newExpressionWithCast.ts] + +function Test() { } +// valid but error with noImplicitAny +var test = new Test(); + +function Test2() { } +// parse error +var test2 = new Test2(); + +function Test3() { } +// valid with noImplicitAny +var test3 = new (Test3)(); + + + +//// [newExpressionWithCast.js] +function Test() { +} +// valid but error with noImplicitAny +var test = new Test(); +function Test2() { +} +// parse error +var test2 = new < any > Test2(); +function Test3() { +} +// valid with noImplicitAny +var test3 = new Test3(); diff --git a/tests/baselines/reference/newMissingIdentifier.js b/tests/baselines/reference/newMissingIdentifier.js new file mode 100644 index 00000000000..0b19a8d187b --- /dev/null +++ b/tests/baselines/reference/newMissingIdentifier.js @@ -0,0 +1,6 @@ +//// [newMissingIdentifier.ts] +var x = new (); + + +//// [newMissingIdentifier.js] +var x = new (); diff --git a/tests/baselines/reference/newOperator.js b/tests/baselines/reference/newOperator.js new file mode 100644 index 00000000000..95dc410142e --- /dev/null +++ b/tests/baselines/reference/newOperator.js @@ -0,0 +1,92 @@ +//// [newOperator.ts] +interface ifc { } +// Attempting to 'new' an interface yields poor error +var i = new ifc(); + +// Parens are optional +var x = new Date; +var y = new Date(); + +// Target is not a class or var, good error +var t1 = new 53(); +var t2 = new ''(); +new string; + +// Use in LHS of expression? +(new Date()).toString(); + +// Various spacing +var t3 = new string[]( ); +var t4 = +new +string +[ + ] + ( + ); + +// Unresolved symbol +var f = new q(); + +// not legal +var t5 = new new Date; + +// Can be an expression +new String; + + +module M { + export class T { + x: number; + } +} + +class S { + public get xs(): M.T[] { + return new M.T[]; + } +} + + +//// [newOperator.js] +// Attempting to 'new' an interface yields poor error +var i = new ifc(); +// Parens are optional +var x = new Date; +var y = new Date(); +// Target is not a class or var, good error +var t1 = new 53(); +var t2 = new ''(); +new string; +// Use in LHS of expression? +(new Date()).toString(); +// Various spacing +var t3 = new string[](); +var t4 = new string[](); +// Unresolved symbol +var f = new q(); +// not legal +var t5 = new new Date; +// Can be an expression +new String; +var M; +(function (M) { + var T = (function () { + function T() { + } + return T; + })(); + M.T = T; +})(M || (M = {})); +var S = (function () { + function S() { + } + Object.defineProperty(S.prototype, "xs", { + get: function () { + return new M.T[]; + }, + enumerable: true, + configurable: true + }); + return S; +})(); diff --git a/tests/baselines/reference/newOperatorErrorCases.js b/tests/baselines/reference/newOperatorErrorCases.js new file mode 100644 index 00000000000..8a44d51fb5c --- /dev/null +++ b/tests/baselines/reference/newOperatorErrorCases.js @@ -0,0 +1,71 @@ +//// [newOperatorErrorCases.ts] + +class C0 { + +} +class C1 { + constructor(n: number, s: string) { } +} + +class T { + constructor(n?: T) { } +} + +var anyCtor: { + new (): any; +}; + +var anyCtor1: { + new (n): any; +}; + +interface nestedCtor { + new (): nestedCtor; +} +var nestedCtor: nestedCtor; + +// Construct expression with no parentheses for construct signature with > 0 parameters +var b = new C0 32, ''; // Parse error + +// Generic construct expression with no parentheses +var c1 = new T; +var c1: T<{}>; +var c2 = new T; // Parse error + + +// Construct expression of non-void returning function +function fnNumber(): number { return 32; } +var s = new fnNumber(); // Error + + +//// [newOperatorErrorCases.js] +var C0 = (function () { + function C0() { + } + return C0; +})(); +var C1 = (function () { + function C1(n, s) { + } + return C1; +})(); +var T = (function () { + function T(n) { + } + return T; +})(); +var anyCtor; +var anyCtor1; +var nestedCtor; +// Construct expression with no parentheses for construct signature with > 0 parameters +var b = new C0; +32, ''; // Parse error +// Generic construct expression with no parentheses +var c1 = new T; +var c1; +var c2 = new T(); // Parse error +// Construct expression of non-void returning function +function fnNumber() { + return 32; +} +var s = new fnNumber(); // Error diff --git a/tests/baselines/reference/noCollisionThisExpressionAndLocalVarInAccessors.js b/tests/baselines/reference/noCollisionThisExpressionAndLocalVarInAccessors.js new file mode 100644 index 00000000000..727b1b6087a --- /dev/null +++ b/tests/baselines/reference/noCollisionThisExpressionAndLocalVarInAccessors.js @@ -0,0 +1,98 @@ +//// [noCollisionThisExpressionAndLocalVarInAccessors.ts] +class class1 { + get a(): number { + var x2 = { + doStuff: (callback) => () => { + var _this = 2; + return callback(_this); + } + } + + return 10; + } + set a(val: number) { + var x2 = { + doStuff: (callback) => () => { + var _this = 2; + return callback(_this); + } + } + + } +} + +class class2 { + get a(): number { + var _this = 2; + var x2 = { + doStuff: (callback) => () => { + return callback(_this); + } + } + + return 10; + } + set a(val: number) { + var _this = 2; + var x2 = { + doStuff: (callback) => () => { + return callback(_this); + } + } + + } +} + +//// [noCollisionThisExpressionAndLocalVarInAccessors.js] +var class1 = (function () { + function class1() { + } + Object.defineProperty(class1.prototype, "a", { + get: function () { + var x2 = { + doStuff: function (callback) { return function () { + var _this = 2; + return callback(_this); + }; } + }; + return 10; + }, + set: function (val) { + var x2 = { + doStuff: function (callback) { return function () { + var _this = 2; + return callback(_this); + }; } + }; + }, + enumerable: true, + configurable: true + }); + return class1; +})(); +var class2 = (function () { + function class2() { + } + Object.defineProperty(class2.prototype, "a", { + get: function () { + var _this = 2; + var x2 = { + doStuff: function (callback) { return function () { + return callback(_this); + }; } + }; + return 10; + }, + set: function (val) { + var _this = 2; + var x2 = { + doStuff: function (callback) { return function () { + return callback(_this); + }; } + }; + }, + enumerable: true, + configurable: true + }); + return class2; +})(); diff --git a/tests/baselines/reference/numLit.js b/tests/baselines/reference/numLit.js new file mode 100644 index 00000000000..aaec91cde5d --- /dev/null +++ b/tests/baselines/reference/numLit.js @@ -0,0 +1,12 @@ +//// [numLit.ts] +1..toString(); +1.0.toString(); +1.toString(); +1.+2.0 + 3. ; + +//// [numLit.js] +1..toString(); +1.0.toString(); +1.; +toString(); +1. + 2.0 + 3.; diff --git a/tests/baselines/reference/numericIndexerConstrainsPropertyDeclarations.js b/tests/baselines/reference/numericIndexerConstrainsPropertyDeclarations.js new file mode 100644 index 00000000000..339f674b9da --- /dev/null +++ b/tests/baselines/reference/numericIndexerConstrainsPropertyDeclarations.js @@ -0,0 +1,151 @@ +//// [numericIndexerConstrainsPropertyDeclarations.ts] +// String indexer types constrain the types of named properties in their containing type + +interface MyNumber extends Number { + foo: number; +} + +class C { + [x: number]: string; + + constructor() { } // ok + + a: string; // ok + b: number; // ok + c: () => {} // ok + "d": string; // ok + "e": number; // ok + 1.0: string; // ok + 2.0: number; // error + "3.0": string; // ok + "4.0": number; // error + 3.0: MyNumber // error + + get X() { // ok + return ''; + } + set X(v) { } // ok + + foo() { + return ''; + } + + static sa: number; // ok + static sb: string; // ok + + static foo() { } // ok + static get X() { // ok + return 1; + } +} + +interface I { + [x: number]: string; + + a: string; // ok + b: number; // ok + c: () => {} // ok + "d": string; // ok + "e": number; // ok + 1.0: string; // ok + 2.0: number; // error + (): string; // ok + (x): number // ok + foo(): string; // ok + "3.0": string; // ok + "4.0": number; // error + f: MyNumber; // error +} + +var a: { + [x: number]: string; + + a: string; // ok + b: number; // ok + c: () => {} // ok + "d": string; // ok + "e": number; // ok + 1.0: string; // ok + 2.0: number; // error + (): string; // ok + (x): number // ok + foo(): string; // ok + "3.0": string; // ok + "4.0": number; // error + f: MyNumber; // error +} + +// error +var b: { [x: number]: string; } = { + a: '', + b: 1, + c: () => { }, + "d": '', + "e": 1, + 1.0: '', + 2.0: 1, + "3.0": '', + "4.0": 1, + f: null, + + get X() { + return ''; + }, + set X(v) { }, + foo() { + return ''; + } +} + +//// [numericIndexerConstrainsPropertyDeclarations.js] +// String indexer types constrain the types of named properties in their containing type +var C = (function () { + function C() { + } // ok + Object.defineProperty(C.prototype, "X", { + get: function () { + return ''; + }, + set: function (v) { + } // ok + , + enumerable: true, + configurable: true + }); + C.prototype.foo = function () { + return ''; + }; + C.foo = function () { + }; // ok + Object.defineProperty(C, "X", { + get: function () { + return 1; + }, + enumerable: true, + configurable: true + }); + return C; +})(); +var a; +// error +var b = { + a: '', + b: 1, + c: function () { + }, + "d": '', + "e": 1, + 1.0: '', + 2.0: 1, + "3.0": '', + "4.0": 1, + f: null, + get X() { + return ''; + }, + set X(v) { + }, + foo: function () { + return ''; + } +}; diff --git a/tests/baselines/reference/numericNamedPropertyDuplicates.js b/tests/baselines/reference/numericNamedPropertyDuplicates.js new file mode 100644 index 00000000000..e4340d629ea --- /dev/null +++ b/tests/baselines/reference/numericNamedPropertyDuplicates.js @@ -0,0 +1,34 @@ +//// [numericNamedPropertyDuplicates.ts] +class C { + 1: number; + 1.0: number; + static 2: number; + static 2: number; +} + +interface I { + 2: number; + 2.: number; +} + +var a: { + 1: number; + 1: number; +} + +var b = { + 2: 1 + 2: 1 +} + +//// [numericNamedPropertyDuplicates.js] +var C = (function () { + function C() { + } + return C; +})(); +var a; +var b = { + 2: 1, + 2: 1 +}; diff --git a/tests/baselines/reference/objectCreationExpressionInFunctionParameter.js b/tests/baselines/reference/objectCreationExpressionInFunctionParameter.js new file mode 100644 index 00000000000..55ac0c530e6 --- /dev/null +++ b/tests/baselines/reference/objectCreationExpressionInFunctionParameter.js @@ -0,0 +1,18 @@ +//// [objectCreationExpressionInFunctionParameter.ts] +class A { + constructor(public a1: string) { + } +} +function foo(x = new A(123)) { //should error, 123 is not string +}} + +//// [objectCreationExpressionInFunctionParameter.js] +var A = (function () { + function A(a1) { + this.a1 = a1; + } + return A; +})(); +function foo(x) { + if (x === void 0) { x = new A(123); } +} diff --git a/tests/baselines/reference/objectLitArrayDeclNoNew.js b/tests/baselines/reference/objectLitArrayDeclNoNew.js new file mode 100644 index 00000000000..a52ff55fc4d --- /dev/null +++ b/tests/baselines/reference/objectLitArrayDeclNoNew.js @@ -0,0 +1,49 @@ +//// [objectLitArrayDeclNoNew.ts] +declare var console; +"use strict"; +module Test { + export interface IState { + } + + export interface IToken { + } + + export interface ILineTokens { + tokens: IToken[]; + endState: IState; + } + + export class Gar { + public moo: number = 0; + } + + export function bug(): ILineTokens { + var state:IState= null; + return { + tokens: Gar[],//IToken[], // Missing new. Correct syntax is: tokens: new IToken[] + endState: state + }; + } + } +} + +//// [objectLitArrayDeclNoNew.js] +"use strict"; +var Test; +(function (Test) { + var Gar = (function () { + function Gar() { + this.moo = 0; + } + return Gar; + })(); + Test.Gar = Gar; + function bug() { + var state = null; + return { + tokens: Gar[], + endState: state + }; + } + Test.bug = bug; +})(Test || (Test = {})); diff --git a/tests/baselines/reference/objectLitPropertyScoping.js b/tests/baselines/reference/objectLitPropertyScoping.js new file mode 100644 index 00000000000..b9615081e3f --- /dev/null +++ b/tests/baselines/reference/objectLitPropertyScoping.js @@ -0,0 +1,33 @@ +//// [objectLitPropertyScoping.ts] +// Should compile, x and y should not be picked up from the properties + +function makePoint(x: number, y: number) { + return { + get x() { + return x; + }, + get y() { + return y; + }, + dist: function () { + return Math.sqrt(x * x + y * y); + } + } +}; + +//// [objectLitPropertyScoping.js] +// Should compile, x and y should not be picked up from the properties +function makePoint(x, y) { + return { + get x() { + return x; + }, + get y() { + return y; + }, + dist: function () { + return Math.sqrt(x * x + y * y); + } + }; +} +; diff --git a/tests/baselines/reference/objectLiteralErrors.js b/tests/baselines/reference/objectLiteralErrors.js new file mode 100644 index 00000000000..2a72e8a2a77 --- /dev/null +++ b/tests/baselines/reference/objectLiteralErrors.js @@ -0,0 +1,138 @@ +//// [objectLiteralErrors.ts] + +// Multiple properties with the same name +var e1 = { a: 0, a: 0 }; +var e2 = { a: '', a: '' }; +var e3 = { a: 0, a: '' }; +var e4 = { a: true, a: false }; +var e5 = { a: {}, a: {} }; +var e6 = { a: 0, 'a': 0 }; +var e7 = { 'a': 0, a: 0 }; +var e8 = { 'a': 0, "a": 0 }; +var e9 = { 'a': 0, 'a': 0 }; +var e10 = { "a": 0, 'a': 0 }; +var e11 = { 1.0: 0, '1': 0 }; +var e12 = { 0: 0, 0: 0 }; +var e13 = { 0: 0, 0: 0 }; +var e14 = { 0: 0, 0x0: 0 }; +var e14 = { 0: 0, 000: 0 }; +var e15 = { "100": 0, 1e2: 0 }; +var e16 = { 0x20: 0, 3.2e1: 0 }; +var e17 = { a: 0, b: 1, a: 0 }; + +// Accessor and property with the same name +var f1 = { a: 0, get a() { return 0; } }; +var f2 = { a: '', get a() { return ''; } }; +var f3 = { a: 0, get a() { return ''; } }; +var f4 = { a: true, get a() { return false; } }; +var f5 = { a: {}, get a() { return {}; } }; +var f6 = { a: 0, get 'a'() { return 0; } }; +var f7 = { 'a': 0, get a() { return 0; } }; +var f8 = { 'a': 0, get "a"() { return 0; } }; +var f9 = { 'a': 0, get 'a'() { return 0; } }; +var f10 = { "a": 0, get 'a'() { return 0; } }; +var f11 = { 1.0: 0, get '1'() { return 0; } }; +var f12 = { 0: 0, get 0() { return 0; } }; +var f13 = { 0: 0, get 0() { return 0; } }; +var f14 = { 0: 0, get 0x0() { return 0; } }; +var f14 = { 0: 0, get 000() { return 0; } }; +var f15 = { "100": 0, get 1e2() { return 0; } }; +var f16 = { 0x20: 0, get 3.2e1() { return 0; } }; +var f17 = { a: 0, get b() { return 1; }, get a() { return 0; } }; + +// Get and set accessor with mismatched type annotations +var g1 = { get a(): number { return 4; }, set a(n: string) { } }; +var g2 = { get a() { return 4; }, set a(n: string) { } }; +var g3 = { get a(): number { return undefined; }, set a(n: string) { } }; + + +//// [objectLiteralErrors.js] +// Multiple properties with the same name +var e1 = { a: 0, a: 0 }; +var e2 = { a: '', a: '' }; +var e3 = { a: 0, a: '' }; +var e4 = { a: true, a: false }; +var e5 = { a: {}, a: {} }; +var e6 = { a: 0, 'a': 0 }; +var e7 = { 'a': 0, a: 0 }; +var e8 = { 'a': 0, "a": 0 }; +var e9 = { 'a': 0, 'a': 0 }; +var e10 = { "a": 0, 'a': 0 }; +var e11 = { 1.0: 0, '1': 0 }; +var e12 = { 0: 0, 0: 0 }; +var e13 = { 0: 0, 0: 0 }; +var e14 = { 0: 0, 0x0: 0 }; +var e14 = { 0: 0, 000: 0 }; +var e15 = { "100": 0, 1e2: 0 }; +var e16 = { 0x20: 0, 3.2e1: 0 }; +var e17 = { a: 0, b: 1, a: 0 }; +// Accessor and property with the same name +var f1 = { a: 0, get a() { + return 0; +} }; +var f2 = { a: '', get a() { + return ''; +} }; +var f3 = { a: 0, get a() { + return ''; +} }; +var f4 = { a: true, get a() { + return false; +} }; +var f5 = { a: {}, get a() { + return {}; +} }; +var f6 = { a: 0, get 'a'() { + return 0; +} }; +var f7 = { 'a': 0, get a() { + return 0; +} }; +var f8 = { 'a': 0, get "a"() { + return 0; +} }; +var f9 = { 'a': 0, get 'a'() { + return 0; +} }; +var f10 = { "a": 0, get 'a'() { + return 0; +} }; +var f11 = { 1.0: 0, get '1'() { + return 0; +} }; +var f12 = { 0: 0, get 0() { + return 0; +} }; +var f13 = { 0: 0, get 0() { + return 0; +} }; +var f14 = { 0: 0, get 0x0() { + return 0; +} }; +var f14 = { 0: 0, get 000() { + return 0; +} }; +var f15 = { "100": 0, get 1e2() { + return 0; +} }; +var f16 = { 0x20: 0, get 3.2e1() { + return 0; +} }; +var f17 = { a: 0, get b() { + return 1; +}, get a() { + return 0; +} }; +// Get and set accessor with mismatched type annotations +var g1 = { get a() { + return 4; +}, set a(n) { +} }; +var g2 = { get a() { + return 4; +}, set a(n) { +} }; +var g3 = { get a() { + return undefined; +}, set a(n) { +} }; diff --git a/tests/baselines/reference/objectLiteralErrorsES3.js b/tests/baselines/reference/objectLiteralErrorsES3.js new file mode 100644 index 00000000000..5b98da0039d --- /dev/null +++ b/tests/baselines/reference/objectLiteralErrorsES3.js @@ -0,0 +1,18 @@ +//// [objectLiteralErrorsES3.ts] + +var e1 = { get a() { return 4; } }; +var e2 = { set a(n) { } }; +var e3 = { get a() { return ''; }, set a(n) { } }; + + + +//// [objectLiteralErrorsES3.js] +var e1 = { get a() { + return 4; +} }; +var e2 = { set a(n) { +} }; +var e3 = { get a() { + return ''; +}, set a(n) { +} }; diff --git a/tests/baselines/reference/objectLiteralGettersAndSetters.js b/tests/baselines/reference/objectLiteralGettersAndSetters.js new file mode 100644 index 00000000000..b602650ef8d --- /dev/null +++ b/tests/baselines/reference/objectLiteralGettersAndSetters.js @@ -0,0 +1,220 @@ +//// [objectLiteralGettersAndSetters.ts] +// Get and set accessor with the same name +var sameName1a = { get 'a'() { return ''; }, set a(n) { var p = n; var p: string; } }; +var sameName2a = { get 0.0() { return ''; }, set 0(n) { var p = n; var p: string; } }; +var sameName3a = { get 0x20() { return ''; }, set 3.2e1(n) { var p = n; var p: string; } }; +var sameName4a = { get ''() { return ''; }, set ""(n) { var p = n; var p: string; } }; +var sameName5a = { get '\t'() { return ''; }, set '\t'(n) { var p = n; var p: string; } }; +var sameName6a = { get 'a'() { return ''; }, set a(n) { var p = n; var p: string; } }; + +// PropertyName CallSignature{FunctionBody} is equivalent to PropertyName:function CallSignature{FunctionBody} +var callSig1 = { num(n: number) { return '' } }; +var callSig1: { num: (n: number) => string; }; +var callSig2 = { num: function (n: number) { return '' } }; +var callSig2: { num: (n: number) => string; }; +var callSig3 = { num: (n: number) => '' }; +var callSig3: { num: (n: number) => string; }; + +// Get accessor only, type of the property is the annotated return type of the get accessor +var getter1 = { get x(): string { return undefined; } }; +var getter1: { x: string; } + +// Get accessor only, type of the property is the inferred return type of the get accessor +var getter2 = { get x() { return ''; } }; +var getter2: { x: string; } + +// Set accessor only, type of the property is the param type of the set accessor +var setter1 = { set x(n: number) { } }; +var setter1: { x: number }; + +// Set accessor only, type of the property is Any for an unannotated set accessor +var setter2 = { set x(n) { } }; +var setter2: { x: any }; + +var anyVar: any; +// Get and set accessor with matching type annotations +var sameType1 = { get x(): string { return undefined; }, set x(n: string) { } }; +var sameType2 = { get x(): Array { return undefined; }, set x(n: number[]) { } }; +var sameType3 = { get x(): any { return undefined; }, set x(n: typeof anyVar) { } }; +var sameType4 = { get x(): Date { return undefined; }, set x(n: Date) { } }; + +// Type of unannotated get accessor return type is the type annotation of the set accessor param +var setParamType1 = { + set n(x: (t: string) => void) { }, + get n() { return (t) => { + var p: string; + var p = t; + } + } +}; +var setParamType2 = { + get n() { return (t) => { + var p: string; + var p = t; + } + }, + set n(x: (t: string) => void) { } +}; + +// Type of unannotated set accessor parameter is the return type annotation of the get accessor +var getParamType1 = { + set n(x) { + var y = x; + var y: string; + }, + get n() { return ''; } +}; +var getParamType2 = { + get n() { return ''; }, + set n(x) { + var y = x; + var y: string; + } +}; + +// Type of unannotated accessors is the inferred return type of the get accessor +var getParamType3 = { + get n() { return ''; }, + set n(x) { + var y = x; + var y: string; + } +}; + + + +//// [objectLiteralGettersAndSetters.js] +// Get and set accessor with the same name +var sameName1a = { get 'a'() { + return ''; +}, set a(n) { + var p = n; + var p; +} }; +var sameName2a = { get 0.0() { + return ''; +}, set 0(n) { + var p = n; + var p; +} }; +var sameName3a = { get 0x20() { + return ''; +}, set 3.2e1(n) { + var p = n; + var p; +} }; +var sameName4a = { get ''() { + return ''; +}, set ""(n) { + var p = n; + var p; +} }; +var sameName5a = { get '\t'() { + return ''; +}, set '\t'(n) { + var p = n; + var p; +} }; +var sameName6a = { get 'a'() { + return ''; +}, set a(n) { + var p = n; + var p; +} }; +// PropertyName CallSignature{FunctionBody} is equivalent to PropertyName:function CallSignature{FunctionBody} +var callSig1 = { num: function (n) { + return ''; +} }; +var callSig1; +var callSig2 = { num: function (n) { + return ''; +} }; +var callSig2; +var callSig3 = { num: function (n) { return ''; } }; +var callSig3; +// Get accessor only, type of the property is the annotated return type of the get accessor +var getter1 = { get x() { + return undefined; +} }; +var getter1; +// Get accessor only, type of the property is the inferred return type of the get accessor +var getter2 = { get x() { + return ''; +} }; +var getter2; +// Set accessor only, type of the property is the param type of the set accessor +var setter1 = { set x(n) { +} }; +var setter1; +// Set accessor only, type of the property is Any for an unannotated set accessor +var setter2 = { set x(n) { +} }; +var setter2; +var anyVar; +// Get and set accessor with matching type annotations +var sameType1 = { get x() { + return undefined; +}, set x(n) { +} }; +var sameType2 = { get x() { + return undefined; +}, set x(n) { +} }; +var sameType3 = { get x() { + return undefined; +}, set x(n) { +} }; +var sameType4 = { get x() { + return undefined; +}, set x(n) { +} }; +// Type of unannotated get accessor return type is the type annotation of the set accessor param +var setParamType1 = { + set n(x) { + }, + get n() { + return function (t) { + var p; + var p = t; + }; + } +}; +var setParamType2 = { + get n() { + return function (t) { + var p; + var p = t; + }; + }, + set n(x) { + } +}; +// Type of unannotated set accessor parameter is the return type annotation of the get accessor +var getParamType1 = { + set n(x) { + var y = x; + var y; + }, + get n() { + return ''; + } +}; +var getParamType2 = { + get n() { + return ''; + }, + set n(x) { + var y = x; + var y; + } +}; +// Type of unannotated accessors is the inferred return type of the get accessor +var getParamType3 = { + get n() { + return ''; + }, + set n(x) { + var y = x; + var y; + } +}; diff --git a/tests/baselines/reference/objectLiteralMemberWithModifiers2.js b/tests/baselines/reference/objectLiteralMemberWithModifiers2.js new file mode 100644 index 00000000000..fd8e0a68430 --- /dev/null +++ b/tests/baselines/reference/objectLiteralMemberWithModifiers2.js @@ -0,0 +1,6 @@ +//// [objectLiteralMemberWithModifiers2.ts] +var v = { public get foo() { } } + +//// [objectLiteralMemberWithModifiers2.js] +var v = { get foo() { +} }; diff --git a/tests/baselines/reference/objectLiteralMemberWithQuestionMark1.js b/tests/baselines/reference/objectLiteralMemberWithQuestionMark1.js new file mode 100644 index 00000000000..7d646cfab8e --- /dev/null +++ b/tests/baselines/reference/objectLiteralMemberWithQuestionMark1.js @@ -0,0 +1,6 @@ +//// [objectLiteralMemberWithQuestionMark1.ts] +var v = { foo?() { } } + +//// [objectLiteralMemberWithQuestionMark1.js] +var v = { foo: function () { +} }; diff --git a/tests/baselines/reference/objectLiteralMemberWithoutBlock1.js b/tests/baselines/reference/objectLiteralMemberWithoutBlock1.js new file mode 100644 index 00000000000..2ad13950b14 --- /dev/null +++ b/tests/baselines/reference/objectLiteralMemberWithoutBlock1.js @@ -0,0 +1,6 @@ +//// [objectLiteralMemberWithoutBlock1.ts] +var v = { foo(); } + +//// [objectLiteralMemberWithoutBlock1.js] +var v = { foo: function () { +} }; diff --git a/tests/baselines/reference/objectLiteralShorthandPropertiesAssignmentError.js b/tests/baselines/reference/objectLiteralShorthandPropertiesAssignmentError.js new file mode 100644 index 00000000000..84a5a9342d0 --- /dev/null +++ b/tests/baselines/reference/objectLiteralShorthandPropertiesAssignmentError.js @@ -0,0 +1,24 @@ +//// [objectLiteralShorthandPropertiesAssignmentError.ts] +var id: number = 10000; +var name: string = "my name"; + +var person: { b: string; id: number } = { name, id }; // error +var person1: { name, id }; // error: can't use short-hand property assignment in type position +function foo(name: string, id: number): { id: string, name: number } { return { name, id }; } // error +function bar(obj: { name: string; id: boolean }) { } +bar({ name, id }); // error + + + +//// [objectLiteralShorthandPropertiesAssignmentError.js] +var id = 10000; +var name = "my name"; +var person = { name: name, id: id }; // error +var person1 = name, id; +; // error: can't use short-hand property assignment in type position +function foo(name, id) { + return { name: name, id: id }; +} // error +function bar(obj) { +} +bar({ name: name, id: id }); // error diff --git a/tests/baselines/reference/objectLiteralShorthandPropertiesAssignmentErrorFromMissingIdentifier.js b/tests/baselines/reference/objectLiteralShorthandPropertiesAssignmentErrorFromMissingIdentifier.js new file mode 100644 index 00000000000..b008644116b --- /dev/null +++ b/tests/baselines/reference/objectLiteralShorthandPropertiesAssignmentErrorFromMissingIdentifier.js @@ -0,0 +1,23 @@ +//// [objectLiteralShorthandPropertiesAssignmentErrorFromMissingIdentifier.ts] +var id: number = 10000; +var name: string = "my name"; + +var person: { b: string; id: number } = { name, id }; // error +function bar(name: string, id: number): { name: number, id: string } { return { name, id }; } // error +function foo(name: string, id: number): { name: string, id: number } { return { name, id }; } // error +var person1: { name, id }; // error : Can't use shorthand in the type position +var person2: { name: string, id: number } = bar("hello", 5); + +//// [objectLiteralShorthandPropertiesAssignmentErrorFromMissingIdentifier.js] +var id = 10000; +var name = "my name"; +var person = { name: name, id: id }; // error +function bar(name, id) { + return { name: name, id: id }; +} // error +function foo(name, id) { + return { name: name, id: id }; +} // error +var person1 = name, id; +; // error : Can't use shorthand in the type position +var person2 = bar("hello", 5); diff --git a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.js b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.js new file mode 100644 index 00000000000..79e7882796f --- /dev/null +++ b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.js @@ -0,0 +1,43 @@ +//// [objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.ts] +// errors +var y = { + "stringLiteral", + 42, + get e, + set f, + this, + super, + var, + class, + typeof +}; + +var x = { + a.b, + a["ss"], + a[1], +}; + +var v = { class }; // error + +//// [objectLiteralShorthandPropertiesErrorFromNotUsingIdentifier.js] +// errors +var y = { + "stringLiteral": , + 42: , + get e() { + }, + set f() { + }, + this: , + super: , + var: , + class: , + typeof: +}; +var x = { + a: .b, + a: ["ss"], + a: [1] +}; +var v = { class: }; // error diff --git a/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.js b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.js new file mode 100644 index 00000000000..010afbc4b9e --- /dev/null +++ b/tests/baselines/reference/objectLiteralShorthandPropertiesErrorWithModule.js @@ -0,0 +1,32 @@ +//// [objectLiteralShorthandPropertiesErrorWithModule.ts] +// module export +var x = "Foo"; +module m { + export var x; +} + +module n { + var z = 10000; + export var y = { + m.x // error + }; +} + +m.y.x; + + +//// [objectLiteralShorthandPropertiesErrorWithModule.js] +// module export +var x = "Foo"; +var m; +(function (m) { + m.x; +})(m || (m = {})); +var n; +(function (n) { + var z = 10000; + n.y = { + m: .x // error + }; +})(n || (n = {})); +m.y.x; diff --git a/tests/baselines/reference/objectLiteralWithGetAccessorInsideFunction.js b/tests/baselines/reference/objectLiteralWithGetAccessorInsideFunction.js new file mode 100644 index 00000000000..58216c786ae --- /dev/null +++ b/tests/baselines/reference/objectLiteralWithGetAccessorInsideFunction.js @@ -0,0 +1,19 @@ +//// [objectLiteralWithGetAccessorInsideFunction.ts] +function bar() { + var x = { + get _extraOccluded() { + var occluded = 0; + return occluded; + }, + } +} + +//// [objectLiteralWithGetAccessorInsideFunction.js] +function bar() { + var x = { + get _extraOccluded() { + var occluded = 0; + return occluded; + } + }; +} diff --git a/tests/baselines/reference/objectTypeLiteralSyntax2.js b/tests/baselines/reference/objectTypeLiteralSyntax2.js new file mode 100644 index 00000000000..c0da0ed83d6 --- /dev/null +++ b/tests/baselines/reference/objectTypeLiteralSyntax2.js @@ -0,0 +1,19 @@ +//// [objectTypeLiteralSyntax2.ts] +var x: { + foo: string, + bar: string +} + +// ASI makes this work +var y: { + foo: string + bar: string +} + +var z: { foo: string bar: string } + +//// [objectTypeLiteralSyntax2.js] +var x; +// ASI makes this work +var y; +var z; diff --git a/tests/baselines/reference/objectTypeWithOptionalProperty1.js b/tests/baselines/reference/objectTypeWithOptionalProperty1.js new file mode 100644 index 00000000000..8f949733a49 --- /dev/null +++ b/tests/baselines/reference/objectTypeWithOptionalProperty1.js @@ -0,0 +1,9 @@ +//// [objectTypeWithOptionalProperty1.ts] + var b = { + x?: 1 // error + } + +//// [objectTypeWithOptionalProperty1.js] +var b = { + x: 1 // error +}; diff --git a/tests/baselines/reference/objectTypesWithOptionalProperties.js b/tests/baselines/reference/objectTypesWithOptionalProperties.js new file mode 100644 index 00000000000..c2177e63762 --- /dev/null +++ b/tests/baselines/reference/objectTypesWithOptionalProperties.js @@ -0,0 +1,43 @@ +//// [objectTypesWithOptionalProperties.ts] +// Basic uses of optional properties + +var a: { + x?: number; // ok +} + +interface I { + x?: number; // ok +} + +class C { + x?: number; // error +} + +interface I2 { + x?: T; // ok +} + +class C2 { + x?: T; // error +} + +var b = { + x?: 1 // error +} + +//// [objectTypesWithOptionalProperties.js] +// Basic uses of optional properties +var a; +var C = (function () { + function C() { + } + return C; +})(); +var C2 = (function () { + function C2() { + } + return C2; +})(); +var b = { + x: 1 // error +}; diff --git a/tests/baselines/reference/objectTypesWithOptionalProperties2.js b/tests/baselines/reference/objectTypesWithOptionalProperties2.js new file mode 100644 index 00000000000..3faa10447b6 --- /dev/null +++ b/tests/baselines/reference/objectTypesWithOptionalProperties2.js @@ -0,0 +1,48 @@ +//// [objectTypesWithOptionalProperties2.ts] +// Illegal attempts to define optional methods + +var a: { + x()?: number; // error +} + +interface I { + x()?: number; // error +} + +class C { + x()?: number; // error +} + +interface I2 { + x()?: T; // error +} + +class C2 { + x()?: T; // error +} + + +var b = { + x()?: 1 // error +} + +//// [objectTypesWithOptionalProperties2.js] +// Illegal attempts to define optional methods +var a; +var C = (function () { + function C() { + } + C.prototype.x = ; + return C; +})(); +var C2 = (function () { + function C2() { + } + C2.prototype.x = ; + return C2; +})(); +var b = { + x: function () { + }, + 1: // error +}; diff --git a/tests/baselines/reference/objectTypesWithPredefinedTypesAsName2.js b/tests/baselines/reference/objectTypesWithPredefinedTypesAsName2.js new file mode 100644 index 00000000000..b47901b2f0c --- /dev/null +++ b/tests/baselines/reference/objectTypesWithPredefinedTypesAsName2.js @@ -0,0 +1,13 @@ +//// [objectTypesWithPredefinedTypesAsName2.ts] +// it is an error to use a predefined type as a type name + +class void {} // parse error unlike the others + +//// [objectTypesWithPredefinedTypesAsName2.js] +// it is an error to use a predefined type as a type name +var = (function () { + function () { + } + return ; +})(); +void {}; // parse error unlike the others diff --git a/tests/baselines/reference/octalIntegerLiteralError.js b/tests/baselines/reference/octalIntegerLiteralError.js new file mode 100644 index 00000000000..068978d2657 --- /dev/null +++ b/tests/baselines/reference/octalIntegerLiteralError.js @@ -0,0 +1,23 @@ +//// [octalIntegerLiteralError.ts] +// error +var oct1 = 0O13334823; +var oct2 = 0o34318592; + +var obj1 = { + 0O45436: "hi", + 19230: "Hello", + "19230": "world", +}; + + +//// [octalIntegerLiteralError.js] +// error +var oct1 = 5852; +823; +var oct2 = 1817; +8592; +var obj1 = { + 19230: "hi", + 19230: "Hello", + "19230": "world" +}; diff --git a/tests/baselines/reference/octalLiteralInStrictModeES3.js b/tests/baselines/reference/octalLiteralInStrictModeES3.js new file mode 100644 index 00000000000..9519503ed36 --- /dev/null +++ b/tests/baselines/reference/octalLiteralInStrictModeES3.js @@ -0,0 +1,7 @@ +//// [octalLiteralInStrictModeES3.ts] +"use strict"; +03; + +//// [octalLiteralInStrictModeES3.js] +"use strict"; +03; diff --git a/tests/baselines/reference/optionalArgsWithDefaultValues.js b/tests/baselines/reference/optionalArgsWithDefaultValues.js new file mode 100644 index 00000000000..12ab7c9f330 --- /dev/null +++ b/tests/baselines/reference/optionalArgsWithDefaultValues.js @@ -0,0 +1,37 @@ +//// [optionalArgsWithDefaultValues.ts] +function foo(x: number, y?:boolean=false, z?=0) {} + +class CCC { + public foo(x: number, y?:boolean=false, z?=0) {} + static foo2(x: number, y?:boolean=false, z?=0) {} +} + +var a = (x?=0) => { return 1; }; +var b = (x, y?:number = 2) => { x; }; + +//// [optionalArgsWithDefaultValues.js] +function foo(x, y, z) { + if (y === void 0) { y = false; } + if (z === void 0) { z = 0; } +} +var CCC = (function () { + function CCC() { + } + CCC.prototype.foo = function (x, y, z) { + if (y === void 0) { y = false; } + if (z === void 0) { z = 0; } + }; + CCC.foo2 = function (x, y, z) { + if (y === void 0) { y = false; } + if (z === void 0) { z = 0; } + }; + return CCC; +})(); +var a = function (x) { + if (x === void 0) { x = 0; } + return 1; +}; +var b = function (x, y) { + if (y === void 0) { y = 2; } + x; +}; diff --git a/tests/baselines/reference/optionalParamArgsTest.js b/tests/baselines/reference/optionalParamArgsTest.js new file mode 100644 index 00000000000..942b95d245e --- /dev/null +++ b/tests/baselines/reference/optionalParamArgsTest.js @@ -0,0 +1,270 @@ +//// [optionalParamArgsTest.ts] +// Optional parameter and default argument tests + +// Key: +// Cx - "Class x" +// My - "Method x" +// Az - "Argument z" +// E.g., C1M1A1 = "Class 1, Method 1, Argument 1" + +interface I1 { + C1M1():number; + C1M2(C1M2A1:number):number; + C1M3(C1M3A1?:number,C1M3A2?:number):number; + C1M4(C1M4A1:number,C1M4A2?:number):number; +} + +// test basic configurations +class C1 { + constructor(v: number = 1, p: number = 0) { } + public n:number = 0; + + public C1M1() { return 0; } // returning C1M1A1 will result in "Unresolved symbol C1M1A1" + + public C1M2(C1M2A1:number) { return C1M2A1; } // will return C1M1A2 without complaint + + // C1M3 contains all optional parameters + public C1M3(C1M3A1:number=0,C1M3A2:number=C1M3A1) {return C1M3A1 + C1M3A2; } + + // C1M4 contains a mix of optional and non-optional parameters + public C1M4(C1M4A1:number,C1M4A2?:number) { return C1M4A1 + C1M4A2; } + + public C1M5(C1M5A1:number,C1M5A2:number=0,C1M5A3?:number) { return C1M5A1 + C1M5A2; } + + // Negative test + // "Optional parameters may only be followed by other optional parameters" + public C1M5(C1M5A1:number,C1M5A2:number=0,C1M5A3:number) { return C1M5A1 + C1M5A2; } +} + +class C2 extends C1 { + constructor(v2: number = 6) { + super(v2); + } +} + + +function F1() { return 0; } +function F2(F2A1:number) { return F2A1; } +function F3(F3A1=0,F3A2=F3A1) {return F3A1 + F3A2; } +function F4(F4A1:number,F4A2?:number) { return F4A1 + F4A2; } + +var L1 = function() {return 0;} +var L2 = function (L2A1:number) { return L2A1; } +var L3 = function (L3A1=0,L3A2=L3A1) {return L3A1 + L3A2; } +var L4 = function (L4A1:number,L4A2?:number) { return L4A1 + L4A2; } + +var c1o1:C1 = new C1(5); +var i1o1:I1 = new C1(5); +// Valid +c1o1.C1M1(); +var f1v1=F1(); +var l1v1=L1(); + +// Valid +c1o1.C1M2(1); +i1o1.C1M2(1); +var f2v1=F2(1); +var l2v1=L2(1); + +// Valid +c1o1.C1M3(1,2); +i1o1.C1M3(1,2); +var f3v1=F3(1,2); +var l3v1=L3(1,2); + +// Valid +c1o1.C1M4(1,2); +i1o1.C1M4(1,2); +var f4v1=F4(1,2); +var l4v1=L4(1,2); + +// Valid +c1o1.C1M3(1); +i1o1.C1M3(1); +var f3v2=F3(1); +var l3v2=L3(1); + +// Valid +c1o1.C1M3(); +i1o1.C1M3(); +var f3v3=F3(); +var l3v3=L3(); + +// Valid +c1o1.C1M4(1); +i1o1.C1M4(1); +var f4v2=F4(1); +var l4v2=L4(1); + +// Negative tests - we expect these cases to fail +c1o1.C1M1(1); +i1o1.C1M1(1); +F1(1); +L1(1); +c1o1.C1M2(); +i1o1.C1M2(); +F2(); +L2(); +c1o1.C1M2(1,2); +i1o1.C1M2(1,2); +F2(1,2); +L2(1,2); +c1o1.C1M3(1,2,3); +i1o1.C1M3(1,2,3); +F3(1,2,3); +L3(1,2,3); +c1o1.C1M4(); +i1o1.C1M4(); +F4(); +L4(); + +function fnOpt1(id: number, children: number[] = [], expectedPath: number[] = [], isRoot?: boolean): void {} +function fnOpt2(id: number, children?: number[], expectedPath?: number[], isRoot?: boolean): void {} +fnOpt1(1, [2, 3], [1], true); +fnOpt2(1, [2, 3], [1], true); + + +//// [optionalParamArgsTest.js] +// Optional parameter and default argument tests +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +// test basic configurations +var C1 = (function () { + function C1(v, p) { + if (v === void 0) { v = 1; } + if (p === void 0) { p = 0; } + this.n = 0; + } + C1.prototype.C1M1 = function () { + return 0; + }; // returning C1M1A1 will result in "Unresolved symbol C1M1A1" + C1.prototype.C1M2 = function (C1M2A1) { + return C1M2A1; + }; // will return C1M1A2 without complaint + // C1M3 contains all optional parameters + C1.prototype.C1M3 = function (C1M3A1, C1M3A2) { + if (C1M3A1 === void 0) { C1M3A1 = 0; } + if (C1M3A2 === void 0) { C1M3A2 = C1M3A1; } + return C1M3A1 + C1M3A2; + }; + // C1M4 contains a mix of optional and non-optional parameters + C1.prototype.C1M4 = function (C1M4A1, C1M4A2) { + return C1M4A1 + C1M4A2; + }; + C1.prototype.C1M5 = function (C1M5A1, C1M5A2, C1M5A3) { + if (C1M5A2 === void 0) { C1M5A2 = 0; } + return C1M5A1 + C1M5A2; + }; + // Negative test + // "Optional parameters may only be followed by other optional parameters" + C1.prototype.C1M5 = function (C1M5A1, C1M5A2, C1M5A3) { + if (C1M5A2 === void 0) { C1M5A2 = 0; } + return C1M5A1 + C1M5A2; + }; + return C1; +})(); +var C2 = (function (_super) { + __extends(C2, _super); + function C2(v2) { + if (v2 === void 0) { v2 = 6; } + _super.call(this, v2); + } + return C2; +})(C1); +function F1() { + return 0; +} +function F2(F2A1) { + return F2A1; +} +function F3(F3A1, F3A2) { + if (F3A1 === void 0) { F3A1 = 0; } + if (F3A2 === void 0) { F3A2 = F3A1; } + return F3A1 + F3A2; +} +function F4(F4A1, F4A2) { + return F4A1 + F4A2; +} +var L1 = function () { + return 0; +}; +var L2 = function (L2A1) { + return L2A1; +}; +var L3 = function (L3A1, L3A2) { + if (L3A1 === void 0) { L3A1 = 0; } + if (L3A2 === void 0) { L3A2 = L3A1; } + return L3A1 + L3A2; +}; +var L4 = function (L4A1, L4A2) { + return L4A1 + L4A2; +}; +var c1o1 = new C1(5); +var i1o1 = new C1(5); +// Valid +c1o1.C1M1(); +var f1v1 = F1(); +var l1v1 = L1(); +// Valid +c1o1.C1M2(1); +i1o1.C1M2(1); +var f2v1 = F2(1); +var l2v1 = L2(1); +// Valid +c1o1.C1M3(1, 2); +i1o1.C1M3(1, 2); +var f3v1 = F3(1, 2); +var l3v1 = L3(1, 2); +// Valid +c1o1.C1M4(1, 2); +i1o1.C1M4(1, 2); +var f4v1 = F4(1, 2); +var l4v1 = L4(1, 2); +// Valid +c1o1.C1M3(1); +i1o1.C1M3(1); +var f3v2 = F3(1); +var l3v2 = L3(1); +// Valid +c1o1.C1M3(); +i1o1.C1M3(); +var f3v3 = F3(); +var l3v3 = L3(); +// Valid +c1o1.C1M4(1); +i1o1.C1M4(1); +var f4v2 = F4(1); +var l4v2 = L4(1); +// Negative tests - we expect these cases to fail +c1o1.C1M1(1); +i1o1.C1M1(1); +F1(1); +L1(1); +c1o1.C1M2(); +i1o1.C1M2(); +F2(); +L2(); +c1o1.C1M2(1, 2); +i1o1.C1M2(1, 2); +F2(1, 2); +L2(1, 2); +c1o1.C1M3(1, 2, 3); +i1o1.C1M3(1, 2, 3); +F3(1, 2, 3); +L3(1, 2, 3); +c1o1.C1M4(); +i1o1.C1M4(); +F4(); +L4(); +function fnOpt1(id, children, expectedPath, isRoot) { + if (children === void 0) { children = []; } + if (expectedPath === void 0) { expectedPath = []; } +} +function fnOpt2(id, children, expectedPath, isRoot) { +} +fnOpt1(1, [2, 3], [1], true); +fnOpt2(1, [2, 3], [1], true); diff --git a/tests/baselines/reference/optionalPropertiesSyntax.js b/tests/baselines/reference/optionalPropertiesSyntax.js new file mode 100644 index 00000000000..21a572757ec --- /dev/null +++ b/tests/baselines/reference/optionalPropertiesSyntax.js @@ -0,0 +1,38 @@ +//// [optionalPropertiesSyntax.ts] +interface fnSigs { + //functions signatures can be optional + fn(): void; + fn?(): void; //err + fn2?(): void; +} + +interface callSig { + //Call signatures can't be optional + (): any; + ()?: any; //err + ?(): any; //err +} + +interface constructSig { + //Construct signatures can't be optional + new (): any; + new ()?: any; //err + new ?(): any; //err +} + +interface propertySig { + //Property signatures can be optional + prop: any; + prop?: any; + prop2?: any; +} + +interface indexSig { + //Index signatures can't be optional + [idx: number]: any; + [idx: number]?: any; //err + ? [idx: number]: any; //err + [idx?: number]: any; //err +} + +//// [optionalPropertiesSyntax.js] diff --git a/tests/baselines/reference/optionalSetterParam.js b/tests/baselines/reference/optionalSetterParam.js new file mode 100644 index 00000000000..4b9b7f01360 --- /dev/null +++ b/tests/baselines/reference/optionalSetterParam.js @@ -0,0 +1,19 @@ +//// [optionalSetterParam.ts] +class foo { + + public set bar(param?:any) { } +} + + +//// [optionalSetterParam.js] +var foo = (function () { + function foo() { + } + Object.defineProperty(foo.prototype, "bar", { + set: function (param) { + }, + enumerable: true, + configurable: true + }); + return foo; +})(); diff --git a/tests/baselines/reference/overloadOnConstAsTypeAnnotation.js b/tests/baselines/reference/overloadOnConstAsTypeAnnotation.js new file mode 100644 index 00000000000..48e52ba0967 --- /dev/null +++ b/tests/baselines/reference/overloadOnConstAsTypeAnnotation.js @@ -0,0 +1,9 @@ +//// [overloadOnConstAsTypeAnnotation.ts] +var f: (x: 'hi') => number = ('hi') => { return 1; }; + +//// [overloadOnConstAsTypeAnnotation.js] +var f = ('hi'); +{ + return 1; +} +; diff --git a/tests/baselines/reference/overloadingStaticFunctionsInFunctions.js b/tests/baselines/reference/overloadingStaticFunctionsInFunctions.js new file mode 100644 index 00000000000..7e926a6250a --- /dev/null +++ b/tests/baselines/reference/overloadingStaticFunctionsInFunctions.js @@ -0,0 +1,15 @@ +//// [overloadingStaticFunctionsInFunctions.ts] +function boo { + static test() + static test(name:string) + static test(name?:any){ } +} + +//// [overloadingStaticFunctionsInFunctions.js] +function boo() { + test(); + test(name, string); + test(name ? : any); + { + } +} diff --git a/tests/baselines/reference/parenthesizedContexualTyping1.types b/tests/baselines/reference/parenthesizedContexualTyping1.types index 60020fd8eb2..925347ed1b3 100644 --- a/tests/baselines/reference/parenthesizedContexualTyping1.types +++ b/tests/baselines/reference/parenthesizedContexualTyping1.types @@ -220,11 +220,11 @@ var l = fun(((Math.random() < 0.5 ? ((x => x)) : ((x => undefined)))), ((x => x) >x => undefined : (x: number) => any >x : number >undefined : undefined ->((x => x)) : (x: number) => number ->(x => x) : (x: number) => number ->x => x : (x: number) => number ->x : number ->x : number +>((x => x)) : (x: any) => any +>(x => x) : (x: any) => any +>x => x : (x: any) => any +>x : any +>x : any var lambda1: (x: number) => number = x => x; >lambda1 : (x: number) => number diff --git a/tests/baselines/reference/parenthesizedContexualTyping3.js b/tests/baselines/reference/parenthesizedContexualTyping3.js index 69784d14ce4..cc6dbd44f88 100644 --- a/tests/baselines/reference/parenthesizedContexualTyping3.js +++ b/tests/baselines/reference/parenthesizedContexualTyping3.js @@ -25,11 +25,11 @@ var h = tempFun `${ (x => x) } ${ (((x => x))) } ${ undefined }` function tempFun(tempStrs, g, x) { return g(x); } -var a = tempFun `${function (x) { return x; }} ${10}`; -var b = tempFun `${(function (x) { return x; })} ${10}`; -var c = tempFun `${((function (x) { return x; }))} ${10}`; -var d = tempFun `${function (x) { return x; }} ${function (x) { return x; }} ${10}`; -var e = tempFun `${function (x) { return x; }} ${(function (x) { return x; })} ${10}`; -var f = tempFun `${function (x) { return x; }} ${((function (x) { return x; }))} ${10}`; -var g = tempFun `${(function (x) { return x; })} ${(((function (x) { return x; })))} ${10}`; -var h = tempFun `${(function (x) { return x; })} ${(((function (x) { return x; })))} ${undefined}`; +var a = tempFun `${x => { return x; }} ${10}`; +var b = tempFun `${(x => { return x; })} ${10}`; +var c = tempFun `${((x => { return x; }))} ${10}`; +var d = tempFun `${x => { return x; }} ${x => { return x; }} ${10}`; +var e = tempFun `${x => { return x; }} ${(x => { return x; })} ${10}`; +var f = tempFun `${x => { return x; }} ${((x => { return x; }))} ${10}`; +var g = tempFun `${(x => { return x; })} ${(((x => { return x; })))} ${10}`; +var h = tempFun `${(x => { return x; })} ${(((x => { return x; })))} ${undefined}`; diff --git a/tests/baselines/reference/parse1.js b/tests/baselines/reference/parse1.js new file mode 100644 index 00000000000..08af81bda17 --- /dev/null +++ b/tests/baselines/reference/parse1.js @@ -0,0 +1,12 @@ +//// [parse1.ts] +var bar = 42; +function foo() { + bar. +} + + +//// [parse1.js] +var bar = 42; +function foo() { + bar.; +} diff --git a/tests/baselines/reference/parse2.js b/tests/baselines/reference/parse2.js new file mode 100644 index 00000000000..69bc1e9e5e4 --- /dev/null +++ b/tests/baselines/reference/parse2.js @@ -0,0 +1,9 @@ +//// [parse2.ts] +function foo() { + foo( +} + +//// [parse2.js] +function foo() { + foo(); +} diff --git a/tests/baselines/reference/parseErrorInHeritageClause1.js b/tests/baselines/reference/parseErrorInHeritageClause1.js new file mode 100644 index 00000000000..d08a4920171 --- /dev/null +++ b/tests/baselines/reference/parseErrorInHeritageClause1.js @@ -0,0 +1,18 @@ +//// [parseErrorInHeritageClause1.ts] +class C extends A # { +} + +//// [parseErrorInHeritageClause1.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function (_super) { + __extends(C, _super); + function C() { + _super.apply(this, arguments); + } + return C; +})(A); diff --git a/tests/baselines/reference/parseIncompleteBinaryExpression1.js b/tests/baselines/reference/parseIncompleteBinaryExpression1.js new file mode 100644 index 00000000000..f136e318ae4 --- /dev/null +++ b/tests/baselines/reference/parseIncompleteBinaryExpression1.js @@ -0,0 +1,5 @@ +//// [parseIncompleteBinaryExpression1.ts] +var v = || b; + +//// [parseIncompleteBinaryExpression1.js] +var v = || b; diff --git a/tests/baselines/reference/parser0_004152.js b/tests/baselines/reference/parser0_004152.js new file mode 100644 index 00000000000..cce49f68fcc --- /dev/null +++ b/tests/baselines/reference/parser0_004152.js @@ -0,0 +1,14 @@ +//// [parser0_004152.ts] +export class Game { + private position = new DisplayPosition([), 3, 3, 3, 3, 3, 0, 3, 3, 3, 3, 3, 3, 0], NoMove, 0); + private prevConfig: SeedCoords[][]; +} + +//// [parser0_004152.js] +var Game = (function () { + function Game() { + this.position = new DisplayPosition([]); + } + return Game; +})(); +exports.Game = Game; diff --git a/tests/baselines/reference/parser10.1.1-8gs.js b/tests/baselines/reference/parser10.1.1-8gs.js new file mode 100644 index 00000000000..85227fab116 --- /dev/null +++ b/tests/baselines/reference/parser10.1.1-8gs.js @@ -0,0 +1,37 @@ +//// [parser10.1.1-8gs.ts] +/// Copyright (c) 2012 Ecma International. All rights reserved. +/// Ecma International makes this code available under the terms and conditions set +/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the +/// "Use Terms"). Any redistribution of this code must retain the above +/// copyright and this notice and otherwise comply with the Use Terms. + +/** + * @path ch10/10.1/10.1.1/10.1.1-8gs.js + * @description Strict Mode - Use Strict Directive Prologue is ''use strict';' which appears twice in the code + * @noStrict + * @negative ^((?!NotEarlyError).)*$ + */ + +"use strict"; +"use strict"; +throw NotEarlyError; +var public = 1; + + +//// [parser10.1.1-8gs.js] +/// Copyright (c) 2012 Ecma International. All rights reserved. +/// Ecma International makes this code available under the terms and conditions set +/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the +/// "Use Terms"). Any redistribution of this code must retain the above +/// copyright and this notice and otherwise comply with the Use Terms. +/** + * @path ch10/10.1/10.1.1/10.1.1-8gs.js + * @description Strict Mode - Use Strict Directive Prologue is ''use strict';' which appears twice in the code + * @noStrict + * @negative ^((?!NotEarlyError).)*$ + */ +"use strict"; +"use strict"; +throw NotEarlyError; +var ; +1; diff --git a/tests/baselines/reference/parser509546.js b/tests/baselines/reference/parser509546.js new file mode 100644 index 00000000000..5524a4d606f --- /dev/null +++ b/tests/baselines/reference/parser509546.js @@ -0,0 +1,13 @@ +//// [parser509546.ts] +export class Logger { + public +} + + +//// [parser509546.js] +var Logger = (function () { + function Logger() { + } + return Logger; +})(); +exports.Logger = Logger; diff --git a/tests/baselines/reference/parser509546_1.js b/tests/baselines/reference/parser509546_1.js new file mode 100644 index 00000000000..d0e32feb1ca --- /dev/null +++ b/tests/baselines/reference/parser509546_1.js @@ -0,0 +1,13 @@ +//// [parser509546_1.ts] +export class Logger { + public +} + + +//// [parser509546_1.js] +var Logger = (function () { + function Logger() { + } + return Logger; +})(); +exports.Logger = Logger; diff --git a/tests/baselines/reference/parser509546_2.js b/tests/baselines/reference/parser509546_2.js new file mode 100644 index 00000000000..976bbd1e471 --- /dev/null +++ b/tests/baselines/reference/parser509546_2.js @@ -0,0 +1,16 @@ +//// [parser509546_2.ts] +"use strict"; + +export class Logger { + public +} + + +//// [parser509546_2.js] +"use strict"; +var Logger = (function () { + function Logger() { + } + return Logger; +})(); +exports.Logger = Logger; diff --git a/tests/baselines/reference/parser509618.js b/tests/baselines/reference/parser509618.js new file mode 100644 index 00000000000..d2e894ac364 --- /dev/null +++ b/tests/baselines/reference/parser509618.js @@ -0,0 +1,7 @@ +//// [parser509618.ts] +declare module ambiModule { + interface i1 { }; +} + + +//// [parser509618.js] diff --git a/tests/baselines/reference/parser509630.js b/tests/baselines/reference/parser509630.js new file mode 100644 index 00000000000..0d5a96884f3 --- /dev/null +++ b/tests/baselines/reference/parser509630.js @@ -0,0 +1,28 @@ +//// [parser509630.ts] +class Type { + public examples = [ // typing here +} +class Any extends Type { +} + + +//// [parser509630.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var Type = (function () { + function Type() { + this.examples = []; // typing here + } + return Type; +})(); +var Any = (function (_super) { + __extends(Any, _super); + function Any() { + _super.apply(this, arguments); + } + return Any; +})(Type); diff --git a/tests/baselines/reference/parser509667.js b/tests/baselines/reference/parser509667.js new file mode 100644 index 00000000000..21e0bc55ce4 --- /dev/null +++ b/tests/baselines/reference/parser509667.js @@ -0,0 +1,27 @@ +//// [parser509667.ts] +class Foo { + f1() { + if (this. + } + + f2() { + } + + f3() { + } +} + +//// [parser509667.js] +var Foo = (function () { + function Foo() { + } + Foo.prototype.f1 = function () { + if (this.) + ; + }; + Foo.prototype.f2 = function () { + }; + Foo.prototype.f3 = function () { + }; + return Foo; +})(); diff --git a/tests/baselines/reference/parser509668.js b/tests/baselines/reference/parser509668.js new file mode 100644 index 00000000000..63c5d8a1a95 --- /dev/null +++ b/tests/baselines/reference/parser509668.js @@ -0,0 +1,17 @@ +//// [parser509668.ts] +class Foo3 { + // Doesn't work, but should + constructor (public ...args: string[]) { } +} + +//// [parser509668.js] +var Foo3 = (function () { + // Doesn't work, but should + function Foo3(public) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + } + return Foo3; +})(); diff --git a/tests/baselines/reference/parser509669.js b/tests/baselines/reference/parser509669.js new file mode 100644 index 00000000000..e4ce2b90312 --- /dev/null +++ b/tests/baselines/reference/parser509669.js @@ -0,0 +1,10 @@ +//// [parser509669.ts] +function foo():any { + return ():void {}; +} + +//// [parser509669.js] +function foo() { + return function () { + }; +} diff --git a/tests/baselines/reference/parser512084.js b/tests/baselines/reference/parser512084.js new file mode 100644 index 00000000000..967c8db3cb0 --- /dev/null +++ b/tests/baselines/reference/parser512084.js @@ -0,0 +1,10 @@ +//// [parser512084.ts] +class foo { + + +//// [parser512084.js] +var foo = (function () { + function foo() { + } + return foo; +})(); diff --git a/tests/baselines/reference/parser512097.js b/tests/baselines/reference/parser512097.js new file mode 100644 index 00000000000..f507b86ccd7 --- /dev/null +++ b/tests/baselines/reference/parser512097.js @@ -0,0 +1,10 @@ +//// [parser512097.ts] +var tt = { aa; } // After this point, no useful parsing occurs in the entire file + +if (true) { +} + +//// [parser512097.js] +var tt = { aa: }; +if (true) { +} diff --git a/tests/baselines/reference/parser512325.js b/tests/baselines/reference/parser512325.js new file mode 100644 index 00000000000..14cbcddd86b --- /dev/null +++ b/tests/baselines/reference/parser512325.js @@ -0,0 +1,6 @@ +//// [parser512325.ts] +var tt = (a, (b, c)) => a+b+c; + +//// [parser512325.js] +var tt = (a, (b, c)); +a + b + c; diff --git a/tests/baselines/reference/parser519458.js b/tests/baselines/reference/parser519458.js new file mode 100644 index 00000000000..3c294d593ff --- /dev/null +++ b/tests/baselines/reference/parser519458.js @@ -0,0 +1,8 @@ +//// [parser519458.ts] +import rect = module("rect"); var bar = new rect.Rect(); + + +//// [parser519458.js] +var rect = module; +("rect"); +var bar = new rect.Rect(); diff --git a/tests/baselines/reference/parser521128.js b/tests/baselines/reference/parser521128.js new file mode 100644 index 00000000000..e16cbad6c33 --- /dev/null +++ b/tests/baselines/reference/parser521128.js @@ -0,0 +1,7 @@ +//// [parser521128.ts] +module.module { } + +//// [parser521128.js] +module.module; +{ +} diff --git a/tests/baselines/reference/parser566700.js b/tests/baselines/reference/parser566700.js new file mode 100644 index 00000000000..6c3628058b2 --- /dev/null +++ b/tests/baselines/reference/parser566700.js @@ -0,0 +1,5 @@ +//// [parser566700.ts] +var v = ()({}); + +//// [parser566700.js] +var v = ()({}); diff --git a/tests/baselines/reference/parser585151.js b/tests/baselines/reference/parser585151.js new file mode 100644 index 00000000000..16085ab3f16 --- /dev/null +++ b/tests/baselines/reference/parser585151.js @@ -0,0 +1,13 @@ +//// [parser585151.ts] +class Foo2 { + var icecream = "chocolate"; +} + + +//// [parser585151.js] +var Foo2 = (function () { + function Foo2() { + } + return Foo2; +})(); +var icecream = "chocolate"; diff --git a/tests/baselines/reference/parser618973.js b/tests/baselines/reference/parser618973.js new file mode 100644 index 00000000000..e52c9667e76 --- /dev/null +++ b/tests/baselines/reference/parser618973.js @@ -0,0 +1,15 @@ +//// [parser618973.ts] +export export class Foo { + public Bar() { + } +} + +//// [parser618973.js] +var Foo = (function () { + function Foo() { + } + Foo.prototype.Bar = function () { + }; + return Foo; +})(); +exports.Foo = Foo; diff --git a/tests/baselines/reference/parser642331_1.js b/tests/baselines/reference/parser642331_1.js new file mode 100644 index 00000000000..d4de3c04d1d --- /dev/null +++ b/tests/baselines/reference/parser642331_1.js @@ -0,0 +1,15 @@ +//// [parser642331_1.ts] +"use strict"; + +class test { + constructor (static) { } +} + + +//// [parser642331_1.js] +"use strict"; +var test = (function () { + function test() { + } + return test; +})(); diff --git a/tests/baselines/reference/parser645086_1.js b/tests/baselines/reference/parser645086_1.js new file mode 100644 index 00000000000..6036616e37c --- /dev/null +++ b/tests/baselines/reference/parser645086_1.js @@ -0,0 +1,6 @@ +//// [parser645086_1.ts] +var v = /[]/]/ + +//// [parser645086_1.js] +var v = /[]/; +/; diff --git a/tests/baselines/reference/parser645086_2.js b/tests/baselines/reference/parser645086_2.js new file mode 100644 index 00000000000..d4ed8be1486 --- /dev/null +++ b/tests/baselines/reference/parser645086_2.js @@ -0,0 +1,6 @@ +//// [parser645086_2.ts] +var v = /[^]/]/ + +//// [parser645086_2.js] +var v = /[^]/; +/; diff --git a/tests/baselines/reference/parserAccessibilityAfterStatic1.js b/tests/baselines/reference/parserAccessibilityAfterStatic1.js new file mode 100644 index 00000000000..263efaf5dd2 --- /dev/null +++ b/tests/baselines/reference/parserAccessibilityAfterStatic1.js @@ -0,0 +1,13 @@ +//// [parserAccessibilityAfterStatic1.ts] +class Outer +{ +static public intI: number; +} + + +//// [parserAccessibilityAfterStatic1.js] +var Outer = (function () { + function Outer() { + } + return Outer; +})(); diff --git a/tests/baselines/reference/parserAccessibilityAfterStatic10.js b/tests/baselines/reference/parserAccessibilityAfterStatic10.js new file mode 100644 index 00000000000..feded66fe95 --- /dev/null +++ b/tests/baselines/reference/parserAccessibilityAfterStatic10.js @@ -0,0 +1,15 @@ +//// [parserAccessibilityAfterStatic10.ts] +class Outer +{ +static public intI() {} +} + + +//// [parserAccessibilityAfterStatic10.js] +var Outer = (function () { + function Outer() { + } + Outer.intI = function () { + }; + return Outer; +})(); diff --git a/tests/baselines/reference/parserAccessibilityAfterStatic6.js b/tests/baselines/reference/parserAccessibilityAfterStatic6.js new file mode 100644 index 00000000000..de4fc048785 --- /dev/null +++ b/tests/baselines/reference/parserAccessibilityAfterStatic6.js @@ -0,0 +1,11 @@ +//// [parserAccessibilityAfterStatic6.ts] +class Outer +{ +static public + +//// [parserAccessibilityAfterStatic6.js] +var Outer = (function () { + function Outer() { + } + return Outer; +})(); diff --git a/tests/baselines/reference/parserAccessibilityAfterStatic7.js b/tests/baselines/reference/parserAccessibilityAfterStatic7.js new file mode 100644 index 00000000000..a2bc5c7fba3 --- /dev/null +++ b/tests/baselines/reference/parserAccessibilityAfterStatic7.js @@ -0,0 +1,15 @@ +//// [parserAccessibilityAfterStatic7.ts] +class Outer +{ +static public intI() {} +} + + +//// [parserAccessibilityAfterStatic7.js] +var Outer = (function () { + function Outer() { + } + Outer.intI = function () { + }; + return Outer; +})(); diff --git a/tests/baselines/reference/parserAccessors5.js b/tests/baselines/reference/parserAccessors5.js new file mode 100644 index 00000000000..7e96492a392 --- /dev/null +++ b/tests/baselines/reference/parserAccessors5.js @@ -0,0 +1,6 @@ +//// [parserAccessors5.ts] +declare class C { + get foo() { return 0; } +} + +//// [parserAccessors5.js] diff --git a/tests/baselines/reference/parserAccessors6.js b/tests/baselines/reference/parserAccessors6.js new file mode 100644 index 00000000000..3767441a633 --- /dev/null +++ b/tests/baselines/reference/parserAccessors6.js @@ -0,0 +1,6 @@ +//// [parserAccessors6.ts] +declare class C { + set foo(v) { } +} + +//// [parserAccessors6.js] diff --git a/tests/baselines/reference/parserAccessors7.js b/tests/baselines/reference/parserAccessors7.js new file mode 100644 index 00000000000..2703480ef53 --- /dev/null +++ b/tests/baselines/reference/parserAccessors7.js @@ -0,0 +1,6 @@ +//// [parserAccessors7.ts] +var v = { get foo(v: number) { } }; + +//// [parserAccessors7.js] +var v = { get foo(v) { +} }; diff --git a/tests/baselines/reference/parserAccessors8.js b/tests/baselines/reference/parserAccessors8.js new file mode 100644 index 00000000000..609fde320dc --- /dev/null +++ b/tests/baselines/reference/parserAccessors8.js @@ -0,0 +1,6 @@ +//// [parserAccessors8.ts] +var v = { set foo() { } } + +//// [parserAccessors8.js] +var v = { set foo() { +} }; diff --git a/tests/baselines/reference/parserAccessors9.js b/tests/baselines/reference/parserAccessors9.js new file mode 100644 index 00000000000..07c9d5cbc1e --- /dev/null +++ b/tests/baselines/reference/parserAccessors9.js @@ -0,0 +1,6 @@ +//// [parserAccessors9.ts] +var v = { set foo(a, b) { } } + +//// [parserAccessors9.js] +var v = { set foo(a, b) { +} }; diff --git a/tests/baselines/reference/parserArgumentList1.js b/tests/baselines/reference/parserArgumentList1.js new file mode 100644 index 00000000000..d33e8931d18 --- /dev/null +++ b/tests/baselines/reference/parserArgumentList1.js @@ -0,0 +1,14 @@ +//// [parserArgumentList1.ts] +export function removeClass (node:HTMLElement, className:string) { + node.className = node.className.replace(_classNameRegexp(className), function (everything, leftDelimiter, name, rightDelimiter) { + return leftDelimiter.length + rightDelimiter.length === 2 ? ' ' : ''; + }); +} + +//// [parserArgumentList1.js] +function removeClass(node, className) { + node.className = node.className.replace(_classNameRegexp(className), function (everything, leftDelimiter, name, rightDelimiter) { + return leftDelimiter.length + rightDelimiter.length === 2 ? ' ' : ''; + }); +} +exports.removeClass = removeClass; diff --git a/tests/baselines/reference/parserArrowFunctionExpression2.js b/tests/baselines/reference/parserArrowFunctionExpression2.js new file mode 100644 index 00000000000..5059cf32182 --- /dev/null +++ b/tests/baselines/reference/parserArrowFunctionExpression2.js @@ -0,0 +1,7 @@ +//// [parserArrowFunctionExpression2.ts] +a = () => { } || a + +//// [parserArrowFunctionExpression2.js] +a = function () { +}; + || a; diff --git a/tests/baselines/reference/parserArrowFunctionExpression3.js b/tests/baselines/reference/parserArrowFunctionExpression3.js new file mode 100644 index 00000000000..68ea230d87b --- /dev/null +++ b/tests/baselines/reference/parserArrowFunctionExpression3.js @@ -0,0 +1,6 @@ +//// [parserArrowFunctionExpression3.ts] +a = (() => { } || a) + +//// [parserArrowFunctionExpression3.js] +a = (function () { +}) || a; diff --git a/tests/baselines/reference/parserAstSpans1.js b/tests/baselines/reference/parserAstSpans1.js new file mode 100644 index 00000000000..64c8f5c0612 --- /dev/null +++ b/tests/baselines/reference/parserAstSpans1.js @@ -0,0 +1,412 @@ +//// [parserAstSpans1.ts] +/** i1 is interface with properties*/ +interface i1 { + /** i1_p1*/ + i1_p1: number; + /** i1_f1*/ + i1_f1(): void; + /** i1_l1*/ + i1_l1: () => void; + i1_nc_p1: number; + i1_nc_f1(): void; + i1_nc_l1: () => void; + p1: number; + f1(): void; + l1: () => void; + nc_p1: number; + nc_f1(): void; + nc_l1: () => void; +} +class c1 implements i1 { + public i1_p1: number; + public i1_f1() { + } + public i1_l1: () => void; + public i1_nc_p1: number; + public i1_nc_f1() { + } + public i1_nc_l1: () => void; + /** c1_p1*/ + public p1: number; + /** c1_f1*/ + public f1() { + } + /** c1_l1*/ + public l1: () => void; + /** c1_nc_p1*/ + public nc_p1: number; + /** c1_nc_f1*/ + public nc_f1() { + } + /** c1_nc_l1*/ + public nc_l1: () => void; +} +var i1_i: i1; +i1_i.i1_f1(); +i1_i.i1_nc_f1(); +i1_i.f1(); +i1_i.nc_f1(); +i1_i.i1_l1(); +i1_i.i1_nc_l1(); +i1_i.l1(); +i1_i.nc_l1(); +var c1_i = new c1(); +c1_i.i1_f1(); +c1_i.i1_nc_f1(); +c1_i.f1(); +c1_i.nc_f1(); +c1_i.i1_l1(); +c1_i.i1_nc_l1(); +c1_i.l1(); +c1_i.nc_l1(); +// assign to interface +i1_i = c1_i; +i1_i.i1_f1(); +i1_i.i1_nc_f1(); +i1_i.f1(); +i1_i.nc_f1(); +i1_i.i1_l1(); +i1_i.i1_nc_l1(); +i1_i.l1(); +i1_i.nc_l1(); + +class c2 { + /** c2 c2_p1*/ + public c2_p1: number; + /** c2 c2_f1*/ + public c2_f1() { + } + /** c2 c2_prop*/ + public get c2_prop() { + return 10; + } + public c2_nc_p1: number; + public c2_nc_f1() { + } + public get c2_nc_prop() { + return 10; + } + /** c2 p1*/ + public p1: number; + /** c2 f1*/ + public f1() { + } + /** c2 prop*/ + public get prop() { + return 10; + } + public nc_p1: number; + public nc_f1() { + } + public get nc_prop() { + return 10; + } + /** c2 constructor*/ + constructor(a: number) { + this.c2_p1 = a; + } +} +class c3 extends c2 { + constructor() { + super(10); + this.p1 = super.c2_p1; + } + /** c3 p1*/ + public p1: number; + /** c3 f1*/ + public f1() { + } + /** c3 prop*/ + public get prop() { + return 10; + } + public nc_p1: number; + public nc_f1() { + } + public get nc_prop() { + return 10; + } +} +var c2_i = new c2(10); +var c3_i = new c3(); +c2_i.c2_f1(); +c2_i.c2_nc_f1(); +c2_i.f1(); +c2_i.nc_f1(); +c3_i.c2_f1(); +c3_i.c2_nc_f1(); +c3_i.f1(); +c3_i.nc_f1(); +// assign +c2_i = c3_i; +c2_i.c2_f1(); +c2_i.c2_nc_f1(); +c2_i.f1(); +c2_i.nc_f1(); +class c4 extends c2 { +} +var c4_i = new c4(10); + +interface i2 { + /** i2_p1*/ + i2_p1: number; + /** i2_f1*/ + i2_f1(): void; + /** i2_l1*/ + i2_l1: () => void; + i2_nc_p1: number; + i2_nc_f1(): void; + i2_nc_l1: () => void; + /** i2 p1*/ + p1: number; + /** i2 f1*/ + f1(): void; + /** i2 l1*/ + l1: () => void; + nc_p1: number; + nc_f1(): void; + nc_l1: () => void; +} +interface i3 extends i2 { + /** i3 p1*/ + p1: number; + /** i3 f1*/ + f1(): void; + /** i3 l1*/ + l1: () => void; + nc_p1: number; + nc_f1(): void; + nc_l1: () => void; +} +var i2_i: i2; +var i3_i: i3; +i2_i.i2_f1(); +i2_i.i2_nc_f1(); +i2_i.f1(); +i2_i.nc_f1(); +i2_i.i2_l1(); +i2_i.i2_nc_l1(); +i2_i.l1(); +i2_i.nc_l1(); +i3_i.i2_f1(); +i3_i.i2_nc_f1(); +i3_i.f1(); +i3_i.nc_f1(); +i3_i.i2_l1(); +i3_i.i2_nc_l1(); +i3_i.l1(); +i3_i.nc_l1(); +// assign to interface +i2_i = i3_i; +i2_i.i2_f1(); +i2_i.i2_nc_f1(); +i2_i.f1(); +i2_i.nc_f1(); +i2_i.i2_l1(); +i2_i.i2_nc_l1(); +i2_i.l1(); +i2_i.nc_l1(); + +/**c5 class*/ +class c5 { + public b: number; +} +class c6 extends c5 { + public d; + constructor() { + super(); + this.d = super.b; + } +} + +//// [parserAstSpans1.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var c1 = (function () { + function c1() { + } + c1.prototype.i1_f1 = function () { + }; + c1.prototype.i1_nc_f1 = function () { + }; + /** c1_f1*/ + c1.prototype.f1 = function () { + }; + /** c1_nc_f1*/ + c1.prototype.nc_f1 = function () { + }; + return c1; +})(); +var i1_i; +i1_i.i1_f1(); +i1_i.i1_nc_f1(); +i1_i.f1(); +i1_i.nc_f1(); +i1_i.i1_l1(); +i1_i.i1_nc_l1(); +i1_i.l1(); +i1_i.nc_l1(); +var c1_i = new c1(); +c1_i.i1_f1(); +c1_i.i1_nc_f1(); +c1_i.f1(); +c1_i.nc_f1(); +c1_i.i1_l1(); +c1_i.i1_nc_l1(); +c1_i.l1(); +c1_i.nc_l1(); +// assign to interface +i1_i = c1_i; +i1_i.i1_f1(); +i1_i.i1_nc_f1(); +i1_i.f1(); +i1_i.nc_f1(); +i1_i.i1_l1(); +i1_i.i1_nc_l1(); +i1_i.l1(); +i1_i.nc_l1(); +var c2 = (function () { + /** c2 constructor*/ + function c2(a) { + this.c2_p1 = a; + } + /** c2 c2_f1*/ + c2.prototype.c2_f1 = function () { + }; + Object.defineProperty(c2.prototype, "c2_prop", { + /** c2 c2_prop*/ + get: function () { + return 10; + }, + enumerable: true, + configurable: true + }); + c2.prototype.c2_nc_f1 = function () { + }; + Object.defineProperty(c2.prototype, "c2_nc_prop", { + get: function () { + return 10; + }, + enumerable: true, + configurable: true + }); + /** c2 f1*/ + c2.prototype.f1 = function () { + }; + Object.defineProperty(c2.prototype, "prop", { + /** c2 prop*/ + get: function () { + return 10; + }, + enumerable: true, + configurable: true + }); + c2.prototype.nc_f1 = function () { + }; + Object.defineProperty(c2.prototype, "nc_prop", { + get: function () { + return 10; + }, + enumerable: true, + configurable: true + }); + return c2; +})(); +var c3 = (function (_super) { + __extends(c3, _super); + function c3() { + _super.call(this, 10); + this.p1 = _super.prototype.c2_p1; + } + /** c3 f1*/ + c3.prototype.f1 = function () { + }; + Object.defineProperty(c3.prototype, "prop", { + /** c3 prop*/ + get: function () { + return 10; + }, + enumerable: true, + configurable: true + }); + c3.prototype.nc_f1 = function () { + }; + Object.defineProperty(c3.prototype, "nc_prop", { + get: function () { + return 10; + }, + enumerable: true, + configurable: true + }); + return c3; +})(c2); +var c2_i = new c2(10); +var c3_i = new c3(); +c2_i.c2_f1(); +c2_i.c2_nc_f1(); +c2_i.f1(); +c2_i.nc_f1(); +c3_i.c2_f1(); +c3_i.c2_nc_f1(); +c3_i.f1(); +c3_i.nc_f1(); +// assign +c2_i = c3_i; +c2_i.c2_f1(); +c2_i.c2_nc_f1(); +c2_i.f1(); +c2_i.nc_f1(); +var c4 = (function (_super) { + __extends(c4, _super); + function c4() { + _super.apply(this, arguments); + } + return c4; +})(c2); +var c4_i = new c4(10); +var i2_i; +var i3_i; +i2_i.i2_f1(); +i2_i.i2_nc_f1(); +i2_i.f1(); +i2_i.nc_f1(); +i2_i.i2_l1(); +i2_i.i2_nc_l1(); +i2_i.l1(); +i2_i.nc_l1(); +i3_i.i2_f1(); +i3_i.i2_nc_f1(); +i3_i.f1(); +i3_i.nc_f1(); +i3_i.i2_l1(); +i3_i.i2_nc_l1(); +i3_i.l1(); +i3_i.nc_l1(); +// assign to interface +i2_i = i3_i; +i2_i.i2_f1(); +i2_i.i2_nc_f1(); +i2_i.f1(); +i2_i.nc_f1(); +i2_i.i2_l1(); +i2_i.i2_nc_l1(); +i2_i.l1(); +i2_i.nc_l1(); +/**c5 class*/ +var c5 = (function () { + function c5() { + } + return c5; +})(); +var c6 = (function (_super) { + __extends(c6, _super); + function c6() { + _super.call(this); + this.d = _super.prototype.b; + } + return c6; +})(c5); diff --git a/tests/baselines/reference/parserCatchClauseWithTypeAnnotation1.js b/tests/baselines/reference/parserCatchClauseWithTypeAnnotation1.js new file mode 100644 index 00000000000..e2ca0ae8be6 --- /dev/null +++ b/tests/baselines/reference/parserCatchClauseWithTypeAnnotation1.js @@ -0,0 +1,11 @@ +//// [parserCatchClauseWithTypeAnnotation1.ts] +try { +} catch (e: Error) { +} + + +//// [parserCatchClauseWithTypeAnnotation1.js] +try { +} +catch (e) { +} diff --git a/tests/baselines/reference/parserClass1.js b/tests/baselines/reference/parserClass1.js new file mode 100644 index 00000000000..1245da3363f --- /dev/null +++ b/tests/baselines/reference/parserClass1.js @@ -0,0 +1,35 @@ +//// [parserClass1.ts] + export class NullLogger implements ILogger { + public information(): boolean { return false; } + public debug(): boolean { return false; } + public warning(): boolean { return false; } + public error(): boolean { return false; } + public fatal(): boolean { return false; } + public log(s: string): void { + } + } + +//// [parserClass1.js] +var NullLogger = (function () { + function NullLogger() { + } + NullLogger.prototype.information = function () { + return false; + }; + NullLogger.prototype.debug = function () { + return false; + }; + NullLogger.prototype.warning = function () { + return false; + }; + NullLogger.prototype.error = function () { + return false; + }; + NullLogger.prototype.fatal = function () { + return false; + }; + NullLogger.prototype.log = function (s) { + }; + return NullLogger; +})(); +exports.NullLogger = NullLogger; diff --git a/tests/baselines/reference/parserClass2.js b/tests/baselines/reference/parserClass2.js new file mode 100644 index 00000000000..b3816ea6ebb --- /dev/null +++ b/tests/baselines/reference/parserClass2.js @@ -0,0 +1,18 @@ +//// [parserClass2.ts] + + + export class LoggerAdapter implements ILogger { + constructor (public logger: ILogger) { + this._information = this.logger.information(); + } + } + +//// [parserClass2.js] +var LoggerAdapter = (function () { + function LoggerAdapter(logger) { + this.logger = logger; + this._information = this.logger.information(); + } + return LoggerAdapter; +})(); +exports.LoggerAdapter = LoggerAdapter; diff --git a/tests/baselines/reference/parserClassDeclaration1.js b/tests/baselines/reference/parserClassDeclaration1.js new file mode 100644 index 00000000000..1e4fc0d5bcf --- /dev/null +++ b/tests/baselines/reference/parserClassDeclaration1.js @@ -0,0 +1,18 @@ +//// [parserClassDeclaration1.ts] +class C extends A extends B { +} + +//// [parserClassDeclaration1.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function (_super) { + __extends(C, _super); + function C() { + _super.apply(this, arguments); + } + return C; +})(A); diff --git a/tests/baselines/reference/parserClassDeclaration18.js b/tests/baselines/reference/parserClassDeclaration18.js new file mode 100644 index 00000000000..d95c730608e --- /dev/null +++ b/tests/baselines/reference/parserClassDeclaration18.js @@ -0,0 +1,10 @@ +//// [parserClassDeclaration18.ts] +declare class FooBase { + constructor(s: string); + constructor(n: number); + constructor(x: any) { + } + bar1():void; +} + +//// [parserClassDeclaration18.js] diff --git a/tests/baselines/reference/parserClassDeclaration2.js b/tests/baselines/reference/parserClassDeclaration2.js new file mode 100644 index 00000000000..18bb068b23f --- /dev/null +++ b/tests/baselines/reference/parserClassDeclaration2.js @@ -0,0 +1,10 @@ +//// [parserClassDeclaration2.ts] +class C implements A implements B { +} + +//// [parserClassDeclaration2.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserClassDeclaration3.js b/tests/baselines/reference/parserClassDeclaration3.js new file mode 100644 index 00000000000..99d34bedaed --- /dev/null +++ b/tests/baselines/reference/parserClassDeclaration3.js @@ -0,0 +1,18 @@ +//// [parserClassDeclaration3.ts] +class C implements A extends B { +} + +//// [parserClassDeclaration3.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function (_super) { + __extends(C, _super); + function C() { + _super.apply(this, arguments); + } + return C; +})(B); diff --git a/tests/baselines/reference/parserClassDeclaration4.js b/tests/baselines/reference/parserClassDeclaration4.js new file mode 100644 index 00000000000..3552c74f184 --- /dev/null +++ b/tests/baselines/reference/parserClassDeclaration4.js @@ -0,0 +1,18 @@ +//// [parserClassDeclaration4.ts] +class C extends A implements B extends C { +} + +//// [parserClassDeclaration4.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function (_super) { + __extends(C, _super); + function C() { + _super.apply(this, arguments); + } + return C; +})(A); diff --git a/tests/baselines/reference/parserClassDeclaration5.js b/tests/baselines/reference/parserClassDeclaration5.js new file mode 100644 index 00000000000..6a7846fd036 --- /dev/null +++ b/tests/baselines/reference/parserClassDeclaration5.js @@ -0,0 +1,18 @@ +//// [parserClassDeclaration5.ts] +class C extends A implements B implements C { +} + +//// [parserClassDeclaration5.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function (_super) { + __extends(C, _super); + function C() { + _super.apply(this, arguments); + } + return C; +})(A); diff --git a/tests/baselines/reference/parserClassDeclaration6.js b/tests/baselines/reference/parserClassDeclaration6.js new file mode 100644 index 00000000000..24e55a48344 --- /dev/null +++ b/tests/baselines/reference/parserClassDeclaration6.js @@ -0,0 +1,18 @@ +//// [parserClassDeclaration6.ts] +class C extends A, B { +} + +//// [parserClassDeclaration6.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function (_super) { + __extends(C, _super); + function C() { + _super.apply(this, arguments); + } + return C; +})(A); diff --git a/tests/baselines/reference/parserClassDeclaration7.js b/tests/baselines/reference/parserClassDeclaration7.js new file mode 100644 index 00000000000..5418dd38a5f --- /dev/null +++ b/tests/baselines/reference/parserClassDeclaration7.js @@ -0,0 +1,7 @@ +//// [parserClassDeclaration7.ts] +declare module M { + declare class C { + } +} + +//// [parserClassDeclaration7.js] diff --git a/tests/baselines/reference/parserCommaInTypeMemberList1.js b/tests/baselines/reference/parserCommaInTypeMemberList1.js new file mode 100644 index 00000000000..25be7d9f18b --- /dev/null +++ b/tests/baselines/reference/parserCommaInTypeMemberList1.js @@ -0,0 +1,5 @@ +//// [parserCommaInTypeMemberList1.ts] +var v: { workItem: any, width: string }; + +//// [parserCommaInTypeMemberList1.js] +var v; diff --git a/tests/baselines/reference/parserCommaInTypeMemberList2.js b/tests/baselines/reference/parserCommaInTypeMemberList2.js new file mode 100644 index 00000000000..fd79326b7b0 --- /dev/null +++ b/tests/baselines/reference/parserCommaInTypeMemberList2.js @@ -0,0 +1,6 @@ +//// [parserCommaInTypeMemberList2.ts] +var s = $.extend< { workItem: any }, { workItem: any, width: string }>({ workItem: this._workItem }, {}); + + +//// [parserCommaInTypeMemberList2.js] +var s = $.extend({ workItem: this._workItem }, {}); diff --git a/tests/baselines/reference/parserComputedPropertyName1.js b/tests/baselines/reference/parserComputedPropertyName1.js new file mode 100644 index 00000000000..ee5b0a22cb6 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName1.js @@ -0,0 +1,5 @@ +//// [parserComputedPropertyName1.ts] +var v = { [e] }; + +//// [parserComputedPropertyName1.js] +var v = { [e]: }; diff --git a/tests/baselines/reference/parserComputedPropertyName10.js b/tests/baselines/reference/parserComputedPropertyName10.js new file mode 100644 index 00000000000..c00d3292f7e --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName10.js @@ -0,0 +1,12 @@ +//// [parserComputedPropertyName10.ts] +class C { + [e] = 1 +} + +//// [parserComputedPropertyName10.js] +var C = (function () { + function C() { + this[e] = 1; + } + return C; +})(); diff --git a/tests/baselines/reference/parserComputedPropertyName11.js b/tests/baselines/reference/parserComputedPropertyName11.js new file mode 100644 index 00000000000..1b9575184f2 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName11.js @@ -0,0 +1,11 @@ +//// [parserComputedPropertyName11.ts] +class C { + [e](); +} + +//// [parserComputedPropertyName11.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserComputedPropertyName13.js b/tests/baselines/reference/parserComputedPropertyName13.js new file mode 100644 index 00000000000..ccf59b67827 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName13.js @@ -0,0 +1,5 @@ +//// [parserComputedPropertyName13.ts] +var v: { [e]: number }; + +//// [parserComputedPropertyName13.js] +var v; diff --git a/tests/baselines/reference/parserComputedPropertyName14.js b/tests/baselines/reference/parserComputedPropertyName14.js new file mode 100644 index 00000000000..486d9b1a53f --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName14.js @@ -0,0 +1,5 @@ +//// [parserComputedPropertyName14.ts] +var v: { [e](): number }; + +//// [parserComputedPropertyName14.js] +var v; diff --git a/tests/baselines/reference/parserComputedPropertyName15.js b/tests/baselines/reference/parserComputedPropertyName15.js new file mode 100644 index 00000000000..ecdb183679e --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName15.js @@ -0,0 +1,5 @@ +//// [parserComputedPropertyName15.ts] +var v: { [e: number]: string; [e]: number }; + +//// [parserComputedPropertyName15.js] +var v; diff --git a/tests/baselines/reference/parserComputedPropertyName16.js b/tests/baselines/reference/parserComputedPropertyName16.js new file mode 100644 index 00000000000..7f0c07e38c2 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName16.js @@ -0,0 +1,10 @@ +//// [parserComputedPropertyName16.ts] +enum E { + [e] = 1 +} + +//// [parserComputedPropertyName16.js] +var E; +(function (E) { + E[E[e] = 1] = e; +})(E || (E = {})); diff --git a/tests/baselines/reference/parserComputedPropertyName18.js b/tests/baselines/reference/parserComputedPropertyName18.js new file mode 100644 index 00000000000..76a88456007 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName18.js @@ -0,0 +1,5 @@ +//// [parserComputedPropertyName18.ts] +var v: { [e]?(): number }; + +//// [parserComputedPropertyName18.js] +var v; diff --git a/tests/baselines/reference/parserComputedPropertyName19.js b/tests/baselines/reference/parserComputedPropertyName19.js new file mode 100644 index 00000000000..caa66d48c52 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName19.js @@ -0,0 +1,5 @@ +//// [parserComputedPropertyName19.ts] +var v: { [e]? }; + +//// [parserComputedPropertyName19.js] +var v; diff --git a/tests/baselines/reference/parserComputedPropertyName20.js b/tests/baselines/reference/parserComputedPropertyName20.js new file mode 100644 index 00000000000..25a912dbcaa --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName20.js @@ -0,0 +1,6 @@ +//// [parserComputedPropertyName20.ts] +interface I { + [e](): number +} + +//// [parserComputedPropertyName20.js] diff --git a/tests/baselines/reference/parserComputedPropertyName21.js b/tests/baselines/reference/parserComputedPropertyName21.js new file mode 100644 index 00000000000..c3ae1d63d66 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName21.js @@ -0,0 +1,6 @@ +//// [parserComputedPropertyName21.ts] +interface I { + [e]: number +} + +//// [parserComputedPropertyName21.js] diff --git a/tests/baselines/reference/parserComputedPropertyName22.js b/tests/baselines/reference/parserComputedPropertyName22.js new file mode 100644 index 00000000000..6e29af5239f --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName22.js @@ -0,0 +1,6 @@ +//// [parserComputedPropertyName22.ts] +declare class C { + [e]: number +} + +//// [parserComputedPropertyName22.js] diff --git a/tests/baselines/reference/parserComputedPropertyName23.js b/tests/baselines/reference/parserComputedPropertyName23.js new file mode 100644 index 00000000000..a29f610290a --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName23.js @@ -0,0 +1,6 @@ +//// [parserComputedPropertyName23.ts] +declare class C { + get [e](): number +} + +//// [parserComputedPropertyName23.js] diff --git a/tests/baselines/reference/parserComputedPropertyName25.js b/tests/baselines/reference/parserComputedPropertyName25.js new file mode 100644 index 00000000000..a00cec2e6dd --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName25.js @@ -0,0 +1,15 @@ +//// [parserComputedPropertyName25.ts] +class C { + // No ASI + [e] = 0 + [e2] = 1 +} + +//// [parserComputedPropertyName25.js] +var C = (function () { + function C() { + // No ASI + this[e] = 0[e2] = 1; + } + return C; +})(); diff --git a/tests/baselines/reference/parserComputedPropertyName26.js b/tests/baselines/reference/parserComputedPropertyName26.js new file mode 100644 index 00000000000..fe47249a22e --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName26.js @@ -0,0 +1,13 @@ +//// [parserComputedPropertyName26.ts] +enum E { + // No ASI + [e] = 0 + [e2] = 1 +} + +//// [parserComputedPropertyName26.js] +var E; +(function (E) { + // No ASI + E[E[e] = 0[e2] = 1] = e; +})(E || (E = {})); diff --git a/tests/baselines/reference/parserComputedPropertyName27.js b/tests/baselines/reference/parserComputedPropertyName27.js new file mode 100644 index 00000000000..03b156af840 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName27.js @@ -0,0 +1,15 @@ +//// [parserComputedPropertyName27.ts] +class C { + // No ASI + [e]: number = 0 + [e2]: number +} + +//// [parserComputedPropertyName27.js] +var C = (function () { + function C() { + // No ASI + this[e] = 0[e2]; + } + return C; +})(); diff --git a/tests/baselines/reference/parserComputedPropertyName28.js b/tests/baselines/reference/parserComputedPropertyName28.js new file mode 100644 index 00000000000..60fb25dfa20 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName28.js @@ -0,0 +1,13 @@ +//// [parserComputedPropertyName28.ts] +class C { + [e]: number = 0; + [e2]: number +} + +//// [parserComputedPropertyName28.js] +var C = (function () { + function C() { + this[e] = 0; + } + return C; +})(); diff --git a/tests/baselines/reference/parserComputedPropertyName29.js b/tests/baselines/reference/parserComputedPropertyName29.js new file mode 100644 index 00000000000..05ced020aff --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName29.js @@ -0,0 +1,15 @@ +//// [parserComputedPropertyName29.ts] +class C { + // yes ASI + [e] = id++ + [e2]: number +} + +//// [parserComputedPropertyName29.js] +var C = (function () { + function C() { + // yes ASI + this[e] = id++; + } + return C; +})(); diff --git a/tests/baselines/reference/parserComputedPropertyName30.js b/tests/baselines/reference/parserComputedPropertyName30.js new file mode 100644 index 00000000000..cdad5321cff --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName30.js @@ -0,0 +1,14 @@ +//// [parserComputedPropertyName30.ts] +enum E { + // no ASI, comma expected + [e] = id++ + [e2] = 1 +} + +//// [parserComputedPropertyName30.js] +var E; +(function (E) { + // no ASI, comma expected + E[E[e] = id++] = e; + E[E[e2] = 1] = e2; +})(E || (E = {})); diff --git a/tests/baselines/reference/parserComputedPropertyName31.js b/tests/baselines/reference/parserComputedPropertyName31.js new file mode 100644 index 00000000000..2a07155a2f0 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName31.js @@ -0,0 +1,13 @@ +//// [parserComputedPropertyName31.ts] +class C { + // yes ASI + [e]: number + [e2]: number +} + +//// [parserComputedPropertyName31.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserComputedPropertyName32.js b/tests/baselines/reference/parserComputedPropertyName32.js new file mode 100644 index 00000000000..685b215c8f4 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName32.js @@ -0,0 +1,6 @@ +//// [parserComputedPropertyName32.ts] +declare class C { + [e](): number +} + +//// [parserComputedPropertyName32.js] diff --git a/tests/baselines/reference/parserComputedPropertyName33.js b/tests/baselines/reference/parserComputedPropertyName33.js new file mode 100644 index 00000000000..1cc06c06780 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName33.js @@ -0,0 +1,17 @@ +//// [parserComputedPropertyName33.ts] +class C { + // No ASI + [e] = 0 + [e2]() { } +} + +//// [parserComputedPropertyName33.js] +var C = (function () { + function C() { + // No ASI + this[e] = 0[e2](); + } + return C; +})(); +{ +} diff --git a/tests/baselines/reference/parserComputedPropertyName34.js b/tests/baselines/reference/parserComputedPropertyName34.js new file mode 100644 index 00000000000..f5a6daa56e5 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName34.js @@ -0,0 +1,14 @@ +//// [parserComputedPropertyName34.ts] +enum E { + // no ASI, comma expected + [e] = id++, + [e2] = 1 +} + +//// [parserComputedPropertyName34.js] +var E; +(function (E) { + // no ASI, comma expected + E[E[e] = id++] = e; + E[E[e2] = 1] = e2; +})(E || (E = {})); diff --git a/tests/baselines/reference/parserComputedPropertyName36.js b/tests/baselines/reference/parserComputedPropertyName36.js new file mode 100644 index 00000000000..264a3512075 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName36.js @@ -0,0 +1,11 @@ +//// [parserComputedPropertyName36.ts] +class C { + [public ]: string; +} + +//// [parserComputedPropertyName36.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserComputedPropertyName39.js b/tests/baselines/reference/parserComputedPropertyName39.js new file mode 100644 index 00000000000..c37312f0034 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName39.js @@ -0,0 +1,15 @@ +//// [parserComputedPropertyName39.ts] +"use strict"; +class C { + [public]() { } +} + +//// [parserComputedPropertyName39.js] +"use strict"; +var C = (function () { + function C() { + } + return C; +})(); +(() => { +}); diff --git a/tests/baselines/reference/parserComputedPropertyName7.js b/tests/baselines/reference/parserComputedPropertyName7.js new file mode 100644 index 00000000000..70ed8b7b073 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName7.js @@ -0,0 +1,11 @@ +//// [parserComputedPropertyName7.ts] +class C { + [e] +} + +//// [parserComputedPropertyName7.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserComputedPropertyName8.js b/tests/baselines/reference/parserComputedPropertyName8.js new file mode 100644 index 00000000000..4b79c459663 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName8.js @@ -0,0 +1,11 @@ +//// [parserComputedPropertyName8.ts] +class C { + public [e] +} + +//// [parserComputedPropertyName8.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserComputedPropertyName9.js b/tests/baselines/reference/parserComputedPropertyName9.js new file mode 100644 index 00000000000..4b62cc0ecd9 --- /dev/null +++ b/tests/baselines/reference/parserComputedPropertyName9.js @@ -0,0 +1,11 @@ +//// [parserComputedPropertyName9.ts] +class C { + [e]: Type +} + +//// [parserComputedPropertyName9.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserConstructorAmbiguity3.js b/tests/baselines/reference/parserConstructorAmbiguity3.js new file mode 100644 index 00000000000..bc565c70a7a --- /dev/null +++ b/tests/baselines/reference/parserConstructorAmbiguity3.js @@ -0,0 +1,5 @@ +//// [parserConstructorAmbiguity3.ts] +new Date + +//// [parserConstructorAmbiguity3.js] +new Date(); diff --git a/tests/baselines/reference/parserConstructorDeclaration10.js b/tests/baselines/reference/parserConstructorDeclaration10.js new file mode 100644 index 00000000000..9289636e919 --- /dev/null +++ b/tests/baselines/reference/parserConstructorDeclaration10.js @@ -0,0 +1,11 @@ +//// [parserConstructorDeclaration10.ts] +class C { + constructor(): number { } +} + +//// [parserConstructorDeclaration10.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserConstructorDeclaration11.js b/tests/baselines/reference/parserConstructorDeclaration11.js new file mode 100644 index 00000000000..a21fa87f694 --- /dev/null +++ b/tests/baselines/reference/parserConstructorDeclaration11.js @@ -0,0 +1,11 @@ +//// [parserConstructorDeclaration11.ts] +class C { + constructor<>() { } +} + +//// [parserConstructorDeclaration11.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserConstructorDeclaration12.js b/tests/baselines/reference/parserConstructorDeclaration12.js new file mode 100644 index 00000000000..dc540c3323e --- /dev/null +++ b/tests/baselines/reference/parserConstructorDeclaration12.js @@ -0,0 +1,18 @@ +//// [parserConstructorDeclaration12.ts] +class C { + constructor<>() { } + constructor<> () { } + constructor <>() { } + constructor <> () { } + constructor< >() { } + constructor< > () { } + constructor < >() { } + constructor < > () { } +} + +//// [parserConstructorDeclaration12.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserConstructorDeclaration2.js b/tests/baselines/reference/parserConstructorDeclaration2.js new file mode 100644 index 00000000000..142bf5a5314 --- /dev/null +++ b/tests/baselines/reference/parserConstructorDeclaration2.js @@ -0,0 +1,11 @@ +//// [parserConstructorDeclaration2.ts] +class C { + static constructor() { } +} + +//// [parserConstructorDeclaration2.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserConstructorDeclaration3.js b/tests/baselines/reference/parserConstructorDeclaration3.js new file mode 100644 index 00000000000..6e7531f1e66 --- /dev/null +++ b/tests/baselines/reference/parserConstructorDeclaration3.js @@ -0,0 +1,11 @@ +//// [parserConstructorDeclaration3.ts] +class C { + export constructor() { } +} + +//// [parserConstructorDeclaration3.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserConstructorDeclaration4.js b/tests/baselines/reference/parserConstructorDeclaration4.js new file mode 100644 index 00000000000..2b1ae1cdb68 --- /dev/null +++ b/tests/baselines/reference/parserConstructorDeclaration4.js @@ -0,0 +1,11 @@ +//// [parserConstructorDeclaration4.ts] +class C { + declare constructor() { } +} + +//// [parserConstructorDeclaration4.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserConstructorDeclaration5.js b/tests/baselines/reference/parserConstructorDeclaration5.js new file mode 100644 index 00000000000..c0d8c03458e --- /dev/null +++ b/tests/baselines/reference/parserConstructorDeclaration5.js @@ -0,0 +1,11 @@ +//// [parserConstructorDeclaration5.ts] +class C { + private constructor() { } +} + +//// [parserConstructorDeclaration5.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserConstructorDeclaration6.js b/tests/baselines/reference/parserConstructorDeclaration6.js new file mode 100644 index 00000000000..abee73fe0b8 --- /dev/null +++ b/tests/baselines/reference/parserConstructorDeclaration6.js @@ -0,0 +1,11 @@ +//// [parserConstructorDeclaration6.ts] +class C { + public public constructor() { } +} + +//// [parserConstructorDeclaration6.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserConstructorDeclaration7.js b/tests/baselines/reference/parserConstructorDeclaration7.js new file mode 100644 index 00000000000..8c3b4db9d22 --- /dev/null +++ b/tests/baselines/reference/parserConstructorDeclaration7.js @@ -0,0 +1,11 @@ +//// [parserConstructorDeclaration7.ts] +class C { + public private constructor() { } +} + +//// [parserConstructorDeclaration7.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserConstructorDeclaration8.js b/tests/baselines/reference/parserConstructorDeclaration8.js new file mode 100644 index 00000000000..26c06b591c0 --- /dev/null +++ b/tests/baselines/reference/parserConstructorDeclaration8.js @@ -0,0 +1,12 @@ +//// [parserConstructorDeclaration8.ts] +class C { + // Not a constructor + public constructor; +} + +//// [parserConstructorDeclaration8.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserConstructorDeclaration9.js b/tests/baselines/reference/parserConstructorDeclaration9.js new file mode 100644 index 00000000000..8393d35f5e7 --- /dev/null +++ b/tests/baselines/reference/parserConstructorDeclaration9.js @@ -0,0 +1,11 @@ +//// [parserConstructorDeclaration9.ts] +class C { + constructor() { } +} + +//// [parserConstructorDeclaration9.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserES3Accessors1.js b/tests/baselines/reference/parserES3Accessors1.js new file mode 100644 index 00000000000..4900c1f32d9 --- /dev/null +++ b/tests/baselines/reference/parserES3Accessors1.js @@ -0,0 +1,17 @@ +//// [parserES3Accessors1.ts] +class C { + get Foo() { } +} + +//// [parserES3Accessors1.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "Foo", { + get: function () { + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/parserES3Accessors2.js b/tests/baselines/reference/parserES3Accessors2.js new file mode 100644 index 00000000000..08259f2655e --- /dev/null +++ b/tests/baselines/reference/parserES3Accessors2.js @@ -0,0 +1,17 @@ +//// [parserES3Accessors2.ts] +class C { + set Foo(a) { } +} + +//// [parserES3Accessors2.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "Foo", { + set: function (a) { + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/parserES3Accessors3.js b/tests/baselines/reference/parserES3Accessors3.js new file mode 100644 index 00000000000..57ceb566dcb --- /dev/null +++ b/tests/baselines/reference/parserES3Accessors3.js @@ -0,0 +1,6 @@ +//// [parserES3Accessors3.ts] +var v = { get Foo() { } }; + +//// [parserES3Accessors3.js] +var v = { get Foo() { +} }; diff --git a/tests/baselines/reference/parserES3Accessors4.js b/tests/baselines/reference/parserES3Accessors4.js new file mode 100644 index 00000000000..5c87923ed5e --- /dev/null +++ b/tests/baselines/reference/parserES3Accessors4.js @@ -0,0 +1,6 @@ +//// [parserES3Accessors4.ts] +var v = { set Foo(a) { } }; + +//// [parserES3Accessors4.js] +var v = { set Foo(a) { +} }; diff --git a/tests/baselines/reference/parserES5ComputedPropertyName1.js b/tests/baselines/reference/parserES5ComputedPropertyName1.js new file mode 100644 index 00000000000..6eb66b78cec --- /dev/null +++ b/tests/baselines/reference/parserES5ComputedPropertyName1.js @@ -0,0 +1,6 @@ +//// [parserES5ComputedPropertyName1.ts] +declare class C { + [e]: number +} + +//// [parserES5ComputedPropertyName1.js] diff --git a/tests/baselines/reference/parserES5ComputedPropertyName10.js b/tests/baselines/reference/parserES5ComputedPropertyName10.js new file mode 100644 index 00000000000..a69165a192a --- /dev/null +++ b/tests/baselines/reference/parserES5ComputedPropertyName10.js @@ -0,0 +1,12 @@ +//// [parserES5ComputedPropertyName10.ts] +class C { + [e] = 1 +} + +//// [parserES5ComputedPropertyName10.js] +var C = (function () { + function C() { + this[e] = 1; + } + return C; +})(); diff --git a/tests/baselines/reference/parserES5ComputedPropertyName11.js b/tests/baselines/reference/parserES5ComputedPropertyName11.js new file mode 100644 index 00000000000..dfa74b03a5f --- /dev/null +++ b/tests/baselines/reference/parserES5ComputedPropertyName11.js @@ -0,0 +1,11 @@ +//// [parserES5ComputedPropertyName11.ts] +class C { + [e](); +} + +//// [parserES5ComputedPropertyName11.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserES5ComputedPropertyName2.js b/tests/baselines/reference/parserES5ComputedPropertyName2.js new file mode 100644 index 00000000000..861716a3cde --- /dev/null +++ b/tests/baselines/reference/parserES5ComputedPropertyName2.js @@ -0,0 +1,5 @@ +//// [parserES5ComputedPropertyName2.ts] +var v = { [e]: 1 }; + +//// [parserES5ComputedPropertyName2.js] +var v = { [e]: 1 }; diff --git a/tests/baselines/reference/parserES5ComputedPropertyName3.js b/tests/baselines/reference/parserES5ComputedPropertyName3.js new file mode 100644 index 00000000000..4e07049b29d --- /dev/null +++ b/tests/baselines/reference/parserES5ComputedPropertyName3.js @@ -0,0 +1,6 @@ +//// [parserES5ComputedPropertyName3.ts] +var v = { [e]() { } }; + +//// [parserES5ComputedPropertyName3.js] +var v = { [e]: function () { +} }; diff --git a/tests/baselines/reference/parserES5ComputedPropertyName4.js b/tests/baselines/reference/parserES5ComputedPropertyName4.js new file mode 100644 index 00000000000..50e240dcf20 --- /dev/null +++ b/tests/baselines/reference/parserES5ComputedPropertyName4.js @@ -0,0 +1,6 @@ +//// [parserES5ComputedPropertyName4.ts] +var v = { get [e]() { } }; + +//// [parserES5ComputedPropertyName4.js] +var v = { get [e]() { +} }; diff --git a/tests/baselines/reference/parserES5ComputedPropertyName5.js b/tests/baselines/reference/parserES5ComputedPropertyName5.js new file mode 100644 index 00000000000..c0eeae9b4aa --- /dev/null +++ b/tests/baselines/reference/parserES5ComputedPropertyName5.js @@ -0,0 +1,6 @@ +//// [parserES5ComputedPropertyName5.ts] +interface I { + [e]: number +} + +//// [parserES5ComputedPropertyName5.js] diff --git a/tests/baselines/reference/parserES5ComputedPropertyName6.js b/tests/baselines/reference/parserES5ComputedPropertyName6.js new file mode 100644 index 00000000000..a2fdae9c32e --- /dev/null +++ b/tests/baselines/reference/parserES5ComputedPropertyName6.js @@ -0,0 +1,10 @@ +//// [parserES5ComputedPropertyName6.ts] +enum E { + [e] = 1 +} + +//// [parserES5ComputedPropertyName6.js] +var E; +(function (E) { + E[E[e] = 1] = e; +})(E || (E = {})); diff --git a/tests/baselines/reference/parserES5ComputedPropertyName7.js b/tests/baselines/reference/parserES5ComputedPropertyName7.js new file mode 100644 index 00000000000..8634682c660 --- /dev/null +++ b/tests/baselines/reference/parserES5ComputedPropertyName7.js @@ -0,0 +1,11 @@ +//// [parserES5ComputedPropertyName7.ts] +class C { + [e] +} + +//// [parserES5ComputedPropertyName7.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserES5ComputedPropertyName8.js b/tests/baselines/reference/parserES5ComputedPropertyName8.js new file mode 100644 index 00000000000..3cbf49002f9 --- /dev/null +++ b/tests/baselines/reference/parserES5ComputedPropertyName8.js @@ -0,0 +1,5 @@ +//// [parserES5ComputedPropertyName8.ts] +var v: { [e]: number }; + +//// [parserES5ComputedPropertyName8.js] +var v; diff --git a/tests/baselines/reference/parserES5ComputedPropertyName9.js b/tests/baselines/reference/parserES5ComputedPropertyName9.js new file mode 100644 index 00000000000..fdefc8649d0 --- /dev/null +++ b/tests/baselines/reference/parserES5ComputedPropertyName9.js @@ -0,0 +1,11 @@ +//// [parserES5ComputedPropertyName9.ts] +class C { + [e]: Type +} + +//// [parserES5ComputedPropertyName9.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserEmptyParenthesizedExpression1.js b/tests/baselines/reference/parserEmptyParenthesizedExpression1.js new file mode 100644 index 00000000000..d8e6385db4c --- /dev/null +++ b/tests/baselines/reference/parserEmptyParenthesizedExpression1.js @@ -0,0 +1,9 @@ +//// [parserEmptyParenthesizedExpression1.ts] +function getObj() { + ().toString(); +} + +//// [parserEmptyParenthesizedExpression1.js] +function getObj() { + ().toString(); +} diff --git a/tests/baselines/reference/parserEnum1.js b/tests/baselines/reference/parserEnum1.js new file mode 100644 index 00000000000..8bd9d128233 --- /dev/null +++ b/tests/baselines/reference/parserEnum1.js @@ -0,0 +1,18 @@ +//// [parserEnum1.ts] + + + export enum SignatureFlags { + None = 0, + IsIndexer = 1, + IsStringIndexer = 1 << 1, + IsNumberIndexer = 1 << 2, + } + +//// [parserEnum1.js] +(function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["IsIndexer"] = 1] = "IsIndexer"; + SignatureFlags[SignatureFlags["IsStringIndexer"] = 1 << 1] = "IsStringIndexer"; + SignatureFlags[SignatureFlags["IsNumberIndexer"] = 1 << 2] = "IsNumberIndexer"; +})(exports.SignatureFlags || (exports.SignatureFlags = {})); +var SignatureFlags = exports.SignatureFlags; diff --git a/tests/baselines/reference/parserEnum2.js b/tests/baselines/reference/parserEnum2.js new file mode 100644 index 00000000000..22946153449 --- /dev/null +++ b/tests/baselines/reference/parserEnum2.js @@ -0,0 +1,18 @@ +//// [parserEnum2.ts] + + + export enum SignatureFlags { + None = 0, + IsIndexer = 1, + IsStringIndexer = 1 << 1, + IsNumberIndexer = 1 << 2 + } + +//// [parserEnum2.js] +(function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["IsIndexer"] = 1] = "IsIndexer"; + SignatureFlags[SignatureFlags["IsStringIndexer"] = 1 << 1] = "IsStringIndexer"; + SignatureFlags[SignatureFlags["IsNumberIndexer"] = 1 << 2] = "IsNumberIndexer"; +})(exports.SignatureFlags || (exports.SignatureFlags = {})); +var SignatureFlags = exports.SignatureFlags; diff --git a/tests/baselines/reference/parserEnum3.js b/tests/baselines/reference/parserEnum3.js new file mode 100644 index 00000000000..bbfb2039314 --- /dev/null +++ b/tests/baselines/reference/parserEnum3.js @@ -0,0 +1,10 @@ +//// [parserEnum3.ts] + + + export enum SignatureFlags { + } + +//// [parserEnum3.js] +(function (SignatureFlags) { +})(exports.SignatureFlags || (exports.SignatureFlags = {})); +var SignatureFlags = exports.SignatureFlags; diff --git a/tests/baselines/reference/parserEnum4.js b/tests/baselines/reference/parserEnum4.js new file mode 100644 index 00000000000..1bad7047486 --- /dev/null +++ b/tests/baselines/reference/parserEnum4.js @@ -0,0 +1,11 @@ +//// [parserEnum4.ts] + + + export enum SignatureFlags { + , + } + +//// [parserEnum4.js] +(function (SignatureFlags) { +})(exports.SignatureFlags || (exports.SignatureFlags = {})); +var SignatureFlags = exports.SignatureFlags; diff --git a/tests/baselines/reference/parserEnum5.js b/tests/baselines/reference/parserEnum5.js new file mode 100644 index 00000000000..50781f40dd7 --- /dev/null +++ b/tests/baselines/reference/parserEnum5.js @@ -0,0 +1,24 @@ +//// [parserEnum5.ts] +enum E2 { a, } +enum E3 { a: 1, } +enum E1 { a, b: 1, c, d: 2 = 3 } + +//// [parserEnum5.js] +var E2; +(function (E2) { + E2[E2["a"] = 0] = "a"; +})(E2 || (E2 = {})); +var E3; +(function (E3) { + E3[E3["a"] = 0] = "a"; + E3[E3["1"] = 1] = "1"; +})(E3 || (E3 = {})); +var E1; +(function (E1) { + E1[E1["a"] = 0] = "a"; + E1[E1["b"] = 1] = "b"; + E1[E1["1"] = 2] = "1"; + E1[E1["c"] = 3] = "c"; + E1[E1["d"] = 4] = "d"; + E1[E1["2"] = 3] = "2"; +})(E1 || (E1 = {})); diff --git a/tests/baselines/reference/parserEnumDeclaration2.js b/tests/baselines/reference/parserEnumDeclaration2.js new file mode 100644 index 00000000000..a97b8cf9044 --- /dev/null +++ b/tests/baselines/reference/parserEnumDeclaration2.js @@ -0,0 +1,7 @@ +//// [parserEnumDeclaration2.ts] +declare module M { + declare enum E { + } +} + +//// [parserEnumDeclaration2.js] diff --git a/tests/baselines/reference/parserEnumDeclaration4.js b/tests/baselines/reference/parserEnumDeclaration4.js new file mode 100644 index 00000000000..47450d419e1 --- /dev/null +++ b/tests/baselines/reference/parserEnumDeclaration4.js @@ -0,0 +1,9 @@ +//// [parserEnumDeclaration4.ts] +enum void { +} + +//// [parserEnumDeclaration4.js] +var ; +(function () { +})( || ( = {})); +void {}; diff --git a/tests/baselines/reference/parserEnumDeclaration6.js b/tests/baselines/reference/parserEnumDeclaration6.js new file mode 100644 index 00000000000..5810ffc0620 --- /dev/null +++ b/tests/baselines/reference/parserEnumDeclaration6.js @@ -0,0 +1,16 @@ +//// [parserEnumDeclaration6.ts] +enum E { + A = 1, + B, + C = 1 << 1, + D, +} + +//// [parserEnumDeclaration6.js] +var E; +(function (E) { + E[E["A"] = 1] = "A"; + E[E["B"] = 2] = "B"; + E[E["C"] = 1 << 1] = "C"; + E[E["D"] = undefined] = "D"; +})(E || (E = {})); diff --git a/tests/baselines/reference/parserEqualsGreaterThanAfterFunction1.js b/tests/baselines/reference/parserEqualsGreaterThanAfterFunction1.js new file mode 100644 index 00000000000..5358a25fd82 --- /dev/null +++ b/tests/baselines/reference/parserEqualsGreaterThanAfterFunction1.js @@ -0,0 +1,4 @@ +//// [parserEqualsGreaterThanAfterFunction1.ts] +function => + +//// [parserEqualsGreaterThanAfterFunction1.js] diff --git a/tests/baselines/reference/parserEqualsGreaterThanAfterFunction2.js b/tests/baselines/reference/parserEqualsGreaterThanAfterFunction2.js new file mode 100644 index 00000000000..a0c210486a3 --- /dev/null +++ b/tests/baselines/reference/parserEqualsGreaterThanAfterFunction2.js @@ -0,0 +1,4 @@ +//// [parserEqualsGreaterThanAfterFunction2.ts] +function (a => b; + +//// [parserEqualsGreaterThanAfterFunction2.js] diff --git a/tests/baselines/reference/parserErrantAccessibilityModifierInModule1.js b/tests/baselines/reference/parserErrantAccessibilityModifierInModule1.js new file mode 100644 index 00000000000..be0bb67511d --- /dev/null +++ b/tests/baselines/reference/parserErrantAccessibilityModifierInModule1.js @@ -0,0 +1,14 @@ +//// [parserErrantAccessibilityModifierInModule1.ts] +module M { + var x=10; // variable local to this module body + private y=x; // property visible only in module + export var z=y; // property visible to any code +} + +//// [parserErrantAccessibilityModifierInModule1.js] +var M; +(function (M) { + var x = 10; // variable local to this module body + y = x; // property visible only in module + M.z = y; // property visible to any code +})(M || (M = {})); diff --git a/tests/baselines/reference/parserErrantEqualsGreaterThanAfterFunction1.js b/tests/baselines/reference/parserErrantEqualsGreaterThanAfterFunction1.js new file mode 100644 index 00000000000..c1b2f517b45 --- /dev/null +++ b/tests/baselines/reference/parserErrantEqualsGreaterThanAfterFunction1.js @@ -0,0 +1,5 @@ +//// [parserErrantEqualsGreaterThanAfterFunction1.ts] +function f() => 4; + +//// [parserErrantEqualsGreaterThanAfterFunction1.js] +4; diff --git a/tests/baselines/reference/parserErrantEqualsGreaterThanAfterFunction2.js b/tests/baselines/reference/parserErrantEqualsGreaterThanAfterFunction2.js new file mode 100644 index 00000000000..5b4b71cab1f --- /dev/null +++ b/tests/baselines/reference/parserErrantEqualsGreaterThanAfterFunction2.js @@ -0,0 +1,5 @@ +//// [parserErrantEqualsGreaterThanAfterFunction2.ts] +function f(p: A) => p; + +//// [parserErrantEqualsGreaterThanAfterFunction2.js] +p; diff --git a/tests/baselines/reference/parserErrantSemicolonInClass1.js b/tests/baselines/reference/parserErrantSemicolonInClass1.js new file mode 100644 index 00000000000..2f38e2b5323 --- /dev/null +++ b/tests/baselines/reference/parserErrantSemicolonInClass1.js @@ -0,0 +1,73 @@ +//// [parserErrantSemicolonInClass1.ts] +class a { + //constructor (); + constructor (n: number); + constructor (s: string); + constructor (ns: any) { + + } + + public pgF() { }; + + public pv; + public get d() { + return 30; + } + public set d() { + } + + public static get p2() { + return { x: 30, y: 40 }; + } + + private static d2() { + } + private static get p3() { + return "string"; + } + private pv3; + + private foo(n: number): string; + private foo(s: string): string; + private foo(ns: any) { + return ns.toString(); + } +} + + +//// [parserErrantSemicolonInClass1.js] +var a = (function () { + function a(ns) { + } + a.prototype.pgF = function () { + }; + Object.defineProperty(a.prototype, "d", { + get: function () { + return 30; + }, + set: function () { + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(a, "p2", { + get: function () { + return { x: 30, y: 40 }; + }, + enumerable: true, + configurable: true + }); + a.d2 = function () { + }; + Object.defineProperty(a, "p3", { + get: function () { + return "string"; + }, + enumerable: true, + configurable: true + }); + a.prototype.foo = function (ns) { + return ns.toString(); + }; + return a; +})(); diff --git a/tests/baselines/reference/parserErrorRecoveryArrayLiteralExpression1.js b/tests/baselines/reference/parserErrorRecoveryArrayLiteralExpression1.js new file mode 100644 index 00000000000..1ed36d8dac5 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecoveryArrayLiteralExpression1.js @@ -0,0 +1,6 @@ +//// [parserErrorRecoveryArrayLiteralExpression1.ts] +var v = [1, 2, 3 +4, 5, 6, 7]; + +//// [parserErrorRecoveryArrayLiteralExpression1.js] +var v = [1, 2, 3, 4, 5, 6, 7]; diff --git a/tests/baselines/reference/parserErrorRecoveryArrayLiteralExpression2.js b/tests/baselines/reference/parserErrorRecoveryArrayLiteralExpression2.js new file mode 100644 index 00000000000..c5386a2b6a2 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecoveryArrayLiteralExpression2.js @@ -0,0 +1,8 @@ +//// [parserErrorRecoveryArrayLiteralExpression2.ts] +var points = [-0.6961439251899719, 1.207661509513855, 0.19374050199985504, -0 + + .7042760848999023, 1.1955541372299194, 0.19600726664066315, -0.7120069861412048]; + + +//// [parserErrorRecoveryArrayLiteralExpression2.js] +var points = [-0.6961439251899719, 1.207661509513855, 0.19374050199985504, -0, .7042760848999023, 1.1955541372299194, 0.19600726664066315, -0.7120069861412048]; diff --git a/tests/baselines/reference/parserErrorRecoveryArrayLiteralExpression3.js b/tests/baselines/reference/parserErrorRecoveryArrayLiteralExpression3.js new file mode 100644 index 00000000000..c366c750cc7 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecoveryArrayLiteralExpression3.js @@ -0,0 +1,9 @@ +//// [parserErrorRecoveryArrayLiteralExpression3.ts] + +var texCoords = [2, 2, 0.5000001192092895, 0.8749999 ; 403953552, 0.5000001192092895, 0.8749999403953552]; + + +//// [parserErrorRecoveryArrayLiteralExpression3.js] +var texCoords = [2, 2, 0.5000001192092895, 0.8749999]; +403953552, 0.5000001192092895, 0.8749999403953552; +; diff --git a/tests/baselines/reference/parserErrorRecoveryIfStatement1.js b/tests/baselines/reference/parserErrorRecoveryIfStatement1.js new file mode 100644 index 00000000000..662f3056a3d --- /dev/null +++ b/tests/baselines/reference/parserErrorRecoveryIfStatement1.js @@ -0,0 +1,25 @@ +//// [parserErrorRecoveryIfStatement1.ts] +class Foo { + f1() { + if ( + } + f2() { + } + f3() { + } +} + +//// [parserErrorRecoveryIfStatement1.js] +var Foo = (function () { + function Foo() { + } + Foo.prototype.f1 = function () { + if () + ; + }; + Foo.prototype.f2 = function () { + }; + Foo.prototype.f3 = function () { + }; + return Foo; +})(); diff --git a/tests/baselines/reference/parserErrorRecoveryIfStatement2.js b/tests/baselines/reference/parserErrorRecoveryIfStatement2.js new file mode 100644 index 00000000000..171f3072535 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecoveryIfStatement2.js @@ -0,0 +1,25 @@ +//// [parserErrorRecoveryIfStatement2.ts] +class Foo { + f1() { + if (a + } + f2() { + } + f3() { + } +} + +//// [parserErrorRecoveryIfStatement2.js] +var Foo = (function () { + function Foo() { + } + Foo.prototype.f1 = function () { + if (a) + ; + }; + Foo.prototype.f2 = function () { + }; + Foo.prototype.f3 = function () { + }; + return Foo; +})(); diff --git a/tests/baselines/reference/parserErrorRecoveryIfStatement3.js b/tests/baselines/reference/parserErrorRecoveryIfStatement3.js new file mode 100644 index 00000000000..117525bcba0 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecoveryIfStatement3.js @@ -0,0 +1,25 @@ +//// [parserErrorRecoveryIfStatement3.ts] +class Foo { + f1() { + if (a.b + } + f2() { + } + f3() { + } +} + +//// [parserErrorRecoveryIfStatement3.js] +var Foo = (function () { + function Foo() { + } + Foo.prototype.f1 = function () { + if (a.b) + ; + }; + Foo.prototype.f2 = function () { + }; + Foo.prototype.f3 = function () { + }; + return Foo; +})(); diff --git a/tests/baselines/reference/parserErrorRecoveryIfStatement4.js b/tests/baselines/reference/parserErrorRecoveryIfStatement4.js new file mode 100644 index 00000000000..460ca957c02 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecoveryIfStatement4.js @@ -0,0 +1,25 @@ +//// [parserErrorRecoveryIfStatement4.ts] +class Foo { + f1() { + if (a.b) + } + f2() { + } + f3() { + } +} + +//// [parserErrorRecoveryIfStatement4.js] +var Foo = (function () { + function Foo() { + } + Foo.prototype.f1 = function () { + if (a.b) + ; + }; + Foo.prototype.f2 = function () { + }; + Foo.prototype.f3 = function () { + }; + return Foo; +})(); diff --git a/tests/baselines/reference/parserErrorRecoveryIfStatement5.js b/tests/baselines/reference/parserErrorRecoveryIfStatement5.js new file mode 100644 index 00000000000..8df07082c42 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecoveryIfStatement5.js @@ -0,0 +1,27 @@ +//// [parserErrorRecoveryIfStatement5.ts] +class Foo { + f1() { + if (a.b) { + } + f2() { + } + f3() { + } +} + +//// [parserErrorRecoveryIfStatement5.js] +var Foo = (function () { + function Foo() { + } + Foo.prototype.f1 = function () { + if (a.b) { + } + f2(); + { + } + f3(); + { + } + }; + return Foo; +})(); diff --git a/tests/baselines/reference/parserErrorRecoveryIfStatement6.js b/tests/baselines/reference/parserErrorRecoveryIfStatement6.js new file mode 100644 index 00000000000..fa327a73814 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecoveryIfStatement6.js @@ -0,0 +1,26 @@ +//// [parserErrorRecoveryIfStatement6.ts] +class Foo { + f1() { + if (a.b) { + } + public f2() { + } + f3() { + } +} + + +//// [parserErrorRecoveryIfStatement6.js] +var Foo = (function () { + function Foo() { + } + Foo.prototype.f1 = function () { + if (a.b) { + } + }; + Foo.prototype.f2 = function () { + }; + Foo.prototype.f3 = function () { + }; + return Foo; +})(); diff --git a/tests/baselines/reference/parserErrorRecovery_ArgumentList1.js b/tests/baselines/reference/parserErrorRecovery_ArgumentList1.js new file mode 100644 index 00000000000..86bbf4494f4 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ArgumentList1.js @@ -0,0 +1,11 @@ +//// [parserErrorRecovery_ArgumentList1.ts] +function foo() { + bar( + return x; +} + +//// [parserErrorRecovery_ArgumentList1.js] +function foo() { + bar(); + return x; +} diff --git a/tests/baselines/reference/parserErrorRecovery_ArgumentList2.js b/tests/baselines/reference/parserErrorRecovery_ArgumentList2.js new file mode 100644 index 00000000000..14f6b67c868 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ArgumentList2.js @@ -0,0 +1,9 @@ +//// [parserErrorRecovery_ArgumentList2.ts] +function foo() { + bar(; +} + +//// [parserErrorRecovery_ArgumentList2.js] +function foo() { + bar(); +} diff --git a/tests/baselines/reference/parserErrorRecovery_ArgumentList3.js b/tests/baselines/reference/parserErrorRecovery_ArgumentList3.js new file mode 100644 index 00000000000..ab76ec173fb --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ArgumentList3.js @@ -0,0 +1,11 @@ +//// [parserErrorRecovery_ArgumentList3.ts] +function foo() { + bar(a, + return; +} + +//// [parserErrorRecovery_ArgumentList3.js] +function foo() { + bar(a); + return; +} diff --git a/tests/baselines/reference/parserErrorRecovery_ArgumentList4.js b/tests/baselines/reference/parserErrorRecovery_ArgumentList4.js new file mode 100644 index 00000000000..2557faacba5 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ArgumentList4.js @@ -0,0 +1,11 @@ +//// [parserErrorRecovery_ArgumentList4.ts] +function foo() { + bar(a,b + return; +} + +//// [parserErrorRecovery_ArgumentList4.js] +function foo() { + bar(a, b); + return; +} diff --git a/tests/baselines/reference/parserErrorRecovery_ArgumentList5.js b/tests/baselines/reference/parserErrorRecovery_ArgumentList5.js new file mode 100644 index 00000000000..bbb65a44e07 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ArgumentList5.js @@ -0,0 +1,11 @@ +//// [parserErrorRecovery_ArgumentList5.ts] +function foo() { + bar(a,) + return; +} + +//// [parserErrorRecovery_ArgumentList5.js] +function foo() { + bar(a); + return; +} diff --git a/tests/baselines/reference/parserErrorRecovery_ArgumentList6.js b/tests/baselines/reference/parserErrorRecovery_ArgumentList6.js new file mode 100644 index 00000000000..16b52248d54 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ArgumentList6.js @@ -0,0 +1,5 @@ +//// [parserErrorRecovery_ArgumentList6.ts] +Foo(, + +//// [parserErrorRecovery_ArgumentList6.js] +Foo(); diff --git a/tests/baselines/reference/parserErrorRecovery_ArgumentList7.js b/tests/baselines/reference/parserErrorRecovery_ArgumentList7.js new file mode 100644 index 00000000000..94eba9445e9 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ArgumentList7.js @@ -0,0 +1,5 @@ +//// [parserErrorRecovery_ArgumentList7.ts] +Foo(a,, + +//// [parserErrorRecovery_ArgumentList7.js] +Foo(a, ); diff --git a/tests/baselines/reference/parserErrorRecovery_Block1.js b/tests/baselines/reference/parserErrorRecovery_Block1.js new file mode 100644 index 00000000000..cdcd5856fa6 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_Block1.js @@ -0,0 +1,11 @@ +//// [parserErrorRecovery_Block1.ts] +function f() { + 1 + + return; +} + +//// [parserErrorRecovery_Block1.js] +function f() { + 1 + ; + return; +} diff --git a/tests/baselines/reference/parserErrorRecovery_Block2.js b/tests/baselines/reference/parserErrorRecovery_Block2.js new file mode 100644 index 00000000000..24ddaf0db3f --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_Block2.js @@ -0,0 +1,10 @@ +//// [parserErrorRecovery_Block2.ts] +function f() { + # + return; +} + +//// [parserErrorRecovery_Block2.js] +function f() { + return; +} diff --git a/tests/baselines/reference/parserErrorRecovery_Block3.js b/tests/baselines/reference/parserErrorRecovery_Block3.js new file mode 100644 index 00000000000..30183fb7d8b --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_Block3.js @@ -0,0 +1,18 @@ +//// [parserErrorRecovery_Block3.ts] +class C { + private a(): boolean { + + private b(): boolean { + } +} + +//// [parserErrorRecovery_Block3.js] +var C = (function () { + function C() { + } + C.prototype.a = function () { + }; + C.prototype.b = function () { + }; + return C; +})(); diff --git a/tests/baselines/reference/parserErrorRecovery_ClassElement1.js b/tests/baselines/reference/parserErrorRecovery_ClassElement1.js new file mode 100644 index 00000000000..7a3bf441e47 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ClassElement1.js @@ -0,0 +1,21 @@ +//// [parserErrorRecovery_ClassElement1.ts] +class C { + +// Classes can't be nested. So we should bail out of parsing here and recover +// this as a source unit element. +class D { +} + +//// [parserErrorRecovery_ClassElement1.js] +var C = (function () { + function C() { + } + return C; +})(); +// Classes can't be nested. So we should bail out of parsing here and recover +// this as a source unit element. +var D = (function () { + function D() { + } + return D; +})(); diff --git a/tests/baselines/reference/parserErrorRecovery_ClassElement2.js b/tests/baselines/reference/parserErrorRecovery_ClassElement2.js new file mode 100644 index 00000000000..fca227a4e8a --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ClassElement2.js @@ -0,0 +1,20 @@ +//// [parserErrorRecovery_ClassElement2.ts] +module M { + class C { + + enum E { + } +} + +//// [parserErrorRecovery_ClassElement2.js] +var M; +(function (M) { + var C = (function () { + function C() { + } + return C; + })(); + var E; + (function (E) { + })(E || (E = {})); +})(M || (M = {})); diff --git a/tests/baselines/reference/parserErrorRecovery_ClassElement3.js b/tests/baselines/reference/parserErrorRecovery_ClassElement3.js new file mode 100644 index 00000000000..39e701628bb --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ClassElement3.js @@ -0,0 +1,21 @@ +//// [parserErrorRecovery_ClassElement3.ts] +module M { + # + class C { + } + @ + enum E { + # + +//// [parserErrorRecovery_ClassElement3.js] +var M; +(function (M) { + var C = (function () { + function C() { + } + return C; + })(); + var E; + (function (E) { + })(E || (E = {})); +})(M || (M = {})); diff --git a/tests/baselines/reference/parserErrorRecovery_Expression1.js b/tests/baselines/reference/parserErrorRecovery_Expression1.js new file mode 100644 index 00000000000..b2c9d64945c --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_Expression1.js @@ -0,0 +1,5 @@ +//// [parserErrorRecovery_Expression1.ts] +var v = ()({}); + +//// [parserErrorRecovery_Expression1.js] +var v = ()({}); diff --git a/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause1.js b/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause1.js new file mode 100644 index 00000000000..b6557221c65 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause1.js @@ -0,0 +1,10 @@ +//// [parserErrorRecovery_ExtendsOrImplementsClause1.ts] +class C extends { +} + +//// [parserErrorRecovery_ExtendsOrImplementsClause1.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause2.js b/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause2.js new file mode 100644 index 00000000000..babceb0f752 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause2.js @@ -0,0 +1,18 @@ +//// [parserErrorRecovery_ExtendsOrImplementsClause2.ts] +class C extends A, { +} + +//// [parserErrorRecovery_ExtendsOrImplementsClause2.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function (_super) { + __extends(C, _super); + function C() { + _super.apply(this, arguments); + } + return C; +})(A); diff --git a/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause3.js b/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause3.js new file mode 100644 index 00000000000..b420e12cccb --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause3.js @@ -0,0 +1,10 @@ +//// [parserErrorRecovery_ExtendsOrImplementsClause3.ts] +class C extends implements A { +} + +//// [parserErrorRecovery_ExtendsOrImplementsClause3.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause4.js b/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause4.js new file mode 100644 index 00000000000..5c0e793173a --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause4.js @@ -0,0 +1,18 @@ +//// [parserErrorRecovery_ExtendsOrImplementsClause4.ts] +class C extends A implements { +} + +//// [parserErrorRecovery_ExtendsOrImplementsClause4.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function (_super) { + __extends(C, _super); + function C() { + _super.apply(this, arguments); + } + return C; +})(A); diff --git a/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause5.js b/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause5.js new file mode 100644 index 00000000000..40dbcf61820 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause5.js @@ -0,0 +1,18 @@ +//// [parserErrorRecovery_ExtendsOrImplementsClause5.ts] +class C extends A, implements B, { +} + +//// [parserErrorRecovery_ExtendsOrImplementsClause5.js] +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +var C = (function (_super) { + __extends(C, _super); + function C() { + _super.apply(this, arguments); + } + return C; +})(A); diff --git a/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause6.js b/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause6.js new file mode 100644 index 00000000000..02c357e5f46 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ExtendsOrImplementsClause6.js @@ -0,0 +1,4 @@ +//// [parserErrorRecovery_ExtendsOrImplementsClause6.ts] +interface I extends { } + +//// [parserErrorRecovery_ExtendsOrImplementsClause6.js] diff --git a/tests/baselines/reference/parserErrorRecovery_IncompleteMemberVariable1.js b/tests/baselines/reference/parserErrorRecovery_IncompleteMemberVariable1.js new file mode 100644 index 00000000000..c26b16b5a0a --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_IncompleteMemberVariable1.js @@ -0,0 +1,55 @@ +//// [parserErrorRecovery_IncompleteMemberVariable1.ts] +// Interface +interface IPoint { + getDist(): number; +} + +// Module +module Shapes { + + // Class + export class Point implements IPoint { + + public con: "hello"; + // Constructor + constructor (public x: number, public y: number) { } + + // Instance member + getDist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Static member + static origin = new Point(0, 0); + } + +} + +// Local variables +var p: IPoint = new Shapes.Point(3, 4); +var dist = p.getDist(); + + +//// [parserErrorRecovery_IncompleteMemberVariable1.js] +// Module +var Shapes; +(function (Shapes) { + // Class + var Point = (function () { + // Constructor + function Point(x, y) { + this.x = x; + this.y = y; + this.con = "hello"; + } + // Instance member + Point.prototype.getDist = function () { + return Math.sqrt(this.x * this.x + this.y * this.y); + }; + // Static member + Point.origin = new Point(0, 0); + return Point; + })(); + Shapes.Point = Point; +})(Shapes || (Shapes = {})); +// Local variables +var p = new Shapes.Point(3, 4); +var dist = p.getDist(); diff --git a/tests/baselines/reference/parserErrorRecovery_IncompleteMemberVariable2.js b/tests/baselines/reference/parserErrorRecovery_IncompleteMemberVariable2.js new file mode 100644 index 00000000000..866f96a8030 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_IncompleteMemberVariable2.js @@ -0,0 +1,55 @@ +//// [parserErrorRecovery_IncompleteMemberVariable2.ts] +// Interface +interface IPoint { + getDist(): number; +} + +// Module +module Shapes { + + // Class + export class Point implements IPoint { + + public con:C "hello"; + // Constructor + constructor (public x: number, public y: number) { } + + // Instance member + getDist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Static member + static origin = new Point(0, 0); + } + +} + +// Local variables +var p: IPoint = new Shapes.Point(3, 4); +var dist = p.getDist(); + + +//// [parserErrorRecovery_IncompleteMemberVariable2.js] +// Module +var Shapes; +(function (Shapes) { + // Class + var Point = (function () { + // Constructor + function Point(x, y) { + this.x = x; + this.y = y; + this.con = "hello"; + } + // Instance member + Point.prototype.getDist = function () { + return Math.sqrt(this.x * this.x + this.y * this.y); + }; + // Static member + Point.origin = new Point(0, 0); + return Point; + })(); + Shapes.Point = Point; +})(Shapes || (Shapes = {})); +// Local variables +var p = new Shapes.Point(3, 4); +var dist = p.getDist(); diff --git a/tests/baselines/reference/parserErrorRecovery_LeftShift1.js b/tests/baselines/reference/parserErrorRecovery_LeftShift1.js new file mode 100644 index 00000000000..69392c15be1 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_LeftShift1.js @@ -0,0 +1,6 @@ +//// [parserErrorRecovery_LeftShift1.ts] +retValue = bfs.VARIABLES >> ); + +//// [parserErrorRecovery_LeftShift1.js] +retValue = bfs.VARIABLES >> ; +; diff --git a/tests/baselines/reference/parserErrorRecovery_ModuleElement1.js b/tests/baselines/reference/parserErrorRecovery_ModuleElement1.js new file mode 100644 index 00000000000..27febb99c86 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ModuleElement1.js @@ -0,0 +1,9 @@ +//// [parserErrorRecovery_ModuleElement1.ts] +return foo; +} +return bar; +} + +//// [parserErrorRecovery_ModuleElement1.js] +return foo; +return bar; diff --git a/tests/baselines/reference/parserErrorRecovery_ModuleElement2.js b/tests/baselines/reference/parserErrorRecovery_ModuleElement2.js new file mode 100644 index 00000000000..722ccbc787c --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ModuleElement2.js @@ -0,0 +1,15 @@ +//// [parserErrorRecovery_ModuleElement2.ts] +function foo() { +} + +function foo() { +} + +) +) + +//// [parserErrorRecovery_ModuleElement2.js] +function foo() { +} +function foo() { +} diff --git a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral1.js b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral1.js new file mode 100644 index 00000000000..dbf89fec52b --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral1.js @@ -0,0 +1,5 @@ +//// [parserErrorRecovery_ObjectLiteral1.ts] +var v = { a: 1 b: 2 } + +//// [parserErrorRecovery_ObjectLiteral1.js] +var v = { a: 1, b: 2 }; diff --git a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.js b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.js new file mode 100644 index 00000000000..08dc96d38ef --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral2.js @@ -0,0 +1,6 @@ +//// [parserErrorRecovery_ObjectLiteral2.ts] +var v = { a +return; + +//// [parserErrorRecovery_ObjectLiteral2.js] +var v = { a: , return: }; diff --git a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral3.js b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral3.js new file mode 100644 index 00000000000..1ea23d59112 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral3.js @@ -0,0 +1,6 @@ +//// [parserErrorRecovery_ObjectLiteral3.ts] +var v = { a: +return; + +//// [parserErrorRecovery_ObjectLiteral3.js] +var v = { a: , return: }; diff --git a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral4.js b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral4.js new file mode 100644 index 00000000000..4fe49788740 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral4.js @@ -0,0 +1,6 @@ +//// [parserErrorRecovery_ObjectLiteral4.ts] +var v = { a: 1 +return; + +//// [parserErrorRecovery_ObjectLiteral4.js] +var v = { a: 1, return: }; diff --git a/tests/baselines/reference/parserErrorRecovery_ObjectLiteral5.js b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral5.js new file mode 100644 index 00000000000..cf55b59c711 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ObjectLiteral5.js @@ -0,0 +1,6 @@ +//// [parserErrorRecovery_ObjectLiteral5.ts] +var v = { a: 1, +return; + +//// [parserErrorRecovery_ObjectLiteral5.js] +var v = { a: 1, return: }; diff --git a/tests/baselines/reference/parserErrorRecovery_ParameterList1.js b/tests/baselines/reference/parserErrorRecovery_ParameterList1.js new file mode 100644 index 00000000000..0a9e78b59cf --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ParameterList1.js @@ -0,0 +1,5 @@ +//// [parserErrorRecovery_ParameterList1.ts] +function f(a { +} + +//// [parserErrorRecovery_ParameterList1.js] diff --git a/tests/baselines/reference/parserErrorRecovery_ParameterList2.js b/tests/baselines/reference/parserErrorRecovery_ParameterList2.js new file mode 100644 index 00000000000..9f85762a89a --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ParameterList2.js @@ -0,0 +1,5 @@ +//// [parserErrorRecovery_ParameterList2.ts] +function f(a, { +} + +//// [parserErrorRecovery_ParameterList2.js] diff --git a/tests/baselines/reference/parserErrorRecovery_ParameterList3.js b/tests/baselines/reference/parserErrorRecovery_ParameterList3.js new file mode 100644 index 00000000000..4c20e676f40 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ParameterList3.js @@ -0,0 +1,7 @@ +//// [parserErrorRecovery_ParameterList3.ts] +function f(a,) { +} + +//// [parserErrorRecovery_ParameterList3.js] +function f(a) { +} diff --git a/tests/baselines/reference/parserErrorRecovery_ParameterList4.js b/tests/baselines/reference/parserErrorRecovery_ParameterList4.js new file mode 100644 index 00000000000..53775cad92e --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ParameterList4.js @@ -0,0 +1,7 @@ +//// [parserErrorRecovery_ParameterList4.ts] +function f(a,#) { +} + +//// [parserErrorRecovery_ParameterList4.js] +function f(a) { +} diff --git a/tests/baselines/reference/parserErrorRecovery_ParameterList5.js b/tests/baselines/reference/parserErrorRecovery_ParameterList5.js new file mode 100644 index 00000000000..7ff32fd1873 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ParameterList5.js @@ -0,0 +1,5 @@ +//// [parserErrorRecovery_ParameterList5.ts] +(a:number => { } + +//// [parserErrorRecovery_ParameterList5.js] +(); diff --git a/tests/baselines/reference/parserErrorRecovery_ParameterList6.js b/tests/baselines/reference/parserErrorRecovery_ParameterList6.js new file mode 100644 index 00000000000..e83c045208d --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_ParameterList6.js @@ -0,0 +1,15 @@ +//// [parserErrorRecovery_ParameterList6.ts] +class Foo { + public banana (x: break) { } +} + +//// [parserErrorRecovery_ParameterList6.js] +var Foo = (function () { + function Foo() { + } + Foo.prototype.banana = ; + return Foo; +})(); +break ; +{ +} diff --git a/tests/baselines/reference/parserErrorRecovery_SourceUnit1.js b/tests/baselines/reference/parserErrorRecovery_SourceUnit1.js new file mode 100644 index 00000000000..a4b6427508f --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_SourceUnit1.js @@ -0,0 +1,18 @@ +//// [parserErrorRecovery_SourceUnit1.ts] +class C { +} +} +class D { +} + +//// [parserErrorRecovery_SourceUnit1.js] +var C = (function () { + function C() { + } + return C; +})(); +var D = (function () { + function D() { + } + return D; +})(); diff --git a/tests/baselines/reference/parserErrorRecovery_SwitchStatement1.js b/tests/baselines/reference/parserErrorRecovery_SwitchStatement1.js new file mode 100644 index 00000000000..63591985d1e --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_SwitchStatement1.js @@ -0,0 +1,17 @@ +//// [parserErrorRecovery_SwitchStatement1.ts] +switch (e) { + case 1: + 1 + + case 2: + 1 + + default: +} + +//// [parserErrorRecovery_SwitchStatement1.js] +switch (e) { + case 1: + 1 + ; + case 2: + 1 + ; + default: +} diff --git a/tests/baselines/reference/parserErrorRecovery_SwitchStatement2.js b/tests/baselines/reference/parserErrorRecovery_SwitchStatement2.js new file mode 100644 index 00000000000..d7000bc23d7 --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_SwitchStatement2.js @@ -0,0 +1,21 @@ +//// [parserErrorRecovery_SwitchStatement2.ts] +class C { + constructor() { + switch (e) { + +class D { +} + +//// [parserErrorRecovery_SwitchStatement2.js] +var C = (function () { + function C() { + switch (e) { + } + } + return C; +})(); +var D = (function () { + function D() { + } + return D; +})(); diff --git a/tests/baselines/reference/parserErrorRecovery_VariableList1.js b/tests/baselines/reference/parserErrorRecovery_VariableList1.js new file mode 100644 index 00000000000..acd4451fded --- /dev/null +++ b/tests/baselines/reference/parserErrorRecovery_VariableList1.js @@ -0,0 +1,7 @@ +//// [parserErrorRecovery_VariableList1.ts] +var a, +return; + +//// [parserErrorRecovery_VariableList1.js] +var a; +return; diff --git a/tests/baselines/reference/parserExportAssignment1.js b/tests/baselines/reference/parserExportAssignment1.js new file mode 100644 index 00000000000..5f3c0e1513f --- /dev/null +++ b/tests/baselines/reference/parserExportAssignment1.js @@ -0,0 +1,4 @@ +//// [parserExportAssignment1.ts] +export = foo + +//// [parserExportAssignment1.js] diff --git a/tests/baselines/reference/parserExportAssignment2.js b/tests/baselines/reference/parserExportAssignment2.js new file mode 100644 index 00000000000..aaa12cea179 --- /dev/null +++ b/tests/baselines/reference/parserExportAssignment2.js @@ -0,0 +1,4 @@ +//// [parserExportAssignment2.ts] +export = foo; + +//// [parserExportAssignment2.js] diff --git a/tests/baselines/reference/parserExportAssignment3.js b/tests/baselines/reference/parserExportAssignment3.js new file mode 100644 index 00000000000..13e04c3607a --- /dev/null +++ b/tests/baselines/reference/parserExportAssignment3.js @@ -0,0 +1,4 @@ +//// [parserExportAssignment3.ts] +export = + +//// [parserExportAssignment3.js] diff --git a/tests/baselines/reference/parserExportAssignment4.js b/tests/baselines/reference/parserExportAssignment4.js new file mode 100644 index 00000000000..7cfd8206dbe --- /dev/null +++ b/tests/baselines/reference/parserExportAssignment4.js @@ -0,0 +1,4 @@ +//// [parserExportAssignment4.ts] +export = ; + +//// [parserExportAssignment4.js] diff --git a/tests/baselines/reference/parserExportAssignment5.js b/tests/baselines/reference/parserExportAssignment5.js new file mode 100644 index 00000000000..ac2a1202e5e --- /dev/null +++ b/tests/baselines/reference/parserExportAssignment5.js @@ -0,0 +1,9 @@ +//// [parserExportAssignment5.ts] +module M { + export = A; +} + +//// [parserExportAssignment5.js] +var M; +(function (M) { +})(M || (M = {})); diff --git a/tests/baselines/reference/parserExportAssignment7.js b/tests/baselines/reference/parserExportAssignment7.js new file mode 100644 index 00000000000..52f9848c243 --- /dev/null +++ b/tests/baselines/reference/parserExportAssignment7.js @@ -0,0 +1,13 @@ +//// [parserExportAssignment7.ts] +export class C { +} + +export = B; + +//// [parserExportAssignment7.js] +var C = (function () { + function C() { + } + return C; +})(); +exports.C = C; diff --git a/tests/baselines/reference/parserExportAssignment8.js b/tests/baselines/reference/parserExportAssignment8.js new file mode 100644 index 00000000000..3c5b851284e --- /dev/null +++ b/tests/baselines/reference/parserExportAssignment8.js @@ -0,0 +1,13 @@ +//// [parserExportAssignment8.ts] +export = B; + +export class C { +} + +//// [parserExportAssignment8.js] +var C = (function () { + function C() { + } + return C; +})(); +exports.C = C; diff --git a/tests/baselines/reference/parserForInStatement2.js b/tests/baselines/reference/parserForInStatement2.js new file mode 100644 index 00000000000..9f522eadc5d --- /dev/null +++ b/tests/baselines/reference/parserForInStatement2.js @@ -0,0 +1,7 @@ +//// [parserForInStatement2.ts] +for (var in X) { +} + +//// [parserForInStatement2.js] +for ( in X) { +} diff --git a/tests/baselines/reference/parserForInStatement3.js b/tests/baselines/reference/parserForInStatement3.js new file mode 100644 index 00000000000..4964c108ca0 --- /dev/null +++ b/tests/baselines/reference/parserForInStatement3.js @@ -0,0 +1,7 @@ +//// [parserForInStatement3.ts] +for (var a, b in X) { +} + +//// [parserForInStatement3.js] +for (var a in X) { +} diff --git a/tests/baselines/reference/parserForInStatement6.js b/tests/baselines/reference/parserForInStatement6.js new file mode 100644 index 00000000000..b80d13f3184 --- /dev/null +++ b/tests/baselines/reference/parserForInStatement6.js @@ -0,0 +1,7 @@ +//// [parserForInStatement6.ts] +for (var a = 1, b = 2 in X) { +} + +//// [parserForInStatement6.js] +for (var a = 1 in X) { +} diff --git a/tests/baselines/reference/parserForInStatement7.js b/tests/baselines/reference/parserForInStatement7.js new file mode 100644 index 00000000000..5c056abedb6 --- /dev/null +++ b/tests/baselines/reference/parserForInStatement7.js @@ -0,0 +1,7 @@ +//// [parserForInStatement7.ts] +for (var a: number = 1, b: string = "" in X) { +} + +//// [parserForInStatement7.js] +for (var a = 1 in X) { +} diff --git a/tests/baselines/reference/parserFunctionDeclaration1.js b/tests/baselines/reference/parserFunctionDeclaration1.js new file mode 100644 index 00000000000..39bbfe67ca8 --- /dev/null +++ b/tests/baselines/reference/parserFunctionDeclaration1.js @@ -0,0 +1,6 @@ +//// [parserFunctionDeclaration1.ts] +declare module M { + declare function F(); +} + +//// [parserFunctionDeclaration1.js] diff --git a/tests/baselines/reference/parserFunctionDeclaration2.js b/tests/baselines/reference/parserFunctionDeclaration2.js new file mode 100644 index 00000000000..032489bc61c --- /dev/null +++ b/tests/baselines/reference/parserFunctionDeclaration2.js @@ -0,0 +1,5 @@ +//// [parserFunctionDeclaration2.ts] +declare function Foo() { +} + +//// [parserFunctionDeclaration2.js] diff --git a/tests/baselines/reference/parserFuzz1.js b/tests/baselines/reference/parserFuzz1.js new file mode 100644 index 00000000000..969c07c1659 --- /dev/null +++ b/tests/baselines/reference/parserFuzz1.js @@ -0,0 +1,13 @@ +//// [parserFuzz1.ts] +cla () { } +} + +//// [parserGetAccessorWithTypeParameters1.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "foo", { + get: function () { + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity12.js b/tests/baselines/reference/parserGreaterThanTokenAmbiguity12.js new file mode 100644 index 00000000000..2db83838747 --- /dev/null +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity12.js @@ -0,0 +1,6 @@ +//// [parserGreaterThanTokenAmbiguity12.ts] +1 >> = 2; + +//// [parserGreaterThanTokenAmbiguity12.js] +1 >> ; +2; diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity13.js b/tests/baselines/reference/parserGreaterThanTokenAmbiguity13.js new file mode 100644 index 00000000000..49130a9dd13 --- /dev/null +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity13.js @@ -0,0 +1,6 @@ +//// [parserGreaterThanTokenAmbiguity13.ts] +1 >>/**/= 2; + +//// [parserGreaterThanTokenAmbiguity13.js] +1 >> ; /**/ +2; diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity14.js b/tests/baselines/reference/parserGreaterThanTokenAmbiguity14.js new file mode 100644 index 00000000000..5cc8bb3b88e --- /dev/null +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity14.js @@ -0,0 +1,7 @@ +//// [parserGreaterThanTokenAmbiguity14.ts] +1 >> += 2; + +//// [parserGreaterThanTokenAmbiguity14.js] +1 >> ; +2; diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity17.js b/tests/baselines/reference/parserGreaterThanTokenAmbiguity17.js new file mode 100644 index 00000000000..58ea53274aa --- /dev/null +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity17.js @@ -0,0 +1,6 @@ +//// [parserGreaterThanTokenAmbiguity17.ts] +1 >>> = 2; + +//// [parserGreaterThanTokenAmbiguity17.js] +1 >>> ; +2; diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity18.js b/tests/baselines/reference/parserGreaterThanTokenAmbiguity18.js new file mode 100644 index 00000000000..71527689b2c --- /dev/null +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity18.js @@ -0,0 +1,6 @@ +//// [parserGreaterThanTokenAmbiguity18.ts] +1 >>>/**/= 2; + +//// [parserGreaterThanTokenAmbiguity18.js] +1 >>> ; /**/ +2; diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity19.js b/tests/baselines/reference/parserGreaterThanTokenAmbiguity19.js new file mode 100644 index 00000000000..52035691c84 --- /dev/null +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity19.js @@ -0,0 +1,7 @@ +//// [parserGreaterThanTokenAmbiguity19.ts] +1 >>> += 2; + +//// [parserGreaterThanTokenAmbiguity19.js] +1 >>> ; +2; diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity2.js b/tests/baselines/reference/parserGreaterThanTokenAmbiguity2.js new file mode 100644 index 00000000000..d4cb01bf4c3 --- /dev/null +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity2.js @@ -0,0 +1,5 @@ +//// [parserGreaterThanTokenAmbiguity2.ts] +1 > > 2; + +//// [parserGreaterThanTokenAmbiguity2.js] +1 > > 2; diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity3.js b/tests/baselines/reference/parserGreaterThanTokenAmbiguity3.js new file mode 100644 index 00000000000..79f8c139260 --- /dev/null +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity3.js @@ -0,0 +1,5 @@ +//// [parserGreaterThanTokenAmbiguity3.ts] +1 >/**/> 2; + +//// [parserGreaterThanTokenAmbiguity3.js] +1 > /**/ > 2; diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity4.js b/tests/baselines/reference/parserGreaterThanTokenAmbiguity4.js new file mode 100644 index 00000000000..5ef065681dc --- /dev/null +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity4.js @@ -0,0 +1,6 @@ +//// [parserGreaterThanTokenAmbiguity4.ts] +1 > +> 2; + +//// [parserGreaterThanTokenAmbiguity4.js] +1 > > 2; diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity7.js b/tests/baselines/reference/parserGreaterThanTokenAmbiguity7.js new file mode 100644 index 00000000000..a97cfa4bcc9 --- /dev/null +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity7.js @@ -0,0 +1,5 @@ +//// [parserGreaterThanTokenAmbiguity7.ts] +1 >> > 2; + +//// [parserGreaterThanTokenAmbiguity7.js] +1 >> > 2; diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity8.js b/tests/baselines/reference/parserGreaterThanTokenAmbiguity8.js new file mode 100644 index 00000000000..0006c03219a --- /dev/null +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity8.js @@ -0,0 +1,5 @@ +//// [parserGreaterThanTokenAmbiguity8.ts] +1 >>/**/> 2; + +//// [parserGreaterThanTokenAmbiguity8.js] +1 >> /**/ > 2; diff --git a/tests/baselines/reference/parserGreaterThanTokenAmbiguity9.js b/tests/baselines/reference/parserGreaterThanTokenAmbiguity9.js new file mode 100644 index 00000000000..25c5ed53a7c --- /dev/null +++ b/tests/baselines/reference/parserGreaterThanTokenAmbiguity9.js @@ -0,0 +1,6 @@ +//// [parserGreaterThanTokenAmbiguity9.ts] +1 >> +> 2; + +//// [parserGreaterThanTokenAmbiguity9.js] +1 >> > 2; diff --git a/tests/baselines/reference/parserIndexMemberDeclaration10.js b/tests/baselines/reference/parserIndexMemberDeclaration10.js new file mode 100644 index 00000000000..cba928413a3 --- /dev/null +++ b/tests/baselines/reference/parserIndexMemberDeclaration10.js @@ -0,0 +1,11 @@ +//// [parserIndexMemberDeclaration10.ts] +class C { + static static [x: string]: string; +} + +//// [parserIndexMemberDeclaration10.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserIndexMemberDeclaration5.js b/tests/baselines/reference/parserIndexMemberDeclaration5.js new file mode 100644 index 00000000000..209e26ae4c0 --- /dev/null +++ b/tests/baselines/reference/parserIndexMemberDeclaration5.js @@ -0,0 +1,11 @@ +//// [parserIndexMemberDeclaration5.ts] +class C { + [a: string]: number public v: number +} + +//// [parserIndexMemberDeclaration5.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserIndexMemberDeclaration6.js b/tests/baselines/reference/parserIndexMemberDeclaration6.js new file mode 100644 index 00000000000..9dae6a786b4 --- /dev/null +++ b/tests/baselines/reference/parserIndexMemberDeclaration6.js @@ -0,0 +1,11 @@ +//// [parserIndexMemberDeclaration6.ts] +class C { + static [x: string]: string; +} + +//// [parserIndexMemberDeclaration6.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserIndexMemberDeclaration7.js b/tests/baselines/reference/parserIndexMemberDeclaration7.js new file mode 100644 index 00000000000..550063e6659 --- /dev/null +++ b/tests/baselines/reference/parserIndexMemberDeclaration7.js @@ -0,0 +1,11 @@ +//// [parserIndexMemberDeclaration7.ts] +class C { + public [x: string]: string; +} + +//// [parserIndexMemberDeclaration7.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserIndexMemberDeclaration8.js b/tests/baselines/reference/parserIndexMemberDeclaration8.js new file mode 100644 index 00000000000..c1f40ad0f15 --- /dev/null +++ b/tests/baselines/reference/parserIndexMemberDeclaration8.js @@ -0,0 +1,11 @@ +//// [parserIndexMemberDeclaration8.ts] +class C { + private [x: string]: string; +} + +//// [parserIndexMemberDeclaration8.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserIndexMemberDeclaration9.js b/tests/baselines/reference/parserIndexMemberDeclaration9.js new file mode 100644 index 00000000000..bd547be3bd3 --- /dev/null +++ b/tests/baselines/reference/parserIndexMemberDeclaration9.js @@ -0,0 +1,11 @@ +//// [parserIndexMemberDeclaration9.ts] +class C { + export [x: string]: string; +} + +//// [parserIndexMemberDeclaration9.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserIndexSignature1.js b/tests/baselines/reference/parserIndexSignature1.js new file mode 100644 index 00000000000..65c67444b34 --- /dev/null +++ b/tests/baselines/reference/parserIndexSignature1.js @@ -0,0 +1,6 @@ +//// [parserIndexSignature1.ts] +interface I { + [...a] +} + +//// [parserIndexSignature1.js] diff --git a/tests/baselines/reference/parserIndexSignature10.js b/tests/baselines/reference/parserIndexSignature10.js new file mode 100644 index 00000000000..a8fbccc402b --- /dev/null +++ b/tests/baselines/reference/parserIndexSignature10.js @@ -0,0 +1,6 @@ +//// [parserIndexSignature10.ts] +interface I { + [a, b]: number +} + +//// [parserIndexSignature10.js] diff --git a/tests/baselines/reference/parserIndexSignature11.js b/tests/baselines/reference/parserIndexSignature11.js new file mode 100644 index 00000000000..a78a2179d64 --- /dev/null +++ b/tests/baselines/reference/parserIndexSignature11.js @@ -0,0 +1,8 @@ +//// [parserIndexSignature11.ts] +interface I { + [p]; // Used to be indexer, now it is a computed property + [p1: string]; + [p2: string, p3: number]; +} + +//// [parserIndexSignature11.js] diff --git a/tests/baselines/reference/parserIndexSignature2.js b/tests/baselines/reference/parserIndexSignature2.js new file mode 100644 index 00000000000..606a9c3435c --- /dev/null +++ b/tests/baselines/reference/parserIndexSignature2.js @@ -0,0 +1,6 @@ +//// [parserIndexSignature2.ts] +interface I { + [public a] +} + +//// [parserIndexSignature2.js] diff --git a/tests/baselines/reference/parserIndexSignature3.js b/tests/baselines/reference/parserIndexSignature3.js new file mode 100644 index 00000000000..d513d378fba --- /dev/null +++ b/tests/baselines/reference/parserIndexSignature3.js @@ -0,0 +1,6 @@ +//// [parserIndexSignature3.ts] +interface I { + [a?] +} + +//// [parserIndexSignature3.js] diff --git a/tests/baselines/reference/parserIndexSignature4.js b/tests/baselines/reference/parserIndexSignature4.js new file mode 100644 index 00000000000..fdfcab478b6 --- /dev/null +++ b/tests/baselines/reference/parserIndexSignature4.js @@ -0,0 +1,6 @@ +//// [parserIndexSignature4.ts] +interface I { + [a = 0] // Used to be indexer, now it is a computed property +} + +//// [parserIndexSignature4.js] diff --git a/tests/baselines/reference/parserIndexSignature5.js b/tests/baselines/reference/parserIndexSignature5.js new file mode 100644 index 00000000000..bce7f74f419 --- /dev/null +++ b/tests/baselines/reference/parserIndexSignature5.js @@ -0,0 +1,6 @@ +//// [parserIndexSignature5.ts] +interface I { + [a] // Used to be indexer, now it is a computed property +} + +//// [parserIndexSignature5.js] diff --git a/tests/baselines/reference/parserIndexSignature6.js b/tests/baselines/reference/parserIndexSignature6.js new file mode 100644 index 00000000000..8566faf26c4 --- /dev/null +++ b/tests/baselines/reference/parserIndexSignature6.js @@ -0,0 +1,6 @@ +//// [parserIndexSignature6.ts] +interface I { + [a:boolean] +} + +//// [parserIndexSignature6.js] diff --git a/tests/baselines/reference/parserIndexSignature7.js b/tests/baselines/reference/parserIndexSignature7.js new file mode 100644 index 00000000000..10c784e795a --- /dev/null +++ b/tests/baselines/reference/parserIndexSignature7.js @@ -0,0 +1,6 @@ +//// [parserIndexSignature7.ts] +interface I { + [a:string] +} + +//// [parserIndexSignature7.js] diff --git a/tests/baselines/reference/parserIndexSignature8.js b/tests/baselines/reference/parserIndexSignature8.js new file mode 100644 index 00000000000..40ea03fb245 --- /dev/null +++ b/tests/baselines/reference/parserIndexSignature8.js @@ -0,0 +1,8 @@ +//// [parserIndexSignature8.ts] +var foo: { [index: any]; }; // expect an error here +var foo2: { [index: RegExp]; }; // expect an error here + + +//// [parserIndexSignature8.js] +var foo; // expect an error here +var foo2; // expect an error here diff --git a/tests/baselines/reference/parserIndexSignature9.js b/tests/baselines/reference/parserIndexSignature9.js new file mode 100644 index 00000000000..c2da7906e78 --- /dev/null +++ b/tests/baselines/reference/parserIndexSignature9.js @@ -0,0 +1,6 @@ +//// [parserIndexSignature9.ts] +interface I { + []: number +} + +//// [parserIndexSignature9.js] diff --git a/tests/baselines/reference/parserInterfaceDeclaration1.js b/tests/baselines/reference/parserInterfaceDeclaration1.js new file mode 100644 index 00000000000..61fe3eee877 --- /dev/null +++ b/tests/baselines/reference/parserInterfaceDeclaration1.js @@ -0,0 +1,5 @@ +//// [parserInterfaceDeclaration1.ts] +interface I extends A extends B { +} + +//// [parserInterfaceDeclaration1.js] diff --git a/tests/baselines/reference/parserInterfaceDeclaration2.js b/tests/baselines/reference/parserInterfaceDeclaration2.js new file mode 100644 index 00000000000..a0bbe96bae4 --- /dev/null +++ b/tests/baselines/reference/parserInterfaceDeclaration2.js @@ -0,0 +1,5 @@ +//// [parserInterfaceDeclaration2.ts] +interface I implements A { +} + +//// [parserInterfaceDeclaration2.js] diff --git a/tests/baselines/reference/parserInterfaceDeclaration3.js b/tests/baselines/reference/parserInterfaceDeclaration3.js new file mode 100644 index 00000000000..8281de6db79 --- /dev/null +++ b/tests/baselines/reference/parserInterfaceDeclaration3.js @@ -0,0 +1,5 @@ +//// [parserInterfaceDeclaration3.ts] +public interface I { +} + +//// [parserInterfaceDeclaration3.js] diff --git a/tests/baselines/reference/parserInterfaceDeclaration4.js b/tests/baselines/reference/parserInterfaceDeclaration4.js new file mode 100644 index 00000000000..9385388d81d --- /dev/null +++ b/tests/baselines/reference/parserInterfaceDeclaration4.js @@ -0,0 +1,5 @@ +//// [parserInterfaceDeclaration4.ts] +static interface I { +} + +//// [parserInterfaceDeclaration4.js] diff --git a/tests/baselines/reference/parserInterfaceDeclaration5.js b/tests/baselines/reference/parserInterfaceDeclaration5.js new file mode 100644 index 00000000000..81ad1108f24 --- /dev/null +++ b/tests/baselines/reference/parserInterfaceDeclaration5.js @@ -0,0 +1,5 @@ +//// [parserInterfaceDeclaration5.ts] +declare interface I { +} + +//// [parserInterfaceDeclaration5.js] diff --git a/tests/baselines/reference/parserInterfaceDeclaration6.js b/tests/baselines/reference/parserInterfaceDeclaration6.js new file mode 100644 index 00000000000..3cecca19198 --- /dev/null +++ b/tests/baselines/reference/parserInterfaceDeclaration6.js @@ -0,0 +1,5 @@ +//// [parserInterfaceDeclaration6.ts] +export export interface I { +} + +//// [parserInterfaceDeclaration6.js] diff --git a/tests/baselines/reference/parserInterfaceDeclaration7.js b/tests/baselines/reference/parserInterfaceDeclaration7.js new file mode 100644 index 00000000000..40998c119cf --- /dev/null +++ b/tests/baselines/reference/parserInterfaceDeclaration7.js @@ -0,0 +1,5 @@ +//// [parserInterfaceDeclaration7.ts] +export interface I { +} + +//// [parserInterfaceDeclaration7.js] diff --git a/tests/baselines/reference/parserInvalidIdentifiersInVariableStatements1.js b/tests/baselines/reference/parserInvalidIdentifiersInVariableStatements1.js new file mode 100644 index 00000000000..09fcffc1b0d --- /dev/null +++ b/tests/baselines/reference/parserInvalidIdentifiersInVariableStatements1.js @@ -0,0 +1,12 @@ +//// [parserInvalidIdentifiersInVariableStatements1.ts] +var export; +var foo; +var class; +var bar; + + +//// [parserInvalidIdentifiersInVariableStatements1.js] +var ; +var foo; +var ; +var bar; diff --git a/tests/baselines/reference/parserKeywordsAsIdentifierName2.js b/tests/baselines/reference/parserKeywordsAsIdentifierName2.js new file mode 100644 index 00000000000..bc47da5766e --- /dev/null +++ b/tests/baselines/reference/parserKeywordsAsIdentifierName2.js @@ -0,0 +1,7 @@ +//// [parserKeywordsAsIdentifierName2.ts] +// 'public' should be marked unusable, should complain on trailing /* +a.public /* + +//// [parserKeywordsAsIdentifierName2.js] +// 'public' should be marked unusable, should complain on trailing /* +a.public; /* diff --git a/tests/baselines/reference/parserMemberAccessAfterPostfixExpression1.js b/tests/baselines/reference/parserMemberAccessAfterPostfixExpression1.js new file mode 100644 index 00000000000..d8f6204adfa --- /dev/null +++ b/tests/baselines/reference/parserMemberAccessAfterPostfixExpression1.js @@ -0,0 +1,6 @@ +//// [parserMemberAccessAfterPostfixExpression1.ts] +a--.toString() + +//// [parserMemberAccessAfterPostfixExpression1.js] +a--; +toString(); diff --git a/tests/baselines/reference/parserMemberAccessExpression1.js b/tests/baselines/reference/parserMemberAccessExpression1.js new file mode 100644 index 00000000000..83897e27097 --- /dev/null +++ b/tests/baselines/reference/parserMemberAccessExpression1.js @@ -0,0 +1,12 @@ +//// [parserMemberAccessExpression1.ts] +Foo(); +Foo.Bar(); +Foo.Bar(); +Foo.Bar(); + + +//// [parserMemberAccessExpression1.js] +Foo(); +Foo.Bar(); +Foo(Bar()); +Foo(Bar()); diff --git a/tests/baselines/reference/parserMemberAccessOffOfGenericType1.js b/tests/baselines/reference/parserMemberAccessOffOfGenericType1.js new file mode 100644 index 00000000000..4529fafba02 --- /dev/null +++ b/tests/baselines/reference/parserMemberAccessOffOfGenericType1.js @@ -0,0 +1,5 @@ +//// [parserMemberAccessOffOfGenericType1.ts] +var v = List.makeChild(); + +//// [parserMemberAccessOffOfGenericType1.js] +var v = List(makeChild()); diff --git a/tests/baselines/reference/parserMemberAccessorDeclaration10.js b/tests/baselines/reference/parserMemberAccessorDeclaration10.js new file mode 100644 index 00000000000..dba06544963 --- /dev/null +++ b/tests/baselines/reference/parserMemberAccessorDeclaration10.js @@ -0,0 +1,18 @@ +//// [parserMemberAccessorDeclaration10.ts] +class C { + export get Foo() { } +} + +//// [parserMemberAccessorDeclaration10.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "Foo", { + get: function () { + } + exports.Foo = Foo;, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/parserMemberAccessorDeclaration11.js b/tests/baselines/reference/parserMemberAccessorDeclaration11.js new file mode 100644 index 00000000000..2a286b8ca6b --- /dev/null +++ b/tests/baselines/reference/parserMemberAccessorDeclaration11.js @@ -0,0 +1,17 @@ +//// [parserMemberAccessorDeclaration11.ts] +class C { + declare get Foo() { } +} + +//// [parserMemberAccessorDeclaration11.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "Foo", { + get: function () { + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/parserMemberAccessorDeclaration12.js b/tests/baselines/reference/parserMemberAccessorDeclaration12.js new file mode 100644 index 00000000000..aea6eccfbc2 --- /dev/null +++ b/tests/baselines/reference/parserMemberAccessorDeclaration12.js @@ -0,0 +1,17 @@ +//// [parserMemberAccessorDeclaration12.ts] +class C { + get Foo(a: number) { } +} + +//// [parserMemberAccessorDeclaration12.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "Foo", { + get: function (a) { + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/parserMemberAccessorDeclaration13.js b/tests/baselines/reference/parserMemberAccessorDeclaration13.js new file mode 100644 index 00000000000..f6ca4ee6a02 --- /dev/null +++ b/tests/baselines/reference/parserMemberAccessorDeclaration13.js @@ -0,0 +1,17 @@ +//// [parserMemberAccessorDeclaration13.ts] +class C { + set Foo() { } +} + +//// [parserMemberAccessorDeclaration13.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "Foo", { + set: function () { + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/parserMemberAccessorDeclaration14.js b/tests/baselines/reference/parserMemberAccessorDeclaration14.js new file mode 100644 index 00000000000..62877d402d1 --- /dev/null +++ b/tests/baselines/reference/parserMemberAccessorDeclaration14.js @@ -0,0 +1,17 @@ +//// [parserMemberAccessorDeclaration14.ts] +class C { + set Foo(a: number, b: number) { } +} + +//// [parserMemberAccessorDeclaration14.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "Foo", { + set: function (a, b) { + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/parserMemberAccessorDeclaration16.js b/tests/baselines/reference/parserMemberAccessorDeclaration16.js new file mode 100644 index 00000000000..a6cd0aaa7e9 --- /dev/null +++ b/tests/baselines/reference/parserMemberAccessorDeclaration16.js @@ -0,0 +1,18 @@ +//// [parserMemberAccessorDeclaration16.ts] +class C { + set Foo(a = 1) { } +} + +//// [parserMemberAccessorDeclaration16.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "Foo", { + set: function (a) { + if (a === void 0) { a = 1; } + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/parserMemberAccessorDeclaration17.js b/tests/baselines/reference/parserMemberAccessorDeclaration17.js new file mode 100644 index 00000000000..6c99c7ddae6 --- /dev/null +++ b/tests/baselines/reference/parserMemberAccessorDeclaration17.js @@ -0,0 +1,17 @@ +//// [parserMemberAccessorDeclaration17.ts] +class C { + set Foo(a?: number) { } +} + +//// [parserMemberAccessorDeclaration17.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "Foo", { + set: function (a) { + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/parserMemberAccessorDeclaration18.js b/tests/baselines/reference/parserMemberAccessorDeclaration18.js new file mode 100644 index 00000000000..9483a1f2daf --- /dev/null +++ b/tests/baselines/reference/parserMemberAccessorDeclaration18.js @@ -0,0 +1,21 @@ +//// [parserMemberAccessorDeclaration18.ts] +class C { + set Foo(...a) { } +} + +//// [parserMemberAccessorDeclaration18.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "Foo", { + set: function () { + var a = []; + for (var _i = 0; _i < arguments.length; _i++) { + a[_i - 0] = arguments[_i]; + } + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/parserMemberAccessorDeclaration7.js b/tests/baselines/reference/parserMemberAccessorDeclaration7.js new file mode 100644 index 00000000000..0d2d24092e5 --- /dev/null +++ b/tests/baselines/reference/parserMemberAccessorDeclaration7.js @@ -0,0 +1,17 @@ +//// [parserMemberAccessorDeclaration7.ts] +class C { + public public get Foo() { } +} + +//// [parserMemberAccessorDeclaration7.js] +var C = (function () { + function C() { + } + Object.defineProperty(C.prototype, "Foo", { + get: function () { + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/parserMemberAccessorDeclaration8.js b/tests/baselines/reference/parserMemberAccessorDeclaration8.js new file mode 100644 index 00000000000..dd93fa4852e --- /dev/null +++ b/tests/baselines/reference/parserMemberAccessorDeclaration8.js @@ -0,0 +1,17 @@ +//// [parserMemberAccessorDeclaration8.ts] +class C { + static static get Foo() { } +} + +//// [parserMemberAccessorDeclaration8.js] +var C = (function () { + function C() { + } + Object.defineProperty(C, "Foo", { + get: function () { + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/parserMemberAccessorDeclaration9.js b/tests/baselines/reference/parserMemberAccessorDeclaration9.js new file mode 100644 index 00000000000..5fca86f689b --- /dev/null +++ b/tests/baselines/reference/parserMemberAccessorDeclaration9.js @@ -0,0 +1,17 @@ +//// [parserMemberAccessorDeclaration9.ts] +class C { + static public get Foo() { } +} + +//// [parserMemberAccessorDeclaration9.js] +var C = (function () { + function C() { + } + Object.defineProperty(C, "Foo", { + get: function () { + }, + enumerable: true, + configurable: true + }); + return C; +})(); diff --git a/tests/baselines/reference/parserMemberFunctionDeclaration1.js b/tests/baselines/reference/parserMemberFunctionDeclaration1.js new file mode 100644 index 00000000000..564245157b0 --- /dev/null +++ b/tests/baselines/reference/parserMemberFunctionDeclaration1.js @@ -0,0 +1,13 @@ +//// [parserMemberFunctionDeclaration1.ts] +class C { + public public Foo() { } +} + +//// [parserMemberFunctionDeclaration1.js] +var C = (function () { + function C() { + } + C.prototype.Foo = function () { + }; + return C; +})(); diff --git a/tests/baselines/reference/parserMemberFunctionDeclaration2.js b/tests/baselines/reference/parserMemberFunctionDeclaration2.js new file mode 100644 index 00000000000..0f103c90b7d --- /dev/null +++ b/tests/baselines/reference/parserMemberFunctionDeclaration2.js @@ -0,0 +1,13 @@ +//// [parserMemberFunctionDeclaration2.ts] +class C { + static static Foo() { } +} + +//// [parserMemberFunctionDeclaration2.js] +var C = (function () { + function C() { + } + C.Foo = function () { + }; + return C; +})(); diff --git a/tests/baselines/reference/parserMemberFunctionDeclaration3.js b/tests/baselines/reference/parserMemberFunctionDeclaration3.js new file mode 100644 index 00000000000..46243f08dad --- /dev/null +++ b/tests/baselines/reference/parserMemberFunctionDeclaration3.js @@ -0,0 +1,13 @@ +//// [parserMemberFunctionDeclaration3.ts] +class C { + static public Foo() { } +} + +//// [parserMemberFunctionDeclaration3.js] +var C = (function () { + function C() { + } + C.Foo = function () { + }; + return C; +})(); diff --git a/tests/baselines/reference/parserMemberFunctionDeclaration4.js b/tests/baselines/reference/parserMemberFunctionDeclaration4.js new file mode 100644 index 00000000000..bcf00aeb1bc --- /dev/null +++ b/tests/baselines/reference/parserMemberFunctionDeclaration4.js @@ -0,0 +1,14 @@ +//// [parserMemberFunctionDeclaration4.ts] +class C { + export Foo() { } +} + +//// [parserMemberFunctionDeclaration4.js] +var C = (function () { + function C() { + } + C.prototype.Foo = function () { + } + exports.Foo = Foo;; + return C; +})(); diff --git a/tests/baselines/reference/parserMemberFunctionDeclaration5.js b/tests/baselines/reference/parserMemberFunctionDeclaration5.js new file mode 100644 index 00000000000..da2d2281999 --- /dev/null +++ b/tests/baselines/reference/parserMemberFunctionDeclaration5.js @@ -0,0 +1,13 @@ +//// [parserMemberFunctionDeclaration5.ts] +class C { + declare Foo() { } +} + +//// [parserMemberFunctionDeclaration5.js] +var C = (function () { + function C() { + } + C.prototype.Foo = function () { + }; + return C; +})(); diff --git a/tests/baselines/reference/parserMemberVariableDeclaration1.js b/tests/baselines/reference/parserMemberVariableDeclaration1.js new file mode 100644 index 00000000000..7c59fa7db4c --- /dev/null +++ b/tests/baselines/reference/parserMemberVariableDeclaration1.js @@ -0,0 +1,11 @@ +//// [parserMemberVariableDeclaration1.ts] +class C { + public public Foo; +} + +//// [parserMemberVariableDeclaration1.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserMemberVariableDeclaration2.js b/tests/baselines/reference/parserMemberVariableDeclaration2.js new file mode 100644 index 00000000000..7f4ae15a7ee --- /dev/null +++ b/tests/baselines/reference/parserMemberVariableDeclaration2.js @@ -0,0 +1,11 @@ +//// [parserMemberVariableDeclaration2.ts] +class C { + static static Foo; +} + +//// [parserMemberVariableDeclaration2.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserMemberVariableDeclaration3.js b/tests/baselines/reference/parserMemberVariableDeclaration3.js new file mode 100644 index 00000000000..e03279abed9 --- /dev/null +++ b/tests/baselines/reference/parserMemberVariableDeclaration3.js @@ -0,0 +1,11 @@ +//// [parserMemberVariableDeclaration3.ts] +class C { + static public Foo; +} + +//// [parserMemberVariableDeclaration3.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserMemberVariableDeclaration4.js b/tests/baselines/reference/parserMemberVariableDeclaration4.js new file mode 100644 index 00000000000..d52dd0f4a08 --- /dev/null +++ b/tests/baselines/reference/parserMemberVariableDeclaration4.js @@ -0,0 +1,11 @@ +//// [parserMemberVariableDeclaration4.ts] +class C { + export Foo; +} + +//// [parserMemberVariableDeclaration4.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserMemberVariableDeclaration5.js b/tests/baselines/reference/parserMemberVariableDeclaration5.js new file mode 100644 index 00000000000..bc8a49ff3f5 --- /dev/null +++ b/tests/baselines/reference/parserMemberVariableDeclaration5.js @@ -0,0 +1,11 @@ +//// [parserMemberVariableDeclaration5.ts] +class C { + declare Foo; +} + +//// [parserMemberVariableDeclaration5.js] +var C = (function () { + function C() { + } + return C; +})(); diff --git a/tests/baselines/reference/parserMissingLambdaOpenBrace1.js b/tests/baselines/reference/parserMissingLambdaOpenBrace1.js new file mode 100644 index 00000000000..8280d8dc9b2 --- /dev/null +++ b/tests/baselines/reference/parserMissingLambdaOpenBrace1.js @@ -0,0 +1,23 @@ +//// [parserMissingLambdaOpenBrace1.ts] +class C { + where(filter: Iterator): Query { + return fromDoWhile(test => + var index = 0; + return this.doWhile((item, i) => filter(item, i) ? test(item, index++) : true); + }); + } +} + +//// [parserMissingLambdaOpenBrace1.js] +var C = (function () { + function C() { + } + C.prototype.where = function (filter) { + var _this = this; + return fromDoWhile(function (test) { + var index = 0; + return _this.doWhile(function (item, i) { return filter(item, i) ? test(item, index++) : true; }); + }); + }; + return C; +})(); diff --git a/tests/baselines/reference/parserMissingToken1.js b/tests/baselines/reference/parserMissingToken1.js new file mode 100644 index 00000000000..506e628fa38 --- /dev/null +++ b/tests/baselines/reference/parserMissingToken1.js @@ -0,0 +1,9 @@ +//// [parserMissingToken1.ts] +a / finally + +//// [parserMissingToken1.js] +a / ; +try { +} +finally { +} diff --git a/tests/baselines/reference/parserMissingToken2.js b/tests/baselines/reference/parserMissingToken2.js new file mode 100644 index 00000000000..753132a4a4a --- /dev/null +++ b/tests/baselines/reference/parserMissingToken2.js @@ -0,0 +1,5 @@ +//// [parserMissingToken2.ts] +/ b; + +//// [parserMissingToken2.js] +/ b;; diff --git a/tests/baselines/reference/parserModifierOnPropertySignature1.js b/tests/baselines/reference/parserModifierOnPropertySignature1.js new file mode 100644 index 00000000000..a71bfd756a0 --- /dev/null +++ b/tests/baselines/reference/parserModifierOnPropertySignature1.js @@ -0,0 +1,7 @@ +//// [parserModifierOnPropertySignature1.ts] +interface Foo{ + public biz; +} + + +//// [parserModifierOnPropertySignature1.js] diff --git a/tests/baselines/reference/parserModifierOnStatementInBlock1.js b/tests/baselines/reference/parserModifierOnStatementInBlock1.js new file mode 100644 index 00000000000..1796c9eddf5 --- /dev/null +++ b/tests/baselines/reference/parserModifierOnStatementInBlock1.js @@ -0,0 +1,11 @@ +//// [parserModifierOnStatementInBlock1.ts] +export function foo() { + export var x = this; +} + + +//// [parserModifierOnStatementInBlock1.js] +function foo() { + exports.x = this; +} +exports.foo = foo; diff --git a/tests/baselines/reference/parserModifierOnStatementInBlock2.js b/tests/baselines/reference/parserModifierOnStatementInBlock2.js new file mode 100644 index 00000000000..7e1c5f8ee50 --- /dev/null +++ b/tests/baselines/reference/parserModifierOnStatementInBlock2.js @@ -0,0 +1,9 @@ +//// [parserModifierOnStatementInBlock2.ts] +{ + declare var x = this; +} + + +//// [parserModifierOnStatementInBlock2.js] +{ +} diff --git a/tests/baselines/reference/parserModifierOnStatementInBlock3.js b/tests/baselines/reference/parserModifierOnStatementInBlock3.js new file mode 100644 index 00000000000..9c625f0dc7f --- /dev/null +++ b/tests/baselines/reference/parserModifierOnStatementInBlock3.js @@ -0,0 +1,14 @@ +//// [parserModifierOnStatementInBlock3.ts] +export function foo() { + export function bar() { + } +} + + +//// [parserModifierOnStatementInBlock3.js] +function foo() { + function bar() { + } + exports.bar = bar; +} +exports.foo = foo; diff --git a/tests/baselines/reference/parserModule1.js b/tests/baselines/reference/parserModule1.js new file mode 100644 index 00000000000..1eba49114ab --- /dev/null +++ b/tests/baselines/reference/parserModule1.js @@ -0,0 +1,60 @@ +//// [parserModule1.ts] + export module CompilerDiagnostics { + export var debug = false; + export interface IDiagnosticWriter { + Alert(output: string): void; + } + + export var diagnosticWriter: IDiagnosticWriter = null; + + export var analysisPass: number = 0; + + export function Alert(output: string) { + if (diagnosticWriter) { + diagnosticWriter.Alert(output); + } + } + + export function debugPrint(s: string) { + if (debug) { + Alert(s); + } + } + + export function assert(condition: boolean, s: string) { + if (debug) { + if (!condition) { + Alert(s); + } + } + } + + } + +//// [parserModule1.js] +var CompilerDiagnostics; +(function (CompilerDiagnostics) { + CompilerDiagnostics.debug = false; + CompilerDiagnostics.diagnosticWriter = null; + CompilerDiagnostics.analysisPass = 0; + function Alert(output) { + if (CompilerDiagnostics.diagnosticWriter) { + CompilerDiagnostics.diagnosticWriter.Alert(output); + } + } + CompilerDiagnostics.Alert = Alert; + function debugPrint(s) { + if (CompilerDiagnostics.debug) { + Alert(s); + } + } + CompilerDiagnostics.debugPrint = debugPrint; + function assert(condition, s) { + if (CompilerDiagnostics.debug) { + if (!condition) { + Alert(s); + } + } + } + CompilerDiagnostics.assert = assert; +})(CompilerDiagnostics = exports.CompilerDiagnostics || (exports.CompilerDiagnostics = {})); diff --git a/tests/baselines/reference/parserModuleDeclaration1.js b/tests/baselines/reference/parserModuleDeclaration1.js new file mode 100644 index 00000000000..aef0434f76d --- /dev/null +++ b/tests/baselines/reference/parserModuleDeclaration1.js @@ -0,0 +1,5 @@ +//// [parserModuleDeclaration1.ts] +module "Foo" { +} + +//// [parserModuleDeclaration1.js] diff --git a/tests/baselines/reference/parserModuleDeclaration3.js b/tests/baselines/reference/parserModuleDeclaration3.js new file mode 100644 index 00000000000..c4c46cd1442 --- /dev/null +++ b/tests/baselines/reference/parserModuleDeclaration3.js @@ -0,0 +1,7 @@ +//// [parserModuleDeclaration3.ts] +declare module M { + declare module M2 { + } +} + +//// [parserModuleDeclaration3.js] diff --git a/tests/baselines/reference/parserModuleDeclaration5.js b/tests/baselines/reference/parserModuleDeclaration5.js new file mode 100644 index 00000000000..c6017ba813d --- /dev/null +++ b/tests/baselines/reference/parserModuleDeclaration5.js @@ -0,0 +1,9 @@ +//// [parserModuleDeclaration5.ts] +module M1 { + declare module M2 { + declare module M3 { + } + } +} + +//// [parserModuleDeclaration5.js] diff --git a/tests/baselines/reference/parserNotRegex1.js b/tests/baselines/reference/parserNotRegex1.js new file mode 100644 index 00000000000..1169640d850 --- /dev/null +++ b/tests/baselines/reference/parserNotRegex1.js @@ -0,0 +1,10 @@ +//// [parserNotRegex1.ts] + if (a.indexOf(-(4/3))) // We should not get a regex here becuase of the / in the comment. + { + return true; + } + +//// [parserNotRegex1.js] +if (a.indexOf(-(4 / 3))) { + return true; +} diff --git a/tests/baselines/reference/parserObjectCreationArrayLiteral1.js b/tests/baselines/reference/parserObjectCreationArrayLiteral1.js new file mode 100644 index 00000000000..562f1ada637 --- /dev/null +++ b/tests/baselines/reference/parserObjectCreationArrayLiteral1.js @@ -0,0 +1,5 @@ +//// [parserObjectCreationArrayLiteral1.ts] +new Foo[]; + +//// [parserObjectCreationArrayLiteral1.js] +new Foo[]; diff --git a/tests/baselines/reference/parserObjectCreationArrayLiteral3.js b/tests/baselines/reference/parserObjectCreationArrayLiteral3.js new file mode 100644 index 00000000000..8bb892de41a --- /dev/null +++ b/tests/baselines/reference/parserObjectCreationArrayLiteral3.js @@ -0,0 +1,5 @@ +//// [parserObjectCreationArrayLiteral3.ts] +new Foo[](); + +//// [parserObjectCreationArrayLiteral3.js] +new Foo[](); diff --git a/tests/baselines/reference/parserObjectType5.js b/tests/baselines/reference/parserObjectType5.js new file mode 100644 index 00000000000..59284c73e73 --- /dev/null +++ b/tests/baselines/reference/parserObjectType5.js @@ -0,0 +1,8 @@ +//// [parserObjectType5.ts] +var v: { + A: B + ; +}; + +//// [parserObjectType5.js] +var v; diff --git a/tests/baselines/reference/parserObjectType6.js b/tests/baselines/reference/parserObjectType6.js new file mode 100644 index 00000000000..96b3c1a8f99 --- /dev/null +++ b/tests/baselines/reference/parserObjectType6.js @@ -0,0 +1,8 @@ +//// [parserObjectType6.ts] +var v: { + a: B + []; +}; + +//// [parserObjectType6.js] +var v; diff --git a/tests/baselines/reference/parserParameterList1.js b/tests/baselines/reference/parserParameterList1.js new file mode 100644 index 00000000000..49af7780b1f --- /dev/null +++ b/tests/baselines/reference/parserParameterList1.js @@ -0,0 +1,13 @@ +//// [parserParameterList1.ts] +class C { + F(...A, B) { } +} + +//// [parserParameterList1.js] +var C = (function () { + function C() { + } + C.prototype.F = function (A, B) { + }; + return C; +})(); diff --git a/tests/baselines/reference/parserParameterList10.js b/tests/baselines/reference/parserParameterList10.js new file mode 100644 index 00000000000..4f85dec801c --- /dev/null +++ b/tests/baselines/reference/parserParameterList10.js @@ -0,0 +1,18 @@ +//// [parserParameterList10.ts] +class C { + foo(...bar = 0) { } +} + +//// [parserParameterList10.js] +var C = (function () { + function C() { + } + C.prototype.foo = function () { + if (bar === void 0) { bar = 0; } + var bar = []; + for (var _i = 0; _i < arguments.length; _i++) { + bar[_i - 0] = arguments[_i]; + } + }; + return C; +})(); diff --git a/tests/baselines/reference/parserParameterList11.js b/tests/baselines/reference/parserParameterList11.js new file mode 100644 index 00000000000..a56e8b58c20 --- /dev/null +++ b/tests/baselines/reference/parserParameterList11.js @@ -0,0 +1,11 @@ +//// [parserParameterList11.ts] +(...arg?) => 102; + +//// [parserParameterList11.js] +(function () { + var arg = []; + for (var _i = 0; _i < arguments.length; _i++) { + arg[_i - 0] = arguments[_i]; + } + return 102; +}); diff --git a/tests/baselines/reference/parserParameterList12.js b/tests/baselines/reference/parserParameterList12.js new file mode 100644 index 00000000000..ce912f0cdfd --- /dev/null +++ b/tests/baselines/reference/parserParameterList12.js @@ -0,0 +1,7 @@ +//// [parserParameterList12.ts] +function F(a,) { +} + +//// [parserParameterList12.js] +function F(a) { +} diff --git a/tests/baselines/reference/parserParameterList2.js b/tests/baselines/reference/parserParameterList2.js new file mode 100644 index 00000000000..c6a7f48c43e --- /dev/null +++ b/tests/baselines/reference/parserParameterList2.js @@ -0,0 +1,14 @@ +//// [parserParameterList2.ts] +class C { + F(A?= 0) { } +} + +//// [parserParameterList2.js] +var C = (function () { + function C() { + } + C.prototype.F = function (A) { + if (A === void 0) { A = 0; } + }; + return C; +})(); diff --git a/tests/baselines/reference/parserParameterList3.js b/tests/baselines/reference/parserParameterList3.js new file mode 100644 index 00000000000..01135f0ceff --- /dev/null +++ b/tests/baselines/reference/parserParameterList3.js @@ -0,0 +1,13 @@ +//// [parserParameterList3.ts] +class C { + F(A?, B) { } +} + +//// [parserParameterList3.js] +var C = (function () { + function C() { + } + C.prototype.F = function (A, B) { + }; + return C; +})(); diff --git a/tests/baselines/reference/parserParameterList9.js b/tests/baselines/reference/parserParameterList9.js new file mode 100644 index 00000000000..965b92a7ef6 --- /dev/null +++ b/tests/baselines/reference/parserParameterList9.js @@ -0,0 +1,17 @@ +//// [parserParameterList9.ts] +class C { + foo(...bar?) { } +} + +//// [parserParameterList9.js] +var C = (function () { + function C() { + } + C.prototype.foo = function () { + var bar = []; + for (var _i = 0; _i < arguments.length; _i++) { + bar[_i - 0] = arguments[_i]; + } + }; + return C; +})(); diff --git a/tests/baselines/reference/parserPostfixPostfixExpression1.js b/tests/baselines/reference/parserPostfixPostfixExpression1.js new file mode 100644 index 00000000000..ebb8917d777 --- /dev/null +++ b/tests/baselines/reference/parserPostfixPostfixExpression1.js @@ -0,0 +1,6 @@ +//// [parserPostfixPostfixExpression1.ts] +a++ ++; + +//// [parserPostfixPostfixExpression1.js] +a++; +++; diff --git a/tests/baselines/reference/parserPostfixUnaryExpression1.js b/tests/baselines/reference/parserPostfixUnaryExpression1.js new file mode 100644 index 00000000000..991e2f34f99 --- /dev/null +++ b/tests/baselines/reference/parserPostfixUnaryExpression1.js @@ -0,0 +1,6 @@ +//// [parserPostfixUnaryExpression1.ts] +foo ++ ++; + +//// [parserPostfixUnaryExpression1.js] +foo++; +++; diff --git a/tests/baselines/reference/parserPublicBreak1.js b/tests/baselines/reference/parserPublicBreak1.js new file mode 100644 index 00000000000..f1b9647f228 --- /dev/null +++ b/tests/baselines/reference/parserPublicBreak1.js @@ -0,0 +1,6 @@ +//// [parserPublicBreak1.ts] +public break; + + +//// [parserPublicBreak1.js] +break; diff --git a/tests/baselines/reference/parserRealSource1.js b/tests/baselines/reference/parserRealSource1.js new file mode 100644 index 00000000000..c62897c9aff --- /dev/null +++ b/tests/baselines/reference/parserRealSource1.js @@ -0,0 +1,325 @@ +//// [parserRealSource1.ts] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. + +/// + +module TypeScript { + export module CompilerDiagnostics { + export var debug = false; + export interface IDiagnosticWriter { + Alert(output: string): void; + } + + export var diagnosticWriter: IDiagnosticWriter = null; + + export var analysisPass: number = 0; + + export function Alert(output: string) { + if (diagnosticWriter) { + diagnosticWriter.Alert(output); + } + } + + export function debugPrint(s: string) { + if (debug) { + Alert(s); + } + } + + export function assert(condition: boolean, s: string) { + if (debug) { + if (!condition) { + Alert(s); + } + } + } + + } + + export interface ILogger { + information(): boolean; + debug(): boolean; + warning(): boolean; + error(): boolean; + fatal(): boolean; + log(s: string): void; + } + + export class NullLogger implements ILogger { + public information(): boolean { return false; } + public debug(): boolean { return false; } + public warning(): boolean { return false; } + public error(): boolean { return false; } + public fatal(): boolean { return false; } + public log(s: string): void { + } + } + + export class LoggerAdapter implements ILogger { + private _information: boolean; + private _debug: boolean; + private _warning: boolean; + private _error: boolean; + private _fatal: boolean; + + constructor (public logger: ILogger) { + this._information = this.logger.information(); + this._debug = this.logger.debug(); + this._warning = this.logger.warning(); + this._error = this.logger.error(); + this._fatal = this.logger.fatal(); + } + + + public information(): boolean { return this._information; } + public debug(): boolean { return this._debug; } + public warning(): boolean { return this._warning; } + public error(): boolean { return this._error; } + public fatal(): boolean { return this._fatal; } + public log(s: string): void { + this.logger.log(s); + } + } + + export class BufferedLogger implements ILogger { + public logContents = []; + + public information(): boolean { return false; } + public debug(): boolean { return false; } + public warning(): boolean { return false; } + public error(): boolean { return false; } + public fatal(): boolean { return false; } + public log(s: string): void { + this.logContents.push(s); + } + } + + export function timeFunction(logger: ILogger, funcDescription: string, func: () =>any): any { + var start = +new Date(); + var result = func(); + var end = +new Date(); + logger.log(funcDescription + " completed in " + (end - start) + " msec"); + return result; + } + + export function stringToLiteral(value: string, length: number): string { + var result = ""; + + var addChar = (index: number) => { + var ch = value.charCodeAt(index); + switch (ch) { + case 0x09: // tab + result += "\\t"; + break; + case 0x0a: // line feed + result += "\\n"; + break; + case 0x0b: // vertical tab + result += "\\v"; + break; + case 0x0c: // form feed + result += "\\f"; + break; + case 0x0d: // carriage return + result += "\\r"; + break; + case 0x22: // double quote + result += "\\\""; + break; + case 0x27: // single quote + result += "\\\'"; + break; + case 0x5c: // Backslash + result += "\\"; + break; + default: + result += value.charAt(index); + } + } + + var tooLong = (value.length > length); + if (tooLong) { + var mid = length >> 1; + for (var i = 0; i < mid; i++) addChar(i); + result += "(...)"; + for (var i = value.length - mid; i < value.length; i++) addChar(i); + } + else { + length = value.length; + for (var i = 0; i < length; i++) addChar(i); + } + return result; + } +} + + +//// [parserRealSource1.js] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. +/// +var TypeScript; +(function (TypeScript) { + var CompilerDiagnostics; + (function (CompilerDiagnostics) { + CompilerDiagnostics.debug = false; + CompilerDiagnostics.diagnosticWriter = null; + CompilerDiagnostics.analysisPass = 0; + function Alert(output) { + if (CompilerDiagnostics.diagnosticWriter) { + CompilerDiagnostics.diagnosticWriter.Alert(output); + } + } + CompilerDiagnostics.Alert = Alert; + function debugPrint(s) { + if (CompilerDiagnostics.debug) { + Alert(s); + } + } + CompilerDiagnostics.debugPrint = debugPrint; + function assert(condition, s) { + if (CompilerDiagnostics.debug) { + if (!condition) { + Alert(s); + } + } + } + CompilerDiagnostics.assert = assert; + })(CompilerDiagnostics = TypeScript.CompilerDiagnostics || (TypeScript.CompilerDiagnostics = {})); + var NullLogger = (function () { + function NullLogger() { + } + NullLogger.prototype.information = function () { + return false; + }; + NullLogger.prototype.debug = function () { + return false; + }; + NullLogger.prototype.warning = function () { + return false; + }; + NullLogger.prototype.error = function () { + return false; + }; + NullLogger.prototype.fatal = function () { + return false; + }; + NullLogger.prototype.log = function (s) { + }; + return NullLogger; + })(); + TypeScript.NullLogger = NullLogger; + var LoggerAdapter = (function () { + function LoggerAdapter(logger) { + this.logger = logger; + this._information = this.logger.information(); + this._debug = this.logger.debug(); + this._warning = this.logger.warning(); + this._error = this.logger.error(); + this._fatal = this.logger.fatal(); + } + LoggerAdapter.prototype.information = function () { + return this._information; + }; + LoggerAdapter.prototype.debug = function () { + return this._debug; + }; + LoggerAdapter.prototype.warning = function () { + return this._warning; + }; + LoggerAdapter.prototype.error = function () { + return this._error; + }; + LoggerAdapter.prototype.fatal = function () { + return this._fatal; + }; + LoggerAdapter.prototype.log = function (s) { + this.logger.log(s); + }; + return LoggerAdapter; + })(); + TypeScript.LoggerAdapter = LoggerAdapter; + var BufferedLogger = (function () { + function BufferedLogger() { + this.logContents = []; + } + BufferedLogger.prototype.information = function () { + return false; + }; + BufferedLogger.prototype.debug = function () { + return false; + }; + BufferedLogger.prototype.warning = function () { + return false; + }; + BufferedLogger.prototype.error = function () { + return false; + }; + BufferedLogger.prototype.fatal = function () { + return false; + }; + BufferedLogger.prototype.log = function (s) { + this.logContents.push(s); + }; + return BufferedLogger; + })(); + TypeScript.BufferedLogger = BufferedLogger; + function timeFunction(logger, funcDescription, func) { + var start = +new Date(); + var result = func(); + var end = +new Date(); + logger.log(funcDescription + " completed in " + (end - start) + " msec"); + return result; + } + TypeScript.timeFunction = timeFunction; + function stringToLiteral(value, length) { + var result = ""; + var addChar = function (index) { + var ch = value.charCodeAt(index); + switch (ch) { + case 0x09: + result += "\\t"; + break; + case 0x0a: + result += "\\n"; + break; + case 0x0b: + result += "\\v"; + break; + case 0x0c: + result += "\\f"; + break; + case 0x0d: + result += "\\r"; + break; + case 0x22: + result += "\\\""; + break; + case 0x27: + result += "\\\'"; + break; + case 0x5c: + result += "\\"; + break; + default: + result += value.charAt(index); + } + }; + var tooLong = (value.length > length); + if (tooLong) { + var mid = length >> 1; + for (var i = 0; i < mid; i++) + addChar(i); + result += "(...)"; + for (var i = value.length - mid; i < value.length; i++) + addChar(i); + } + else { + length = value.length; + for (var i = 0; i < length; i++) + addChar(i); + } + return result; + } + TypeScript.stringToLiteral = stringToLiteral; +})(TypeScript || (TypeScript = {})); diff --git a/tests/baselines/reference/parserRealSource10.js b/tests/baselines/reference/parserRealSource10.js new file mode 100644 index 00000000000..0dd944a7721 --- /dev/null +++ b/tests/baselines/reference/parserRealSource10.js @@ -0,0 +1,930 @@ +//// [parserRealSource10.ts] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. + +/// + +module TypeScript { + export enum TokenID { + // Keywords + Any, + Bool, + Break, + Case, + Catch, + Class, + Const, + Continue, + Debugger, + Default, + Delete, + Do, + Else, + Enum, + Export, + Extends, + Declare, + False, + Finally, + For, + Function, + Constructor, + Get, + If, + Implements, + Import, + In, + InstanceOf, + Interface, + Let, + Module, + New, + Number, + Null, + Package, + Private, + Protected, + Public, + Return, + Set, + Static, + String, + Super, + Switch, + This, + Throw, + True, + Try, + TypeOf, + Var, + Void, + With, + While, + Yield, + // Punctuation + Semicolon, + OpenParen, + CloseParen, + OpenBracket, + CloseBracket, + OpenBrace, + CloseBrace, + Comma, + Equals, + PlusEquals, + MinusEquals, + AsteriskEquals, + SlashEquals, + PercentEquals, + AmpersandEquals, + CaretEquals, + BarEquals, + LessThanLessThanEquals, + GreaterThanGreaterThanEquals, + GreaterThanGreaterThanGreaterThanEquals, + Question, + Colon, + BarBar, + AmpersandAmpersand, + Bar, + Caret, + And, + EqualsEquals, + ExclamationEquals, + EqualsEqualsEquals, + ExclamationEqualsEquals, + LessThan, + LessThanEquals, + GreaterThan, + GreaterThanEquals, + LessThanLessThan, + GreaterThanGreaterThan, + GreaterThanGreaterThanGreaterThan, + Plus, + Minus, + Asterisk, + Slash, + Percent, + Tilde, + Exclamation, + PlusPlus, + MinusMinus, + Dot, + DotDotDot, + Error, + EndOfFile, + EqualsGreaterThan, + Identifier, + StringLiteral, + RegularExpressionLiteral, + NumberLiteral, + Whitespace, + Comment, + Lim, + LimFixed = EqualsGreaterThan, + LimKeyword = Yield, + } + + export var tokenTable = new TokenInfo[]; + export var nodeTypeTable = new string[]; + export var nodeTypeToTokTable = new number[]; + export var noRegexTable = new boolean[]; + + noRegexTable[TokenID.Identifier] = true; + noRegexTable[TokenID.StringLiteral] = true; + noRegexTable[TokenID.NumberLiteral] = true; + noRegexTable[TokenID.RegularExpressionLiteral] = true; + noRegexTable[TokenID.This] = true; + noRegexTable[TokenID.PlusPlus] = true; + noRegexTable[TokenID.MinusMinus] = true; + noRegexTable[TokenID.CloseParen] = true; + noRegexTable[TokenID.CloseBracket] = true; + noRegexTable[TokenID.CloseBrace] = true; + noRegexTable[TokenID.True] = true; + noRegexTable[TokenID.False] = true; + + export enum OperatorPrecedence { + None, + Comma, + Assignment, + Conditional, + LogicalOr, + LogicalAnd, + BitwiseOr, + BitwiseExclusiveOr, + BitwiseAnd, + Equality, + Relational, + Shift, + Additive, + Multiplicative, + Unary, + Lim + } + + export enum Reservation { + None = 0, + Javascript = 1, + JavascriptFuture = 2, + TypeScript = 4, + JavascriptFutureStrict = 8, + TypeScriptAndJS = Javascript | TypeScript, + TypeScriptAndJSFuture = JavascriptFuture | TypeScript, + TypeScriptAndJSFutureStrict = JavascriptFutureStrict | TypeScript, + } + + export class TokenInfo { + constructor (public tokenId: TokenID, public reservation: Reservation, + public binopPrecedence: number, public binopNodeType: number, + public unopPrecedence: number, public unopNodeType: number, + public text: string, public ers: ErrorRecoverySet) { } + } + + function setTokenInfo(tokenId: TokenID, reservation: number, binopPrecedence: number, + binopNodeType: number, unopPrecedence: number, unopNodeType: number, + text: string, ers: ErrorRecoverySet) { + if (tokenId !== undefined) { + tokenTable[tokenId] = new TokenInfo(tokenId, reservation, binopPrecedence, + binopNodeType, unopPrecedence, unopNodeType, text, ers); + if (binopNodeType != NodeType.None) { + nodeTypeTable[binopNodeType] = text; + nodeTypeToTokTable[binopNodeType] = tokenId; + } + if (unopNodeType != NodeType.None) { + nodeTypeTable[unopNodeType] = text; + } + } + } + + setTokenInfo(TokenID.Any, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "any", ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Bool, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "boolean", ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Break, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "break", ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Case, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "case", ErrorRecoverySet.SCase); + setTokenInfo(TokenID.Catch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "catch", ErrorRecoverySet.Catch); + setTokenInfo(TokenID.Class, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "class", ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Const, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "const", ErrorRecoverySet.Var); + setTokenInfo(TokenID.Continue, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "continue", ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Debugger, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.Debugger, "debugger", ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Default, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "default", ErrorRecoverySet.SCase); + setTokenInfo(TokenID.Delete, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.Delete, "delete", ErrorRecoverySet.Prefix); + setTokenInfo(TokenID.Do, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "do", ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Else, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "else", ErrorRecoverySet.Else); + setTokenInfo(TokenID.Enum, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "enum", ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Export, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "export", ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Extends, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "extends", ErrorRecoverySet.None); + setTokenInfo(TokenID.Declare, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "declare", ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.False, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "false", ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Finally, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "finally", ErrorRecoverySet.Catch); + setTokenInfo(TokenID.For, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "for", ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Function, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "function", ErrorRecoverySet.Func); + setTokenInfo(TokenID.Constructor, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "constructor", ErrorRecoverySet.Func); + setTokenInfo(TokenID.Get, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "get", ErrorRecoverySet.Func); + setTokenInfo(TokenID.Set, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "set", ErrorRecoverySet.Func); + setTokenInfo(TokenID.If, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "if", ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Implements, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "implements", ErrorRecoverySet.None); + setTokenInfo(TokenID.Import, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "import", ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.In, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, NodeType.In, OperatorPrecedence.None, NodeType.None, "in", ErrorRecoverySet.None); + setTokenInfo(TokenID.InstanceOf, Reservation.TypeScriptAndJS, OperatorPrecedence.Relational, NodeType.InstOf, OperatorPrecedence.None, NodeType.None, "instanceof", ErrorRecoverySet.BinOp); + setTokenInfo(TokenID.Interface, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "interface", ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Let, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "let", ErrorRecoverySet.None); + setTokenInfo(TokenID.Module, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "module", ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.New, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "new", ErrorRecoverySet.PreOp); + setTokenInfo(TokenID.Number, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "number", ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Null, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "null", ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Package, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "package", ErrorRecoverySet.None); + setTokenInfo(TokenID.Private, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "private", ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Protected, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "protected", ErrorRecoverySet.None); + setTokenInfo(TokenID.Public, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "public", ErrorRecoverySet.TypeScriptS); + setTokenInfo(TokenID.Return, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "return", ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.Static, Reservation.TypeScriptAndJSFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "static", ErrorRecoverySet.None); + setTokenInfo(TokenID.String, Reservation.TypeScript, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "string", ErrorRecoverySet.PrimType); + setTokenInfo(TokenID.Super, Reservation.TypeScriptAndJSFuture, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "super", ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Switch, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "switch", ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.This, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "this", ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Throw, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "throw", ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.True, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "true", ErrorRecoverySet.RLit); + setTokenInfo(TokenID.Try, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "try", ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.TypeOf, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.Typeof, "typeof", ErrorRecoverySet.Prefix); + setTokenInfo(TokenID.Var, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "var", ErrorRecoverySet.Var); + setTokenInfo(TokenID.Void, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.Void, "void", ErrorRecoverySet.Prefix); + setTokenInfo(TokenID.With, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.With, "with", ErrorRecoverySet.Stmt); + setTokenInfo(TokenID.While, Reservation.TypeScriptAndJS, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "while", ErrorRecoverySet.While); + setTokenInfo(TokenID.Yield, Reservation.JavascriptFutureStrict, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "yield", ErrorRecoverySet.None); + + setTokenInfo(TokenID.Identifier, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "identifier", ErrorRecoverySet.ID); + setTokenInfo(TokenID.NumberLiteral, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "numberLiteral", ErrorRecoverySet.Literal); + setTokenInfo(TokenID.RegularExpressionLiteral, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "regex", ErrorRecoverySet.RegExp); + setTokenInfo(TokenID.StringLiteral, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "qstring", ErrorRecoverySet.Literal); + + // Non-operator non-identifier tokens + setTokenInfo(TokenID.Semicolon, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, ";", ErrorRecoverySet.SColon); // ; + setTokenInfo(TokenID.CloseParen, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, ")", ErrorRecoverySet.RParen); // ) + setTokenInfo(TokenID.CloseBracket, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "]", ErrorRecoverySet.RBrack); // ] + setTokenInfo(TokenID.OpenBrace, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "{", ErrorRecoverySet.LCurly); // { + setTokenInfo(TokenID.CloseBrace, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "}", ErrorRecoverySet.RCurly); // } + setTokenInfo(TokenID.DotDotDot, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "...", ErrorRecoverySet.None); // ... + + // Operator non-identifier tokens + setTokenInfo(TokenID.Comma, Reservation.None, OperatorPrecedence.Comma, NodeType.Comma, OperatorPrecedence.None, NodeType.None, ",", ErrorRecoverySet.Comma); // , + setTokenInfo(TokenID.Equals, Reservation.None, OperatorPrecedence.Assignment, NodeType.Asg, OperatorPrecedence.None, NodeType.None, "=", ErrorRecoverySet.Asg); // = + setTokenInfo(TokenID.PlusEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgAdd, OperatorPrecedence.None, NodeType.None, "+=", ErrorRecoverySet.BinOp); // += + setTokenInfo(TokenID.MinusEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgSub, OperatorPrecedence.None, NodeType.None, "-=", ErrorRecoverySet.BinOp); // -= + setTokenInfo(TokenID.AsteriskEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgMul, OperatorPrecedence.None, NodeType.None, "*=", ErrorRecoverySet.BinOp); // *= + + setTokenInfo(TokenID.SlashEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgDiv, OperatorPrecedence.None, NodeType.None, "/=", ErrorRecoverySet.BinOp); // /= + setTokenInfo(TokenID.PercentEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgMod, OperatorPrecedence.None, NodeType.None, "%=", ErrorRecoverySet.BinOp); // %= + setTokenInfo(TokenID.AmpersandEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgAnd, OperatorPrecedence.None, NodeType.None, "&=", ErrorRecoverySet.BinOp); // &= + setTokenInfo(TokenID.CaretEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgXor, OperatorPrecedence.None, NodeType.None, "^=", ErrorRecoverySet.BinOp); // ^= + setTokenInfo(TokenID.BarEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgOr, OperatorPrecedence.None, NodeType.None, "|=", ErrorRecoverySet.BinOp); // |= + setTokenInfo(TokenID.LessThanLessThanEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgLsh, OperatorPrecedence.None, NodeType.None, "<<=", ErrorRecoverySet.BinOp); // <<= + setTokenInfo(TokenID.GreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgRsh, OperatorPrecedence.None, NodeType.None, ">>=", ErrorRecoverySet.BinOp); // >>= + setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThanEquals, Reservation.None, OperatorPrecedence.Assignment, NodeType.AsgRs2, OperatorPrecedence.None, NodeType.None, ">>>=", ErrorRecoverySet.BinOp); // >>>= + setTokenInfo(TokenID.Question, Reservation.None, OperatorPrecedence.Conditional, NodeType.ConditionalExpression, OperatorPrecedence.None, NodeType.None, "?", ErrorRecoverySet.BinOp); // ? + setTokenInfo(TokenID.Colon, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, ":", ErrorRecoverySet.Colon); // : + setTokenInfo(TokenID.BarBar, Reservation.None, OperatorPrecedence.LogicalOr, NodeType.LogOr, OperatorPrecedence.None, NodeType.None, "||", ErrorRecoverySet.BinOp); // || + setTokenInfo(TokenID.AmpersandAmpersand, Reservation.None, OperatorPrecedence.LogicalAnd, NodeType.LogAnd, OperatorPrecedence.None, NodeType.None, "&&", ErrorRecoverySet.BinOp); // && + setTokenInfo(TokenID.Bar, Reservation.None, OperatorPrecedence.BitwiseOr, NodeType.Or, OperatorPrecedence.None, NodeType.None, "|", ErrorRecoverySet.BinOp); // | + setTokenInfo(TokenID.Caret, Reservation.None, OperatorPrecedence.BitwiseExclusiveOr, NodeType.Xor, OperatorPrecedence.None, NodeType.None, "^", ErrorRecoverySet.BinOp); // ^ + setTokenInfo(TokenID.And, Reservation.None, OperatorPrecedence.BitwiseAnd, NodeType.And, OperatorPrecedence.None, NodeType.None, "&", ErrorRecoverySet.BinOp); // & + setTokenInfo(TokenID.EqualsEquals, Reservation.None, OperatorPrecedence.Equality, NodeType.Eq, OperatorPrecedence.None, NodeType.None, "==", ErrorRecoverySet.BinOp); // == + setTokenInfo(TokenID.ExclamationEquals, Reservation.None, OperatorPrecedence.Equality, NodeType.Ne, OperatorPrecedence.None, NodeType.None, "!=", ErrorRecoverySet.BinOp); // != + setTokenInfo(TokenID.EqualsEqualsEquals, Reservation.None, OperatorPrecedence.Equality, NodeType.Eqv, OperatorPrecedence.None, NodeType.None, "===", ErrorRecoverySet.BinOp); // === + setTokenInfo(TokenID.ExclamationEqualsEquals, Reservation.None, OperatorPrecedence.Equality, NodeType.NEqv, OperatorPrecedence.None, NodeType.None, "!==", ErrorRecoverySet.BinOp); // !== + setTokenInfo(TokenID.LessThan, Reservation.None, OperatorPrecedence.Relational, NodeType.Lt, OperatorPrecedence.None, NodeType.None, "<", ErrorRecoverySet.BinOp); // < + setTokenInfo(TokenID.LessThanEquals, Reservation.None, OperatorPrecedence.Relational, NodeType.Le, OperatorPrecedence.None, NodeType.None, "<=", ErrorRecoverySet.BinOp); // <= + setTokenInfo(TokenID.GreaterThan, Reservation.None, OperatorPrecedence.Relational, NodeType.Gt, OperatorPrecedence.None, NodeType.None, ">", ErrorRecoverySet.BinOp); // > + setTokenInfo(TokenID.GreaterThanEquals, Reservation.None, OperatorPrecedence.Relational, NodeType.Ge, OperatorPrecedence.None, NodeType.None, ">=", ErrorRecoverySet.BinOp); // >= + setTokenInfo(TokenID.LessThanLessThan, Reservation.None, OperatorPrecedence.Shift, NodeType.Lsh, OperatorPrecedence.None, NodeType.None, "<<", ErrorRecoverySet.BinOp); // << + setTokenInfo(TokenID.GreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, NodeType.Rsh, OperatorPrecedence.None, NodeType.None, ">>", ErrorRecoverySet.BinOp); // >> + setTokenInfo(TokenID.GreaterThanGreaterThanGreaterThan, Reservation.None, OperatorPrecedence.Shift, NodeType.Rs2, OperatorPrecedence.None, NodeType.None, ">>>", ErrorRecoverySet.BinOp); // >>> + setTokenInfo(TokenID.Plus, Reservation.None, OperatorPrecedence.Additive, NodeType.Add, OperatorPrecedence.Unary, NodeType.Pos, "+", ErrorRecoverySet.AddOp); // + + setTokenInfo(TokenID.Minus, Reservation.None, OperatorPrecedence.Additive, NodeType.Sub, OperatorPrecedence.Unary, NodeType.Neg, "-", ErrorRecoverySet.AddOp); // - + setTokenInfo(TokenID.Asterisk, Reservation.None, OperatorPrecedence.Multiplicative, NodeType.Mul, OperatorPrecedence.None, NodeType.None, "*", ErrorRecoverySet.BinOp); // * + setTokenInfo(TokenID.Slash, Reservation.None, OperatorPrecedence.Multiplicative, NodeType.Div, OperatorPrecedence.None, NodeType.None, "/", ErrorRecoverySet.BinOp); // / + setTokenInfo(TokenID.Percent, Reservation.None, OperatorPrecedence.Multiplicative, NodeType.Mod, OperatorPrecedence.None, NodeType.None, "%", ErrorRecoverySet.BinOp); // % + setTokenInfo(TokenID.Tilde, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.Not, "~", ErrorRecoverySet.PreOp); // ~ + setTokenInfo(TokenID.Exclamation, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.LogNot, "!", ErrorRecoverySet.PreOp); // ! + setTokenInfo(TokenID.PlusPlus, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.IncPre, "++", ErrorRecoverySet.PreOp); // ++ + setTokenInfo(TokenID.MinusMinus, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.Unary, NodeType.DecPre, "--", ErrorRecoverySet.PreOp); // -- + setTokenInfo(TokenID.OpenParen, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "(", ErrorRecoverySet.LParen); // ( + setTokenInfo(TokenID.OpenBracket, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "[", ErrorRecoverySet.LBrack); // [ + setTokenInfo(TokenID.Dot, Reservation.None, OperatorPrecedence.Unary, NodeType.None, OperatorPrecedence.None, NodeType.None, ".", ErrorRecoverySet.Dot); // . + setTokenInfo(TokenID.EndOfFile, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "", ErrorRecoverySet.EOF); // EOF + setTokenInfo(TokenID.EqualsGreaterThan, Reservation.None, OperatorPrecedence.None, NodeType.None, OperatorPrecedence.None, NodeType.None, "=>", ErrorRecoverySet.None); // => + + export function lookupToken(tokenId: TokenID): TokenInfo { + return tokenTable[tokenId]; + } + + export enum TokenClass { + Punctuation, + Keyword, + Operator, + Comment, + Whitespace, + Identifier, + Literal, + } + + export class SavedToken { + constructor (public tok: Token, public minChar: number, public limChar: number) { } + } + + export class Token { + constructor (public tokenId: TokenID) { + } + + public toString() { + return "token: " + this.tokenId + " " + this.getText() + " (" + (TokenID)._map[this.tokenId] + ")"; + } + + public print(line: number, outfile) { + outfile.WriteLine(this.toString() + ",on line" + line); + } + + public getText(): string { + return tokenTable[this.tokenId].text; + } + + public classification(): TokenClass { + if (this.tokenId <= TokenID.LimKeyword) { + return TokenClass.Keyword; + } + else { + var tokenInfo = lookupToken(this.tokenId); + if (tokenInfo != undefined) { + if ((tokenInfo.unopNodeType != NodeType.None) || + (tokenInfo.binopNodeType != NodeType.None)) { + return TokenClass.Operator; + } + } + } + + return TokenClass.Punctuation; + } + } + + export class NumberLiteralToken extends Token { + constructor (public value: number, public hasEmptyFraction?: boolean) { + super(TokenID.NumberLiteral); + } + + public getText(): string { + return this.hasEmptyFraction ? this.value.toString() + ".0" : this.value.toString(); + } + + public classification(): TokenClass { + return TokenClass.Literal; + } + } + + export class StringLiteralToken extends Token { + constructor (public value: string) { + super(TokenID.StringLiteral); + } + + public getText(): string { + return this.value; + } + + public classification(): TokenClass { + return TokenClass.Literal; + } + } + + export class IdentifierToken extends Token { + constructor (public value: string, public hasEscapeSequence : boolean) { + super(TokenID.Identifier); + } + public getText(): string { + return this.value; + } + public classification(): TokenClass { + return TokenClass.Identifier; + } + } + + export class WhitespaceToken extends Token { + constructor (tokenId: TokenID, public value: string) { + super(tokenId); + } + + public getText(): string { + return this.value; + } + + public classification(): TokenClass { + return TokenClass.Whitespace; + } + } + + export class CommentToken extends Token { + constructor (tokenID: TokenID, public value: string, public isBlock: boolean, public startPos: number, public line: number, public endsLine: boolean) { + super(tokenID); + } + + public getText(): string { + return this.value; + } + + public classification(): TokenClass { + return TokenClass.Comment; + } + } + + export class RegularExpressionLiteralToken extends Token { + constructor(public regex) { + super(TokenID.RegularExpressionLiteral); + } + + public getText(): string { + return this.regex.toString(); + } + + public classification(): TokenClass { + return TokenClass.Literal; + } + } + + // TODO: new with length TokenID.LimFixed + export var staticTokens = new Token[]; + export function initializeStaticTokens() { + for (var i = 0; i <= TokenID.LimFixed; i++) { + staticTokens[i] = new Token(i); + } + } +} + +//// [parserRealSource10.js] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +/// +var TypeScript; +(function (TypeScript) { + (function (TokenID) { + // Keywords + TokenID[TokenID["Any"] = 0] = "Any"; + TokenID[TokenID["Bool"] = 1] = "Bool"; + TokenID[TokenID["Break"] = 2] = "Break"; + TokenID[TokenID["Case"] = 3] = "Case"; + TokenID[TokenID["Catch"] = 4] = "Catch"; + TokenID[TokenID["Class"] = 5] = "Class"; + TokenID[TokenID["Const"] = 6] = "Const"; + TokenID[TokenID["Continue"] = 7] = "Continue"; + TokenID[TokenID["Debugger"] = 8] = "Debugger"; + TokenID[TokenID["Default"] = 9] = "Default"; + TokenID[TokenID["Delete"] = 10] = "Delete"; + TokenID[TokenID["Do"] = 11] = "Do"; + TokenID[TokenID["Else"] = 12] = "Else"; + TokenID[TokenID["Enum"] = 13] = "Enum"; + TokenID[TokenID["Export"] = 14] = "Export"; + TokenID[TokenID["Extends"] = 15] = "Extends"; + TokenID[TokenID["Declare"] = 16] = "Declare"; + TokenID[TokenID["False"] = 17] = "False"; + TokenID[TokenID["Finally"] = 18] = "Finally"; + TokenID[TokenID["For"] = 19] = "For"; + TokenID[TokenID["Function"] = 20] = "Function"; + TokenID[TokenID["Constructor"] = 21] = "Constructor"; + TokenID[TokenID["Get"] = 22] = "Get"; + TokenID[TokenID["If"] = 23] = "If"; + TokenID[TokenID["Implements"] = 24] = "Implements"; + TokenID[TokenID["Import"] = 25] = "Import"; + TokenID[TokenID["In"] = 26] = "In"; + TokenID[TokenID["InstanceOf"] = 27] = "InstanceOf"; + TokenID[TokenID["Interface"] = 28] = "Interface"; + TokenID[TokenID["Let"] = 29] = "Let"; + TokenID[TokenID["Module"] = 30] = "Module"; + TokenID[TokenID["New"] = 31] = "New"; + TokenID[TokenID["Number"] = 32] = "Number"; + TokenID[TokenID["Null"] = 33] = "Null"; + TokenID[TokenID["Package"] = 34] = "Package"; + TokenID[TokenID["Private"] = 35] = "Private"; + TokenID[TokenID["Protected"] = 36] = "Protected"; + TokenID[TokenID["Public"] = 37] = "Public"; + TokenID[TokenID["Return"] = 38] = "Return"; + TokenID[TokenID["Set"] = 39] = "Set"; + TokenID[TokenID["Static"] = 40] = "Static"; + TokenID[TokenID["String"] = 41] = "String"; + TokenID[TokenID["Super"] = 42] = "Super"; + TokenID[TokenID["Switch"] = 43] = "Switch"; + TokenID[TokenID["This"] = 44] = "This"; + TokenID[TokenID["Throw"] = 45] = "Throw"; + TokenID[TokenID["True"] = 46] = "True"; + TokenID[TokenID["Try"] = 47] = "Try"; + TokenID[TokenID["TypeOf"] = 48] = "TypeOf"; + TokenID[TokenID["Var"] = 49] = "Var"; + TokenID[TokenID["Void"] = 50] = "Void"; + TokenID[TokenID["With"] = 51] = "With"; + TokenID[TokenID["While"] = 52] = "While"; + TokenID[TokenID["Yield"] = 53] = "Yield"; + // Punctuation + TokenID[TokenID["Semicolon"] = 54] = "Semicolon"; + TokenID[TokenID["OpenParen"] = 55] = "OpenParen"; + TokenID[TokenID["CloseParen"] = 56] = "CloseParen"; + TokenID[TokenID["OpenBracket"] = 57] = "OpenBracket"; + TokenID[TokenID["CloseBracket"] = 58] = "CloseBracket"; + TokenID[TokenID["OpenBrace"] = 59] = "OpenBrace"; + TokenID[TokenID["CloseBrace"] = 60] = "CloseBrace"; + TokenID[TokenID["Comma"] = 61] = "Comma"; + TokenID[TokenID["Equals"] = 62] = "Equals"; + TokenID[TokenID["PlusEquals"] = 63] = "PlusEquals"; + TokenID[TokenID["MinusEquals"] = 64] = "MinusEquals"; + TokenID[TokenID["AsteriskEquals"] = 65] = "AsteriskEquals"; + TokenID[TokenID["SlashEquals"] = 66] = "SlashEquals"; + TokenID[TokenID["PercentEquals"] = 67] = "PercentEquals"; + TokenID[TokenID["AmpersandEquals"] = 68] = "AmpersandEquals"; + TokenID[TokenID["CaretEquals"] = 69] = "CaretEquals"; + TokenID[TokenID["BarEquals"] = 70] = "BarEquals"; + TokenID[TokenID["LessThanLessThanEquals"] = 71] = "LessThanLessThanEquals"; + TokenID[TokenID["GreaterThanGreaterThanEquals"] = 72] = "GreaterThanGreaterThanEquals"; + TokenID[TokenID["GreaterThanGreaterThanGreaterThanEquals"] = 73] = "GreaterThanGreaterThanGreaterThanEquals"; + TokenID[TokenID["Question"] = 74] = "Question"; + TokenID[TokenID["Colon"] = 75] = "Colon"; + TokenID[TokenID["BarBar"] = 76] = "BarBar"; + TokenID[TokenID["AmpersandAmpersand"] = 77] = "AmpersandAmpersand"; + TokenID[TokenID["Bar"] = 78] = "Bar"; + TokenID[TokenID["Caret"] = 79] = "Caret"; + TokenID[TokenID["And"] = 80] = "And"; + TokenID[TokenID["EqualsEquals"] = 81] = "EqualsEquals"; + TokenID[TokenID["ExclamationEquals"] = 82] = "ExclamationEquals"; + TokenID[TokenID["EqualsEqualsEquals"] = 83] = "EqualsEqualsEquals"; + TokenID[TokenID["ExclamationEqualsEquals"] = 84] = "ExclamationEqualsEquals"; + TokenID[TokenID["LessThan"] = 85] = "LessThan"; + TokenID[TokenID["LessThanEquals"] = 86] = "LessThanEquals"; + TokenID[TokenID["GreaterThan"] = 87] = "GreaterThan"; + TokenID[TokenID["GreaterThanEquals"] = 88] = "GreaterThanEquals"; + TokenID[TokenID["LessThanLessThan"] = 89] = "LessThanLessThan"; + TokenID[TokenID["GreaterThanGreaterThan"] = 90] = "GreaterThanGreaterThan"; + TokenID[TokenID["GreaterThanGreaterThanGreaterThan"] = 91] = "GreaterThanGreaterThanGreaterThan"; + TokenID[TokenID["Plus"] = 92] = "Plus"; + TokenID[TokenID["Minus"] = 93] = "Minus"; + TokenID[TokenID["Asterisk"] = 94] = "Asterisk"; + TokenID[TokenID["Slash"] = 95] = "Slash"; + TokenID[TokenID["Percent"] = 96] = "Percent"; + TokenID[TokenID["Tilde"] = 97] = "Tilde"; + TokenID[TokenID["Exclamation"] = 98] = "Exclamation"; + TokenID[TokenID["PlusPlus"] = 99] = "PlusPlus"; + TokenID[TokenID["MinusMinus"] = 100] = "MinusMinus"; + TokenID[TokenID["Dot"] = 101] = "Dot"; + TokenID[TokenID["DotDotDot"] = 102] = "DotDotDot"; + TokenID[TokenID["Error"] = 103] = "Error"; + TokenID[TokenID["EndOfFile"] = 104] = "EndOfFile"; + TokenID[TokenID["EqualsGreaterThan"] = 105] = "EqualsGreaterThan"; + TokenID[TokenID["Identifier"] = 106] = "Identifier"; + TokenID[TokenID["StringLiteral"] = 107] = "StringLiteral"; + TokenID[TokenID["RegularExpressionLiteral"] = 108] = "RegularExpressionLiteral"; + TokenID[TokenID["NumberLiteral"] = 109] = "NumberLiteral"; + TokenID[TokenID["Whitespace"] = 110] = "Whitespace"; + TokenID[TokenID["Comment"] = 111] = "Comment"; + TokenID[TokenID["Lim"] = 112] = "Lim"; + TokenID[TokenID["LimFixed"] = TokenID.EqualsGreaterThan] = "LimFixed"; + TokenID[TokenID["LimKeyword"] = TokenID.Yield] = "LimKeyword"; + })(TypeScript.TokenID || (TypeScript.TokenID = {})); + var TokenID = TypeScript.TokenID; + TypeScript.tokenTable = new TokenInfo[]; + TypeScript.nodeTypeTable = new string[]; + TypeScript.nodeTypeToTokTable = new number[]; + TypeScript.noRegexTable = new boolean[]; + TypeScript.noRegexTable[106 /* Identifier */] = true; + TypeScript.noRegexTable[107 /* StringLiteral */] = true; + TypeScript.noRegexTable[109 /* NumberLiteral */] = true; + TypeScript.noRegexTable[108 /* RegularExpressionLiteral */] = true; + TypeScript.noRegexTable[44 /* This */] = true; + TypeScript.noRegexTable[99 /* PlusPlus */] = true; + TypeScript.noRegexTable[100 /* MinusMinus */] = true; + TypeScript.noRegexTable[56 /* CloseParen */] = true; + TypeScript.noRegexTable[58 /* CloseBracket */] = true; + TypeScript.noRegexTable[60 /* CloseBrace */] = true; + TypeScript.noRegexTable[46 /* True */] = true; + TypeScript.noRegexTable[17 /* False */] = true; + (function (OperatorPrecedence) { + OperatorPrecedence[OperatorPrecedence["None"] = 0] = "None"; + OperatorPrecedence[OperatorPrecedence["Comma"] = 1] = "Comma"; + OperatorPrecedence[OperatorPrecedence["Assignment"] = 2] = "Assignment"; + OperatorPrecedence[OperatorPrecedence["Conditional"] = 3] = "Conditional"; + OperatorPrecedence[OperatorPrecedence["LogicalOr"] = 4] = "LogicalOr"; + OperatorPrecedence[OperatorPrecedence["LogicalAnd"] = 5] = "LogicalAnd"; + OperatorPrecedence[OperatorPrecedence["BitwiseOr"] = 6] = "BitwiseOr"; + OperatorPrecedence[OperatorPrecedence["BitwiseExclusiveOr"] = 7] = "BitwiseExclusiveOr"; + OperatorPrecedence[OperatorPrecedence["BitwiseAnd"] = 8] = "BitwiseAnd"; + OperatorPrecedence[OperatorPrecedence["Equality"] = 9] = "Equality"; + OperatorPrecedence[OperatorPrecedence["Relational"] = 10] = "Relational"; + OperatorPrecedence[OperatorPrecedence["Shift"] = 11] = "Shift"; + OperatorPrecedence[OperatorPrecedence["Additive"] = 12] = "Additive"; + OperatorPrecedence[OperatorPrecedence["Multiplicative"] = 13] = "Multiplicative"; + OperatorPrecedence[OperatorPrecedence["Unary"] = 14] = "Unary"; + OperatorPrecedence[OperatorPrecedence["Lim"] = 15] = "Lim"; + })(TypeScript.OperatorPrecedence || (TypeScript.OperatorPrecedence = {})); + var OperatorPrecedence = TypeScript.OperatorPrecedence; + (function (Reservation) { + Reservation[Reservation["None"] = 0] = "None"; + Reservation[Reservation["Javascript"] = 1] = "Javascript"; + Reservation[Reservation["JavascriptFuture"] = 2] = "JavascriptFuture"; + Reservation[Reservation["TypeScript"] = 4] = "TypeScript"; + Reservation[Reservation["JavascriptFutureStrict"] = 8] = "JavascriptFutureStrict"; + Reservation[Reservation["TypeScriptAndJS"] = Reservation.Javascript | Reservation.TypeScript] = "TypeScriptAndJS"; + Reservation[Reservation["TypeScriptAndJSFuture"] = Reservation.JavascriptFuture | Reservation.TypeScript] = "TypeScriptAndJSFuture"; + Reservation[Reservation["TypeScriptAndJSFutureStrict"] = Reservation.JavascriptFutureStrict | Reservation.TypeScript] = "TypeScriptAndJSFutureStrict"; + })(TypeScript.Reservation || (TypeScript.Reservation = {})); + var Reservation = TypeScript.Reservation; + var TokenInfo = (function () { + function TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { + this.tokenId = tokenId; + this.reservation = reservation; + this.binopPrecedence = binopPrecedence; + this.binopNodeType = binopNodeType; + this.unopPrecedence = unopPrecedence; + this.unopNodeType = unopNodeType; + this.text = text; + this.ers = ers; + } + return TokenInfo; + })(); + TypeScript.TokenInfo = TokenInfo; + function setTokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers) { + if (tokenId !== undefined) { + TypeScript.tokenTable[tokenId] = new TokenInfo(tokenId, reservation, binopPrecedence, binopNodeType, unopPrecedence, unopNodeType, text, ers); + if (binopNodeType != NodeType.None) { + TypeScript.nodeTypeTable[binopNodeType] = text; + TypeScript.nodeTypeToTokTable[binopNodeType] = tokenId; + } + if (unopNodeType != NodeType.None) { + TypeScript.nodeTypeTable[unopNodeType] = text; + } + } + } + setTokenInfo(0 /* Any */, 4 /* TypeScript */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "any", ErrorRecoverySet.PrimType); + setTokenInfo(1 /* Bool */, 4 /* TypeScript */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "boolean", ErrorRecoverySet.PrimType); + setTokenInfo(2 /* Break */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "break", ErrorRecoverySet.Stmt); + setTokenInfo(3 /* Case */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "case", ErrorRecoverySet.SCase); + setTokenInfo(4 /* Catch */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "catch", ErrorRecoverySet.Catch); + setTokenInfo(5 /* Class */, Reservation.TypeScriptAndJSFuture, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "class", ErrorRecoverySet.TypeScriptS); + setTokenInfo(6 /* Const */, Reservation.TypeScriptAndJSFuture, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "const", ErrorRecoverySet.Var); + setTokenInfo(7 /* Continue */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "continue", ErrorRecoverySet.Stmt); + setTokenInfo(8 /* Debugger */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.Debugger, "debugger", ErrorRecoverySet.Stmt); + setTokenInfo(9 /* Default */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "default", ErrorRecoverySet.SCase); + setTokenInfo(10 /* Delete */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 14 /* Unary */, NodeType.Delete, "delete", ErrorRecoverySet.Prefix); + setTokenInfo(11 /* Do */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "do", ErrorRecoverySet.Stmt); + setTokenInfo(12 /* Else */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "else", ErrorRecoverySet.Else); + setTokenInfo(13 /* Enum */, Reservation.TypeScriptAndJSFuture, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "enum", ErrorRecoverySet.TypeScriptS); + setTokenInfo(14 /* Export */, Reservation.TypeScriptAndJSFuture, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "export", ErrorRecoverySet.TypeScriptS); + setTokenInfo(15 /* Extends */, Reservation.TypeScriptAndJSFuture, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "extends", ErrorRecoverySet.None); + setTokenInfo(16 /* Declare */, 4 /* TypeScript */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "declare", ErrorRecoverySet.Stmt); + setTokenInfo(17 /* False */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "false", ErrorRecoverySet.RLit); + setTokenInfo(18 /* Finally */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "finally", ErrorRecoverySet.Catch); + setTokenInfo(19 /* For */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "for", ErrorRecoverySet.Stmt); + setTokenInfo(20 /* Function */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "function", ErrorRecoverySet.Func); + setTokenInfo(21 /* Constructor */, Reservation.TypeScriptAndJSFutureStrict, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "constructor", ErrorRecoverySet.Func); + setTokenInfo(22 /* Get */, 4 /* TypeScript */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "get", ErrorRecoverySet.Func); + setTokenInfo(39 /* Set */, 4 /* TypeScript */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "set", ErrorRecoverySet.Func); + setTokenInfo(23 /* If */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "if", ErrorRecoverySet.Stmt); + setTokenInfo(24 /* Implements */, Reservation.TypeScriptAndJSFutureStrict, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "implements", ErrorRecoverySet.None); + setTokenInfo(25 /* Import */, Reservation.TypeScriptAndJSFuture, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "import", ErrorRecoverySet.TypeScriptS); + setTokenInfo(26 /* In */, Reservation.TypeScriptAndJS, 10 /* Relational */, NodeType.In, 0 /* None */, NodeType.None, "in", ErrorRecoverySet.None); + setTokenInfo(27 /* InstanceOf */, Reservation.TypeScriptAndJS, 10 /* Relational */, NodeType.InstOf, 0 /* None */, NodeType.None, "instanceof", ErrorRecoverySet.BinOp); + setTokenInfo(28 /* Interface */, Reservation.TypeScriptAndJSFutureStrict, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "interface", ErrorRecoverySet.TypeScriptS); + setTokenInfo(29 /* Let */, 8 /* JavascriptFutureStrict */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "let", ErrorRecoverySet.None); + setTokenInfo(30 /* Module */, 4 /* TypeScript */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "module", ErrorRecoverySet.TypeScriptS); + setTokenInfo(31 /* New */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "new", ErrorRecoverySet.PreOp); + setTokenInfo(32 /* Number */, 4 /* TypeScript */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "number", ErrorRecoverySet.PrimType); + setTokenInfo(33 /* Null */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "null", ErrorRecoverySet.RLit); + setTokenInfo(34 /* Package */, 8 /* JavascriptFutureStrict */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "package", ErrorRecoverySet.None); + setTokenInfo(35 /* Private */, Reservation.TypeScriptAndJSFutureStrict, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "private", ErrorRecoverySet.TypeScriptS); + setTokenInfo(36 /* Protected */, 8 /* JavascriptFutureStrict */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "protected", ErrorRecoverySet.None); + setTokenInfo(37 /* Public */, Reservation.TypeScriptAndJSFutureStrict, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "public", ErrorRecoverySet.TypeScriptS); + setTokenInfo(38 /* Return */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "return", ErrorRecoverySet.Stmt); + setTokenInfo(40 /* Static */, Reservation.TypeScriptAndJSFutureStrict, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "static", ErrorRecoverySet.None); + setTokenInfo(41 /* String */, 4 /* TypeScript */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "string", ErrorRecoverySet.PrimType); + setTokenInfo(42 /* Super */, Reservation.TypeScriptAndJSFuture, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "super", ErrorRecoverySet.RLit); + setTokenInfo(43 /* Switch */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "switch", ErrorRecoverySet.Stmt); + setTokenInfo(44 /* This */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "this", ErrorRecoverySet.RLit); + setTokenInfo(45 /* Throw */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "throw", ErrorRecoverySet.Stmt); + setTokenInfo(46 /* True */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "true", ErrorRecoverySet.RLit); + setTokenInfo(47 /* Try */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "try", ErrorRecoverySet.Stmt); + setTokenInfo(48 /* TypeOf */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 14 /* Unary */, NodeType.Typeof, "typeof", ErrorRecoverySet.Prefix); + setTokenInfo(49 /* Var */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "var", ErrorRecoverySet.Var); + setTokenInfo(50 /* Void */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 14 /* Unary */, NodeType.Void, "void", ErrorRecoverySet.Prefix); + setTokenInfo(51 /* With */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.With, "with", ErrorRecoverySet.Stmt); + setTokenInfo(52 /* While */, Reservation.TypeScriptAndJS, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "while", ErrorRecoverySet.While); + setTokenInfo(53 /* Yield */, 8 /* JavascriptFutureStrict */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "yield", ErrorRecoverySet.None); + setTokenInfo(106 /* Identifier */, 0 /* None */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "identifier", ErrorRecoverySet.ID); + setTokenInfo(109 /* NumberLiteral */, 0 /* None */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "numberLiteral", ErrorRecoverySet.Literal); + setTokenInfo(108 /* RegularExpressionLiteral */, 0 /* None */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "regex", ErrorRecoverySet.RegExp); + setTokenInfo(107 /* StringLiteral */, 0 /* None */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "qstring", ErrorRecoverySet.Literal); + // Non-operator non-identifier tokens + setTokenInfo(54 /* Semicolon */, 0 /* None */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, ";", ErrorRecoverySet.SColon); // ; + setTokenInfo(56 /* CloseParen */, 0 /* None */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, ")", ErrorRecoverySet.RParen); // ) + setTokenInfo(58 /* CloseBracket */, 0 /* None */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "]", ErrorRecoverySet.RBrack); // ] + setTokenInfo(59 /* OpenBrace */, 0 /* None */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "{", ErrorRecoverySet.LCurly); // { + setTokenInfo(60 /* CloseBrace */, 0 /* None */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "}", ErrorRecoverySet.RCurly); // } + setTokenInfo(102 /* DotDotDot */, 0 /* None */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "...", ErrorRecoverySet.None); // ... + // Operator non-identifier tokens + setTokenInfo(61 /* Comma */, 0 /* None */, 1 /* Comma */, NodeType.Comma, 0 /* None */, NodeType.None, ",", ErrorRecoverySet.Comma); // , + setTokenInfo(62 /* Equals */, 0 /* None */, 2 /* Assignment */, NodeType.Asg, 0 /* None */, NodeType.None, "=", ErrorRecoverySet.Asg); // = + setTokenInfo(63 /* PlusEquals */, 0 /* None */, 2 /* Assignment */, NodeType.AsgAdd, 0 /* None */, NodeType.None, "+=", ErrorRecoverySet.BinOp); // += + setTokenInfo(64 /* MinusEquals */, 0 /* None */, 2 /* Assignment */, NodeType.AsgSub, 0 /* None */, NodeType.None, "-=", ErrorRecoverySet.BinOp); // -= + setTokenInfo(65 /* AsteriskEquals */, 0 /* None */, 2 /* Assignment */, NodeType.AsgMul, 0 /* None */, NodeType.None, "*=", ErrorRecoverySet.BinOp); // *= + setTokenInfo(66 /* SlashEquals */, 0 /* None */, 2 /* Assignment */, NodeType.AsgDiv, 0 /* None */, NodeType.None, "/=", ErrorRecoverySet.BinOp); // /= + setTokenInfo(67 /* PercentEquals */, 0 /* None */, 2 /* Assignment */, NodeType.AsgMod, 0 /* None */, NodeType.None, "%=", ErrorRecoverySet.BinOp); // %= + setTokenInfo(68 /* AmpersandEquals */, 0 /* None */, 2 /* Assignment */, NodeType.AsgAnd, 0 /* None */, NodeType.None, "&=", ErrorRecoverySet.BinOp); // &= + setTokenInfo(69 /* CaretEquals */, 0 /* None */, 2 /* Assignment */, NodeType.AsgXor, 0 /* None */, NodeType.None, "^=", ErrorRecoverySet.BinOp); // ^= + setTokenInfo(70 /* BarEquals */, 0 /* None */, 2 /* Assignment */, NodeType.AsgOr, 0 /* None */, NodeType.None, "|=", ErrorRecoverySet.BinOp); // |= + setTokenInfo(71 /* LessThanLessThanEquals */, 0 /* None */, 2 /* Assignment */, NodeType.AsgLsh, 0 /* None */, NodeType.None, "<<=", ErrorRecoverySet.BinOp); // <<= + setTokenInfo(72 /* GreaterThanGreaterThanEquals */, 0 /* None */, 2 /* Assignment */, NodeType.AsgRsh, 0 /* None */, NodeType.None, ">>=", ErrorRecoverySet.BinOp); // >>= + setTokenInfo(73 /* GreaterThanGreaterThanGreaterThanEquals */, 0 /* None */, 2 /* Assignment */, NodeType.AsgRs2, 0 /* None */, NodeType.None, ">>>=", ErrorRecoverySet.BinOp); // >>>= + setTokenInfo(74 /* Question */, 0 /* None */, 3 /* Conditional */, NodeType.ConditionalExpression, 0 /* None */, NodeType.None, "?", ErrorRecoverySet.BinOp); // ? + setTokenInfo(75 /* Colon */, 0 /* None */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, ":", ErrorRecoverySet.Colon); // : + setTokenInfo(76 /* BarBar */, 0 /* None */, 4 /* LogicalOr */, NodeType.LogOr, 0 /* None */, NodeType.None, "||", ErrorRecoverySet.BinOp); // || + setTokenInfo(77 /* AmpersandAmpersand */, 0 /* None */, 5 /* LogicalAnd */, NodeType.LogAnd, 0 /* None */, NodeType.None, "&&", ErrorRecoverySet.BinOp); // && + setTokenInfo(78 /* Bar */, 0 /* None */, 6 /* BitwiseOr */, NodeType.Or, 0 /* None */, NodeType.None, "|", ErrorRecoverySet.BinOp); // | + setTokenInfo(79 /* Caret */, 0 /* None */, 7 /* BitwiseExclusiveOr */, NodeType.Xor, 0 /* None */, NodeType.None, "^", ErrorRecoverySet.BinOp); // ^ + setTokenInfo(80 /* And */, 0 /* None */, 8 /* BitwiseAnd */, NodeType.And, 0 /* None */, NodeType.None, "&", ErrorRecoverySet.BinOp); // & + setTokenInfo(81 /* EqualsEquals */, 0 /* None */, 9 /* Equality */, NodeType.Eq, 0 /* None */, NodeType.None, "==", ErrorRecoverySet.BinOp); // == + setTokenInfo(82 /* ExclamationEquals */, 0 /* None */, 9 /* Equality */, NodeType.Ne, 0 /* None */, NodeType.None, "!=", ErrorRecoverySet.BinOp); // != + setTokenInfo(83 /* EqualsEqualsEquals */, 0 /* None */, 9 /* Equality */, NodeType.Eqv, 0 /* None */, NodeType.None, "===", ErrorRecoverySet.BinOp); // === + setTokenInfo(84 /* ExclamationEqualsEquals */, 0 /* None */, 9 /* Equality */, NodeType.NEqv, 0 /* None */, NodeType.None, "!==", ErrorRecoverySet.BinOp); // !== + setTokenInfo(85 /* LessThan */, 0 /* None */, 10 /* Relational */, NodeType.Lt, 0 /* None */, NodeType.None, "<", ErrorRecoverySet.BinOp); // < + setTokenInfo(86 /* LessThanEquals */, 0 /* None */, 10 /* Relational */, NodeType.Le, 0 /* None */, NodeType.None, "<=", ErrorRecoverySet.BinOp); // <= + setTokenInfo(87 /* GreaterThan */, 0 /* None */, 10 /* Relational */, NodeType.Gt, 0 /* None */, NodeType.None, ">", ErrorRecoverySet.BinOp); // > + setTokenInfo(88 /* GreaterThanEquals */, 0 /* None */, 10 /* Relational */, NodeType.Ge, 0 /* None */, NodeType.None, ">=", ErrorRecoverySet.BinOp); // >= + setTokenInfo(89 /* LessThanLessThan */, 0 /* None */, 11 /* Shift */, NodeType.Lsh, 0 /* None */, NodeType.None, "<<", ErrorRecoverySet.BinOp); // << + setTokenInfo(90 /* GreaterThanGreaterThan */, 0 /* None */, 11 /* Shift */, NodeType.Rsh, 0 /* None */, NodeType.None, ">>", ErrorRecoverySet.BinOp); // >> + setTokenInfo(91 /* GreaterThanGreaterThanGreaterThan */, 0 /* None */, 11 /* Shift */, NodeType.Rs2, 0 /* None */, NodeType.None, ">>>", ErrorRecoverySet.BinOp); // >>> + setTokenInfo(92 /* Plus */, 0 /* None */, 12 /* Additive */, NodeType.Add, 14 /* Unary */, NodeType.Pos, "+", ErrorRecoverySet.AddOp); // + + setTokenInfo(93 /* Minus */, 0 /* None */, 12 /* Additive */, NodeType.Sub, 14 /* Unary */, NodeType.Neg, "-", ErrorRecoverySet.AddOp); // - + setTokenInfo(94 /* Asterisk */, 0 /* None */, 13 /* Multiplicative */, NodeType.Mul, 0 /* None */, NodeType.None, "*", ErrorRecoverySet.BinOp); // * + setTokenInfo(95 /* Slash */, 0 /* None */, 13 /* Multiplicative */, NodeType.Div, 0 /* None */, NodeType.None, "/", ErrorRecoverySet.BinOp); // / + setTokenInfo(96 /* Percent */, 0 /* None */, 13 /* Multiplicative */, NodeType.Mod, 0 /* None */, NodeType.None, "%", ErrorRecoverySet.BinOp); // % + setTokenInfo(97 /* Tilde */, 0 /* None */, 0 /* None */, NodeType.None, 14 /* Unary */, NodeType.Not, "~", ErrorRecoverySet.PreOp); // ~ + setTokenInfo(98 /* Exclamation */, 0 /* None */, 0 /* None */, NodeType.None, 14 /* Unary */, NodeType.LogNot, "!", ErrorRecoverySet.PreOp); // ! + setTokenInfo(99 /* PlusPlus */, 0 /* None */, 0 /* None */, NodeType.None, 14 /* Unary */, NodeType.IncPre, "++", ErrorRecoverySet.PreOp); // ++ + setTokenInfo(100 /* MinusMinus */, 0 /* None */, 0 /* None */, NodeType.None, 14 /* Unary */, NodeType.DecPre, "--", ErrorRecoverySet.PreOp); // -- + setTokenInfo(55 /* OpenParen */, 0 /* None */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "(", ErrorRecoverySet.LParen); // ( + setTokenInfo(57 /* OpenBracket */, 0 /* None */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "[", ErrorRecoverySet.LBrack); // [ + setTokenInfo(101 /* Dot */, 0 /* None */, 14 /* Unary */, NodeType.None, 0 /* None */, NodeType.None, ".", ErrorRecoverySet.Dot); // . + setTokenInfo(104 /* EndOfFile */, 0 /* None */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "", ErrorRecoverySet.EOF); // EOF + setTokenInfo(105 /* EqualsGreaterThan */, 0 /* None */, 0 /* None */, NodeType.None, 0 /* None */, NodeType.None, "=>", ErrorRecoverySet.None); // => + function lookupToken(tokenId) { + return TypeScript.tokenTable[tokenId]; + } + TypeScript.lookupToken = lookupToken; + (function (TokenClass) { + TokenClass[TokenClass["Punctuation"] = 0] = "Punctuation"; + TokenClass[TokenClass["Keyword"] = 1] = "Keyword"; + TokenClass[TokenClass["Operator"] = 2] = "Operator"; + TokenClass[TokenClass["Comment"] = 3] = "Comment"; + TokenClass[TokenClass["Whitespace"] = 4] = "Whitespace"; + TokenClass[TokenClass["Identifier"] = 5] = "Identifier"; + TokenClass[TokenClass["Literal"] = 6] = "Literal"; + })(TypeScript.TokenClass || (TypeScript.TokenClass = {})); + var TokenClass = TypeScript.TokenClass; + var SavedToken = (function () { + function SavedToken(tok, minChar, limChar) { + this.tok = tok; + this.minChar = minChar; + this.limChar = limChar; + } + return SavedToken; + })(); + TypeScript.SavedToken = SavedToken; + var Token = (function () { + function Token(tokenId) { + this.tokenId = tokenId; + } + Token.prototype.toString = function () { + return "token: " + this.tokenId + " " + this.getText() + " (" + TokenID._map[this.tokenId] + ")"; + }; + Token.prototype.print = function (line, outfile) { + outfile.WriteLine(this.toString() + ",on line" + line); + }; + Token.prototype.getText = function () { + return TypeScript.tokenTable[this.tokenId].text; + }; + Token.prototype.classification = function () { + if (this.tokenId <= TokenID.LimKeyword) { + return 1 /* Keyword */; + } + else { + var tokenInfo = lookupToken(this.tokenId); + if (tokenInfo != undefined) { + if ((tokenInfo.unopNodeType != NodeType.None) || (tokenInfo.binopNodeType != NodeType.None)) { + return 2 /* Operator */; + } + } + } + return 0 /* Punctuation */; + }; + return Token; + })(); + TypeScript.Token = Token; + var NumberLiteralToken = (function (_super) { + __extends(NumberLiteralToken, _super); + function NumberLiteralToken(value, hasEmptyFraction) { + _super.call(this, 109 /* NumberLiteral */); + this.value = value; + this.hasEmptyFraction = hasEmptyFraction; + } + NumberLiteralToken.prototype.getText = function () { + return this.hasEmptyFraction ? this.value.toString() + ".0" : this.value.toString(); + }; + NumberLiteralToken.prototype.classification = function () { + return 6 /* Literal */; + }; + return NumberLiteralToken; + })(Token); + TypeScript.NumberLiteralToken = NumberLiteralToken; + var StringLiteralToken = (function (_super) { + __extends(StringLiteralToken, _super); + function StringLiteralToken(value) { + _super.call(this, 107 /* StringLiteral */); + this.value = value; + } + StringLiteralToken.prototype.getText = function () { + return this.value; + }; + StringLiteralToken.prototype.classification = function () { + return 6 /* Literal */; + }; + return StringLiteralToken; + })(Token); + TypeScript.StringLiteralToken = StringLiteralToken; + var IdentifierToken = (function (_super) { + __extends(IdentifierToken, _super); + function IdentifierToken(value, hasEscapeSequence) { + _super.call(this, 106 /* Identifier */); + this.value = value; + this.hasEscapeSequence = hasEscapeSequence; + } + IdentifierToken.prototype.getText = function () { + return this.value; + }; + IdentifierToken.prototype.classification = function () { + return 5 /* Identifier */; + }; + return IdentifierToken; + })(Token); + TypeScript.IdentifierToken = IdentifierToken; + var WhitespaceToken = (function (_super) { + __extends(WhitespaceToken, _super); + function WhitespaceToken(tokenId, value) { + _super.call(this, tokenId); + this.value = value; + } + WhitespaceToken.prototype.getText = function () { + return this.value; + }; + WhitespaceToken.prototype.classification = function () { + return 4 /* Whitespace */; + }; + return WhitespaceToken; + })(Token); + TypeScript.WhitespaceToken = WhitespaceToken; + var CommentToken = (function (_super) { + __extends(CommentToken, _super); + function CommentToken(tokenID, value, isBlock, startPos, line, endsLine) { + _super.call(this, tokenID); + this.value = value; + this.isBlock = isBlock; + this.startPos = startPos; + this.line = line; + this.endsLine = endsLine; + } + CommentToken.prototype.getText = function () { + return this.value; + }; + CommentToken.prototype.classification = function () { + return 3 /* Comment */; + }; + return CommentToken; + })(Token); + TypeScript.CommentToken = CommentToken; + var RegularExpressionLiteralToken = (function (_super) { + __extends(RegularExpressionLiteralToken, _super); + function RegularExpressionLiteralToken(regex) { + _super.call(this, 108 /* RegularExpressionLiteral */); + this.regex = regex; + } + RegularExpressionLiteralToken.prototype.getText = function () { + return this.regex.toString(); + }; + RegularExpressionLiteralToken.prototype.classification = function () { + return 6 /* Literal */; + }; + return RegularExpressionLiteralToken; + })(Token); + TypeScript.RegularExpressionLiteralToken = RegularExpressionLiteralToken; + // TODO: new with length TokenID.LimFixed + TypeScript.staticTokens = new Token[]; + function initializeStaticTokens() { + for (var i = 0; i <= TokenID.LimFixed; i++) { + TypeScript.staticTokens[i] = new Token(i); + } + } + TypeScript.initializeStaticTokens = initializeStaticTokens; +})(TypeScript || (TypeScript = {})); diff --git a/tests/baselines/reference/parserRealSource11.js b/tests/baselines/reference/parserRealSource11.js new file mode 100644 index 00000000000..0574c52eaaa --- /dev/null +++ b/tests/baselines/reference/parserRealSource11.js @@ -0,0 +1,4717 @@ +//// [parserRealSource11.ts] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. + +/// + +module TypeScript { + export class ASTSpan { + public minChar: number = -1; // -1 = "undefined" or "compiler generated" + public limChar: number = -1; // -1 = "undefined" or "compiler generated" + } + + export class AST extends ASTSpan { + public type: Type = null; + public flags = ASTFlags.Writeable; + + // REVIEW: for diagnostic purposes + public passCreated: number = CompilerDiagnostics.analysisPass; + + public preComments: Comment[] = null; + public postComments: Comment[] = null; + + public isParenthesized = false; + + constructor (public nodeType: NodeType) { + super(); + } + + public isExpression() { return false; } + + public isStatementOrExpression() { return false; } + + public isCompoundStatement() { return false; } + + public isLeaf() { return this.isStatementOrExpression() && (!this.isCompoundStatement()); } + + public typeCheck(typeFlow: TypeFlow) { + switch (this.nodeType) { + case NodeType.Error: + case NodeType.EmptyExpr: + this.type = typeFlow.anyType; + break; + case NodeType.This: + return typeFlow.typeCheckThis(this); + case NodeType.Null: + this.type = typeFlow.nullType; + break; + case NodeType.False: + case NodeType.True: + this.type = typeFlow.booleanType; + break; + case NodeType.Super: + return typeFlow.typeCheckSuper(this); + case NodeType.EndCode: + case NodeType.Empty: + case NodeType.Void: + this.type = typeFlow.voidType; + break; + default: + throw new Error("please implement in derived class"); + } + return this; + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + switch (this.nodeType) { + case NodeType.This: + emitter.recordSourceMappingStart(this); + if (emitter.thisFnc && (hasFlag(emitter.thisFnc.fncFlags, FncFlags.IsFatArrowFunction))) { + emitter.writeToOutput("_this"); + } + else { + emitter.writeToOutput("this"); + } + emitter.recordSourceMappingEnd(this); + break; + case NodeType.Null: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("null"); + emitter.recordSourceMappingEnd(this); + break; + case NodeType.False: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("false"); + emitter.recordSourceMappingEnd(this); + break; + case NodeType.True: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("true"); + emitter.recordSourceMappingEnd(this); + break; + case NodeType.Super: + emitter.recordSourceMappingStart(this); + emitter.emitSuperReference(); + emitter.recordSourceMappingEnd(this); + break; + case NodeType.EndCode: + break; + case NodeType.Error: + case NodeType.EmptyExpr: + break; + + case NodeType.Empty: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("; "); + emitter.recordSourceMappingEnd(this); + break; + case NodeType.Void: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("void "); + emitter.recordSourceMappingEnd(this); + break; + default: + throw new Error("please implement in derived class"); + } + emitter.emitParensAndCommentsInPlace(this, false); + } + + public print(context: PrintContext) { + context.startLine(); + var lineCol = { line: -1, col: -1 }; + var limLineCol = { line: -1, col: -1 }; + if (context.parser !== null) { + context.parser.getSourceLineCol(lineCol, this.minChar); + context.parser.getSourceLineCol(limLineCol, this.limChar); + context.write("(" + lineCol.line + "," + lineCol.col + ")--" + + "(" + limLineCol.line + "," + limLineCol.col + "): "); + } + var lab = this.printLabel(); + if (hasFlag(this.flags, ASTFlags.Error)) { + lab += " (Error)"; + } + context.writeLine(lab); + } + + public printLabel() { + if (nodeTypeTable[this.nodeType] !== undefined) { + return nodeTypeTable[this.nodeType]; + } + else { + return (NodeType)._map[this.nodeType]; + } + } + + public addToControlFlow(context: ControlFlowContext): void { + // by default, AST adds itself to current basic block and does not check its children + context.walker.options.goChildren = false; + context.addContent(this); + } + + public netFreeUses(container: Symbol, freeUses: StringHashTable) { + } + + public treeViewLabel() { + return (NodeType)._map[this.nodeType]; + } + + public static getResolvedIdentifierName(name: string): string { + if (!name) return ""; + + var resolved = ""; + var start = 0; + var i = 0; + while(i <= name.length - 6) { + // Look for escape sequence \uxxxx + if (name.charAt(i) == '\\' && name.charAt(i+1) == 'u') { + var charCode = parseInt(name.substr(i + 2, 4), 16); + resolved += name.substr(start, i - start); + resolved += String.fromCharCode(charCode); + i += 6; + start = i; + continue; + } + i++; + } + // Append remaining string + resolved += name.substring(start); + return resolved; + } + } + + export class IncompleteAST extends AST { + constructor (min: number, lim: number) { + super(NodeType.Error); + + this.minChar = min; + this.limChar = lim; + } + } + + export class ASTList extends AST { + public enclosingScope: SymbolScope = null; + public members: AST[] = new AST[]; + + constructor () { + super(NodeType.List); + } + + public addToControlFlow(context: ControlFlowContext) { + var len = this.members.length; + for (var i = 0; i < len; i++) { + if (context.noContinuation) { + context.addUnreachable(this.members[i]); + break; + } + else { + this.members[i] = context.walk(this.members[i], this); + } + } + context.walker.options.goChildren = false; + } + + public append(ast: AST) { + this.members[this.members.length] = ast; + return this; + } + + public appendAll(ast: AST) { + if (ast.nodeType == NodeType.List) { + var list = ast; + for (var i = 0, len = list.members.length; i < len; i++) { + this.append(list.members[i]); + } + } + else { + this.append(ast); + } + return this; + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.recordSourceMappingStart(this); + emitter.emitJavascriptList(this, null, TokenID.Semicolon, startLine, false, false); + emitter.recordSourceMappingEnd(this); + } + + public typeCheck(typeFlow: TypeFlow) { + var len = this.members.length; + typeFlow.nestingLevel++; + for (var i = 0; i < len; i++) { + if (this.members[i]) { + this.members[i] = this.members[i].typeCheck(typeFlow); + } + } + typeFlow.nestingLevel--; + return this; + } + } + + export class Identifier extends AST { + public sym: Symbol = null; + public cloId = -1; + public text: string; + + // 'actualText' is the text that the user has entered for the identifier. the text might + // include any Unicode escape sequences (e.g.: \u0041 for 'A'). 'text', however, contains + // the resolved value of any escape sequences in the actual text; so in the previous + // example, actualText = '\u0041', text = 'A'. + // + // For purposes of finding a symbol, use text, as this will allow you to match all + // variations of the variable text. For full-fidelity translation of the user input, such + // as emitting, use the actualText field. + // + // Note: + // To change text, and to avoid running into a situation where 'actualText' does not + // match 'text', always use setText. + constructor (public actualText: string, public hasEscapeSequence?: boolean) { + super(NodeType.Name); + this.setText(actualText, hasEscapeSequence); + } + + public setText(actualText: string, hasEscapeSequence?: boolean) { + this.actualText = actualText; + if (hasEscapeSequence) { + this.text = AST.getResolvedIdentifierName(actualText); + } + else { + this.text = actualText; + } + } + + public isMissing() { return false; } + public isLeaf() { return true; } + + public treeViewLabel() { + return "id: " + this.actualText; + } + + public printLabel() { + if (this.actualText) { + return "id: " + this.actualText; + } + else { + return "name node"; + } + } + + public typeCheck(typeFlow: TypeFlow) { + return typeFlow.typeCheckName(this); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitJavascriptName(this, true); + } + + public static fromToken(token: Token): Identifier { + return new Identifier(token.getText(), (token).hasEscapeSequence); + } + } + + export class MissingIdentifier extends Identifier { + constructor () { + super("__missing"); + } + + public isMissing() { + return true; + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + // Emit nothing for a missing ID + } + } + + export class Label extends AST { + constructor (public id: Identifier) { + super(NodeType.Label); + } + + public printLabel() { return this.id.actualText + ":"; } + + public typeCheck(typeFlow: TypeFlow) { + this.type = typeFlow.voidType; + return this; + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.recordSourceMappingStart(this.id); + emitter.writeToOutput(this.id.actualText); + emitter.recordSourceMappingEnd(this.id); + emitter.writeLineToOutput(":"); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + } + + export class Expression extends AST { + constructor (nodeType: NodeType) { + super(nodeType); + } + + public isExpression() { return true; } + + public isStatementOrExpression() { return true; } + } + + export class UnaryExpression extends Expression { + public targetType: Type = null; // Target type for an object literal (null if no target type) + public castTerm: AST = null; + + constructor (nodeType: NodeType, public operand: AST) { + super(nodeType); + } + + public addToControlFlow(context: ControlFlowContext): void { + super.addToControlFlow(context); + // TODO: add successor as catch block/finally block if present + if (this.nodeType == NodeType.Throw) { + context.returnStmt(); + } + } + + public typeCheck(typeFlow: TypeFlow) { + switch (this.nodeType) { + case NodeType.Not: + return typeFlow.typeCheckBitNot(this); + + case NodeType.LogNot: + return typeFlow.typeCheckLogNot(this); + + case NodeType.Pos: + case NodeType.Neg: + return typeFlow.typeCheckUnaryNumberOperator(this); + + case NodeType.IncPost: + case NodeType.IncPre: + case NodeType.DecPost: + case NodeType.DecPre: + return typeFlow.typeCheckIncOrDec(this); + + case NodeType.ArrayLit: + typeFlow.typeCheckArrayLit(this); + return this; + + case NodeType.ObjectLit: + typeFlow.typeCheckObjectLit(this); + return this; + + case NodeType.Throw: + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.voidType; + return this; + + case NodeType.Typeof: + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.stringType; + return this; + + case NodeType.Delete: + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.booleanType; + break; + + case NodeType.TypeAssertion: + this.castTerm = typeFlow.typeCheck(this.castTerm); + var applyTargetType = !this.operand.isParenthesized; + + var targetType = applyTargetType ? this.castTerm.type : null; + + typeFlow.checker.typeCheckWithContextualType(targetType, typeFlow.checker.inProvisionalTypecheckMode(), true, this.operand); + typeFlow.castWithCoercion(this.operand, this.castTerm.type, false, true); + this.type = this.castTerm.type; + return this; + + case NodeType.Void: + // REVIEW - Although this is good to do for completeness's sake, + // this shouldn't be strictly necessary from the void operator's + // point of view + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.checker.undefinedType; + break; + + default: + throw new Error("please implement in derived class"); + } + return this; + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + switch (this.nodeType) { + case NodeType.IncPost: + emitter.emitJavascript(this.operand, TokenID.PlusPlus, false); + emitter.writeToOutput("++"); + break; + case NodeType.LogNot: + emitter.writeToOutput("!"); + emitter.emitJavascript(this.operand, TokenID.Exclamation, false); + break; + case NodeType.DecPost: + emitter.emitJavascript(this.operand, TokenID.MinusMinus, false); + emitter.writeToOutput("--"); + break; + case NodeType.ObjectLit: + emitter.emitObjectLiteral(this.operand); + break; + case NodeType.ArrayLit: + emitter.emitArrayLiteral(this.operand); + break; + case NodeType.Not: + emitter.writeToOutput("~"); + emitter.emitJavascript(this.operand, TokenID.Tilde, false); + break; + case NodeType.Neg: + emitter.writeToOutput("-"); + if (this.operand.nodeType == NodeType.Neg) { + this.operand.isParenthesized = true; + } + emitter.emitJavascript(this.operand, TokenID.Minus, false); + break; + case NodeType.Pos: + emitter.writeToOutput("+"); + if (this.operand.nodeType == NodeType.Pos) { + this.operand.isParenthesized = true; + } + emitter.emitJavascript(this.operand, TokenID.Plus, false); + break; + case NodeType.IncPre: + emitter.writeToOutput("++"); + emitter.emitJavascript(this.operand, TokenID.PlusPlus, false); + break; + case NodeType.DecPre: + emitter.writeToOutput("--"); + emitter.emitJavascript(this.operand, TokenID.MinusMinus, false); + break; + case NodeType.Throw: + emitter.writeToOutput("throw "); + emitter.emitJavascript(this.operand, TokenID.Tilde, false); + emitter.writeToOutput(";"); + break; + case NodeType.Typeof: + emitter.writeToOutput("typeof "); + emitter.emitJavascript(this.operand, TokenID.Tilde, false); + break; + case NodeType.Delete: + emitter.writeToOutput("delete "); + emitter.emitJavascript(this.operand, TokenID.Tilde, false); + break; + case NodeType.Void: + emitter.writeToOutput("void "); + emitter.emitJavascript(this.operand, TokenID.Tilde, false); + break; + case NodeType.TypeAssertion: + emitter.emitJavascript(this.operand, TokenID.Tilde, false); + break; + default: + throw new Error("please implement in derived class"); + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + } + + export class CallExpression extends Expression { + constructor (nodeType: NodeType, + public target: AST, + public arguments: ASTList) { + super(nodeType); + this.minChar = this.target.minChar; + } + + public signature: Signature = null; + + public typeCheck(typeFlow: TypeFlow) { + if (this.nodeType == NodeType.New) { + return typeFlow.typeCheckNew(this); + } + else { + return typeFlow.typeCheckCall(this); + } + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + + if (this.nodeType == NodeType.New) { + emitter.emitNew(this.target, this.arguments); + } + else { + emitter.emitCall(this, this.target, this.arguments); + } + + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + } + + export class BinaryExpression extends Expression { + constructor (nodeType: NodeType, public operand1: AST, public operand2: AST) { + super(nodeType); + } + + public typeCheck(typeFlow: TypeFlow) { + switch (this.nodeType) { + case NodeType.Dot: + return typeFlow.typeCheckDotOperator(this); + case NodeType.Asg: + return typeFlow.typeCheckAsgOperator(this); + case NodeType.Add: + case NodeType.Sub: + case NodeType.Mul: + case NodeType.Div: + case NodeType.Mod: + case NodeType.Or: + case NodeType.And: + return typeFlow.typeCheckArithmeticOperator(this, false); + case NodeType.Xor: + return typeFlow.typeCheckBitwiseOperator(this, false); + case NodeType.Ne: + case NodeType.Eq: + var text: string; + if (typeFlow.checker.styleSettings.eqeqeq) { + text = nodeTypeTable[this.nodeType]; + typeFlow.checker.errorReporter.styleError(this, "use of " + text); + } + else if (typeFlow.checker.styleSettings.eqnull) { + text = nodeTypeTable[this.nodeType]; + if ((this.operand2 !== null) && (this.operand2.nodeType == NodeType.Null)) { + typeFlow.checker.errorReporter.styleError(this, "use of " + text + " to compare with null"); + } + } + case NodeType.Eqv: + case NodeType.NEqv: + case NodeType.Lt: + case NodeType.Le: + case NodeType.Ge: + case NodeType.Gt: + return typeFlow.typeCheckBooleanOperator(this); + case NodeType.Index: + return typeFlow.typeCheckIndex(this); + case NodeType.Member: + this.type = typeFlow.voidType; + return this; + case NodeType.LogOr: + return typeFlow.typeCheckLogOr(this); + case NodeType.LogAnd: + return typeFlow.typeCheckLogAnd(this); + case NodeType.AsgAdd: + case NodeType.AsgSub: + case NodeType.AsgMul: + case NodeType.AsgDiv: + case NodeType.AsgMod: + case NodeType.AsgOr: + case NodeType.AsgAnd: + return typeFlow.typeCheckArithmeticOperator(this, true); + case NodeType.AsgXor: + return typeFlow.typeCheckBitwiseOperator(this, true); + case NodeType.Lsh: + case NodeType.Rsh: + case NodeType.Rs2: + return typeFlow.typeCheckShift(this, false); + case NodeType.AsgLsh: + case NodeType.AsgRsh: + case NodeType.AsgRs2: + return typeFlow.typeCheckShift(this, true); + case NodeType.Comma: + return typeFlow.typeCheckCommaOperator(this); + case NodeType.InstOf: + return typeFlow.typeCheckInstOf(this); + case NodeType.In: + return typeFlow.typeCheckInOperator(this); + case NodeType.From: + typeFlow.checker.errorReporter.simpleError(this, "Illegal use of 'from' keyword in binary expression"); + break; + default: + throw new Error("please implement in derived class"); + } + return this; + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + var binTokenId = nodeTypeToTokTable[this.nodeType]; + + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if (binTokenId != undefined) { + + emitter.emitJavascript(this.operand1, binTokenId, false); + + if (tokenTable[binTokenId].text == "instanceof") { + emitter.writeToOutput(" instanceof "); + } + else if (tokenTable[binTokenId].text == "in") { + emitter.writeToOutput(" in "); + } + else { + emitter.writeToOutputTrimmable(" " + tokenTable[binTokenId].text + " "); + } + + emitter.emitJavascript(this.operand2, binTokenId, false); + } + else { + switch (this.nodeType) { + case NodeType.Dot: + if (!emitter.tryEmitConstant(this)) { + emitter.emitJavascript(this.operand1, TokenID.Dot, false); + emitter.writeToOutput("."); + emitter.emitJavascriptName(this.operand2, false); + } + break; + case NodeType.Index: + emitter.emitIndex(this.operand1, this.operand2); + break; + + case NodeType.Member: + if (this.operand2.nodeType == NodeType.FuncDecl && (this.operand2).isAccessor()) { + var funcDecl = this.operand2; + if (hasFlag(funcDecl.fncFlags, FncFlags.GetAccessor)) { + emitter.writeToOutput("get "); + } + else { + emitter.writeToOutput("set "); + } + emitter.emitJavascript(this.operand1, TokenID.Colon, false); + } + else { + emitter.emitJavascript(this.operand1, TokenID.Colon, false); + emitter.writeToOutputTrimmable(": "); + } + emitter.emitJavascript(this.operand2, TokenID.Comma, false); + break; + case NodeType.Comma: + emitter.emitJavascript(this.operand1, TokenID.Comma, false); + if (emitter.emitState.inObjectLiteral) { + emitter.writeLineToOutput(", "); + } + else { + emitter.writeToOutput(","); + } + emitter.emitJavascript(this.operand2, TokenID.Comma, false); + break; + case NodeType.Is: + throw new Error("should be de-sugared during type check"); + default: + throw new Error("please implement in derived class"); + } + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + } + + export class ConditionalExpression extends Expression { + constructor (public operand1: AST, + public operand2: AST, + public operand3: AST) { + super(NodeType.ConditionalExpression); + } + + public typeCheck(typeFlow: TypeFlow) { + return typeFlow.typeCheckQMark(this); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.operand1, TokenID.Question, false); + emitter.writeToOutput(" ? "); + emitter.emitJavascript(this.operand2, TokenID.Question, false); + emitter.writeToOutput(" : "); + emitter.emitJavascript(this.operand3, TokenID.Question, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + } + + export class NumberLiteral extends Expression { + constructor (public value: number, public hasEmptyFraction?: boolean) { + super(NodeType.NumberLit); + } + + public isNegativeZero = false; + + public typeCheck(typeFlow: TypeFlow) { + this.type = typeFlow.doubleType; + return this; + } + + public treeViewLabel() { + return "num: " + this.printLabel(); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if (this.isNegativeZero) { + emitter.writeToOutput("-"); + } + + emitter.writeToOutput(this.value.toString()); + + if (this.hasEmptyFraction) + emitter.writeToOutput(".0"); + + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + + public printLabel() { + if (Math.floor(this.value) != this.value) { + return this.value.toFixed(2).toString(); + } + else if (this.hasEmptyFraction) { + return this.value.toString() + ".0"; + } + else { + return this.value.toString(); + } + } + } + + export class RegexLiteral extends Expression { + constructor (public regex) { + super(NodeType.Regex); + } + + public typeCheck(typeFlow: TypeFlow) { + this.type = typeFlow.regexType; + return this; + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(this.regex.toString()); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + } + + export class StringLiteral extends Expression { + constructor (public text: string) { + super(NodeType.QString); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitStringLiteral(this.text); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + + public typeCheck(typeFlow: TypeFlow) { + this.type = typeFlow.stringType; + return this; + } + + public treeViewLabel() { + return "st: " + this.text; + } + + public printLabel() { + return this.text; + } + } + + export class ModuleElement extends AST { + constructor (nodeType: NodeType) { + super(nodeType); + } + } + + export class ImportDeclaration extends ModuleElement { + public isStatementOrExpression() { return true; } + public varFlags = VarFlags.None; + public isDynamicImport = false; + + constructor (public id: Identifier, public alias: AST) { + super(NodeType.ImportDeclaration); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + var mod = this.alias.type; + // REVIEW: Only modules may be aliased for now, though there's no real + // restriction on what the type symbol may be + if (!this.isDynamicImport || (this.id.sym && !(this.id.sym).onlyReferencedAsTypeRef)) { + var prevModAliasId = emitter.modAliasId; + var prevFirstModAlias = emitter.firstModAlias; + + emitter.recordSourceMappingStart(this); + emitter.emitParensAndCommentsInPlace(this, true); + emitter.writeToOutput("var " + this.id.actualText + " = "); + emitter.modAliasId = this.id.actualText; + emitter.firstModAlias = this.firstAliasedModToString(); + emitter.emitJavascript(this.alias, TokenID.Tilde, false); + // the dynamic import case will insert the semi-colon automatically + if (!this.isDynamicImport) { + emitter.writeToOutput(";"); + } + emitter.emitParensAndCommentsInPlace(this, false); + emitter.recordSourceMappingEnd(this); + + emitter.modAliasId = prevModAliasId; + emitter.firstModAlias = prevFirstModAlias; + } + } + + public typeCheck(typeFlow: TypeFlow) { + return typeFlow.typeCheckImportDecl(this); + } + + public getAliasName(aliasAST?: AST = this.alias) : string { + if (aliasAST.nodeType == NodeType.Name) { + return (aliasAST).actualText; + } else { + var dotExpr = aliasAST; + return this.getAliasName(dotExpr.operand1) + "." + this.getAliasName(dotExpr.operand2); + } + } + + public firstAliasedModToString() { + if (this.alias.nodeType == NodeType.Name) { + return (this.alias).actualText; + } + else { + var dotExpr = this.alias; + var firstMod = dotExpr.operand1; + return firstMod.actualText; + } + } + } + + export class BoundDecl extends AST { + public init: AST = null; + public typeExpr: AST = null; + public varFlags = VarFlags.None; + public sym: Symbol = null; + + constructor (public id: Identifier, nodeType: NodeType, public nestingLevel: number) { + super(nodeType); + } + + public isStatementOrExpression() { return true; } + + public isPrivate() { return hasFlag(this.varFlags, VarFlags.Private); } + public isPublic() { return hasFlag(this.varFlags, VarFlags.Public); } + public isProperty() { return hasFlag(this.varFlags, VarFlags.Property); } + + public typeCheck(typeFlow: TypeFlow) { + return typeFlow.typeCheckBoundDecl(this); + } + + public printLabel() { + return this.treeViewLabel(); + } + } + + export class VarDecl extends BoundDecl { + constructor (id: Identifier, nest: number) { + super(id, NodeType.VarDecl, nest); + } + + public isAmbient() { return hasFlag(this.varFlags, VarFlags.Ambient); } + public isExported() { return hasFlag(this.varFlags, VarFlags.Exported); } + public isStatic() { return hasFlag(this.varFlags, VarFlags.Static); } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitJavascriptVarDecl(this, tokenId); + } + + public treeViewLabel() { + return "var " + this.id.actualText; + } + } + + export class ArgDecl extends BoundDecl { + constructor (id: Identifier) { + super(id, NodeType.ArgDecl, 0); + } + + public isOptional = false; + + public isOptionalArg() { return this.isOptional || this.init; } + + public treeViewLabel() { + return "arg: " + this.id.actualText; + } + + public parameterPropertySym: FieldSymbol = null; + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(this.id.actualText); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + } + + var internalId = 0; + + export class FuncDecl extends AST { + public hint: string = null; + public fncFlags = FncFlags.None; + public returnTypeAnnotation: AST = null; + public symbols: IHashTable; + public variableArgList = false; + public signature: Signature; + public envids: Identifier[]; + public jumpRefs: Identifier[] = null; + public internalNameCache: string = null; + public tmp1Declared = false; + public enclosingFnc: FuncDecl = null; + public freeVariables: Symbol[] = []; + public unitIndex = -1; + public classDecl: NamedDeclaration = null; + public boundToProperty: VarDecl = null; + public isOverload = false; + public innerStaticFuncs: FuncDecl[] = []; + public isTargetTypedAsMethod = false; + public isInlineCallLiteral = false; + public accessorSymbol: Symbol = null; + public leftCurlyCount = 0; + public rightCurlyCount = 0; + public returnStatementsWithExpressions: ReturnStatement[] = []; + public scopeType: Type = null; // Type of the FuncDecl, before target typing + public endingToken: ASTSpan = null; + + constructor (public name: Identifier, public bod: ASTList, public isConstructor: boolean, + public arguments: ASTList, public vars: ASTList, public scopes: ASTList, public statics: ASTList, + nodeType: number) { + + super(nodeType); + } + + public internalName(): string { + if (this.internalNameCache == null) { + var extName = this.getNameText(); + if (extName) { + this.internalNameCache = "_internal_" + extName; + } + else { + this.internalNameCache = "_internal_" + internalId++; + } + } + return this.internalNameCache; + } + + public hasSelfReference() { return hasFlag(this.fncFlags, FncFlags.HasSelfReference); } + public setHasSelfReference() { this.fncFlags |= FncFlags.HasSelfReference; } + + public addCloRef(id: Identifier, sym: Symbol): number { + if (this.envids == null) { + this.envids = new Identifier[]; + } + this.envids[this.envids.length] = id; + var outerFnc = this.enclosingFnc; + if (sym) { + while (outerFnc && (outerFnc.type.symbol != sym.container)) { + outerFnc.addJumpRef(sym); + outerFnc = outerFnc.enclosingFnc; + } + } + return this.envids.length - 1; + } + + public addJumpRef(sym: Symbol): void { + if (this.jumpRefs == null) { + this.jumpRefs = new Identifier[]; + } + var id = new Identifier(sym.name); + this.jumpRefs[this.jumpRefs.length] = id; + id.sym = sym; + id.cloId = this.addCloRef(id, null); + } + + public buildControlFlow(): ControlFlowContext { + var entry = new BasicBlock(); + var exit = new BasicBlock(); + + var context = new ControlFlowContext(entry, exit); + + var controlFlowPrefix = (ast: AST, parent: AST, walker: IAstWalker) => { + ast.addToControlFlow(walker.state); + return ast; + } + + var walker = getAstWalkerFactory().getWalker(controlFlowPrefix, null, null, context); + context.walker = walker; + walker.walk(this.bod, this); + + return context; + } + + public typeCheck(typeFlow: TypeFlow) { + return typeFlow.typeCheckFunction(this); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitJavascriptFunction(this); + } + + public getNameText() { + if (this.name) { + return this.name.actualText; + } + else { + return this.hint; + } + } + + public isMethod() { + return (this.fncFlags & FncFlags.Method) != FncFlags.None; + } + + public isCallMember() { return hasFlag(this.fncFlags, FncFlags.CallMember); } + public isConstructMember() { return hasFlag(this.fncFlags, FncFlags.ConstructMember); } + public isIndexerMember() { return hasFlag(this.fncFlags, FncFlags.IndexerMember); } + public isSpecialFn() { return this.isCallMember() || this.isIndexerMember() || this.isConstructMember(); } + public isAnonymousFn() { return this.name === null; } + public isAccessor() { return hasFlag(this.fncFlags, FncFlags.GetAccessor) || hasFlag(this.fncFlags, FncFlags.SetAccessor); } + public isGetAccessor() { return hasFlag(this.fncFlags, FncFlags.GetAccessor); } + public isSetAccessor() { return hasFlag(this.fncFlags, FncFlags.SetAccessor); } + public isAmbient() { return hasFlag(this.fncFlags, FncFlags.Ambient); } + public isExported() { return hasFlag(this.fncFlags, FncFlags.Exported); } + public isPrivate() { return hasFlag(this.fncFlags, FncFlags.Private); } + public isPublic() { return hasFlag(this.fncFlags, FncFlags.Public); } + public isStatic() { return hasFlag(this.fncFlags, FncFlags.Static); } + + public treeViewLabel() { + if (this.name == null) { + return "funcExpr"; + } + else { + return "func: " + this.name.actualText + } + } + + public ClearFlags(): void { + this.fncFlags = FncFlags.None; + } + + public isSignature() { return (this.fncFlags & FncFlags.Signature) != FncFlags.None; } + + public hasStaticDeclarations() { return (!this.isConstructor && (this.statics.members.length > 0 || this.innerStaticFuncs.length > 0)); } + } + + export class LocationInfo { + constructor (public filename: string, public lineMap: number[], public unitIndex) { } + } + + export var unknownLocationInfo = new LocationInfo("unknown", null, -1); + + export class Script extends FuncDecl { + public locationInfo: LocationInfo = null; + public referencedFiles: IFileReference[] = []; + public requiresGlobal = false; + public requiresInherits = false; + public isResident = false; + public isDeclareFile = false; + public hasBeenTypeChecked = false; + public topLevelMod: ModuleDeclaration = null; + public leftCurlyCount = 0; + public rightCurlyCount = 0; + public vars: ASTList; + public scopes: ASTList; + // Remember if the script contains Unicode chars, that is needed when generating code for this script object to decide the output file correct encoding. + public containsUnicodeChar = false; + public containsUnicodeCharInComment = false; + + constructor (vars: ASTList, scopes: ASTList) { + super(new Identifier("script"), null, false, null, vars, scopes, null, NodeType.Script); + this.vars = vars; + this.scopes = scopes; + } + + public typeCheck(typeFlow: TypeFlow) { + return typeFlow.typeCheckScript(this); + } + + public treeViewLabel() { + return "Script"; + } + + public emitRequired() { + if (!this.isDeclareFile && !this.isResident && this.bod) { + for (var i = 0, len = this.bod.members.length; i < len; i++) { + var stmt = this.bod.members[i]; + if (stmt.nodeType == NodeType.ModuleDeclaration) { + if (!hasFlag((stmt).modFlags, ModuleFlags.ShouldEmitModuleDecl | ModuleFlags.Ambient)) { + return true; + } + } + else if (stmt.nodeType == NodeType.ClassDeclaration) { + if (!hasFlag((stmt).varFlags, VarFlags.Ambient)) { + return true; + } + } + else if (stmt.nodeType == NodeType.VarDecl) { + if (!hasFlag((stmt).varFlags, VarFlags.Ambient)) { + return true; + } + } + else if (stmt.nodeType == NodeType.FuncDecl) { + if (!(stmt).isSignature()) { + return true; + } + } + else if (stmt.nodeType != NodeType.InterfaceDeclaration && stmt.nodeType != NodeType.Empty) { + return true; + } + } + } + return false; + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + if (this.emitRequired()) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascriptList(this.bod, null, TokenID.Semicolon, true, false, false, true, this.requiresInherits); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + } + } + + export class NamedDeclaration extends ModuleElement { + public leftCurlyCount = 0; + public rightCurlyCount = 0; + + constructor (nodeType: NodeType, + public name: Identifier, + public members: ASTList) { + super(nodeType); + } + } + + export class ModuleDeclaration extends NamedDeclaration { + public modFlags = ModuleFlags.ShouldEmitModuleDecl; + public mod: ModuleType; + public prettyName: string; + public amdDependencies: string[] = []; + public vars: ASTList; + public scopes: ASTList; + // Remember if the module contains Unicode chars, that is needed for dynamic module as we will generate a file for each. + public containsUnicodeChar = false; + public containsUnicodeCharInComment = false; + + constructor (name: Identifier, members: ASTList, vars: ASTList, scopes: ASTList, public endingToken: ASTSpan) { + super(NodeType.ModuleDeclaration, name, members); + + this.vars = vars; + this.scopes = scopes; + this.prettyName = this.name.actualText; + } + + public isExported() { return hasFlag(this.modFlags, ModuleFlags.Exported); } + public isAmbient() { return hasFlag(this.modFlags, ModuleFlags.Ambient); } + public isEnum() { return hasFlag(this.modFlags, ModuleFlags.IsEnum); } + + public recordNonInterface() { + this.modFlags &= ~ModuleFlags.ShouldEmitModuleDecl; + } + + public typeCheck(typeFlow: TypeFlow) { + return typeFlow.typeCheckModule(this); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + if (!hasFlag(this.modFlags, ModuleFlags.ShouldEmitModuleDecl)) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascriptModule(this); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + } + } + + export class TypeDeclaration extends NamedDeclaration { + public varFlags = VarFlags.None; + + constructor (nodeType: NodeType, + name: Identifier, + public extendsList: ASTList, + public implementsList: ASTList, + members: ASTList) { + super(nodeType, name, members); + } + + public isExported() { + return hasFlag(this.varFlags, VarFlags.Exported); + } + + public isAmbient() { + return hasFlag(this.varFlags, VarFlags.Ambient); + } + } + + export class ClassDeclaration extends TypeDeclaration { + public knownMemberNames: any = {}; + public constructorDecl: FuncDecl = null; + public constructorNestingLevel = 0; + public endingToken: ASTSpan = null; + + constructor (name: Identifier, + members: ASTList, + extendsList: ASTList, + implementsList: ASTList) { + super(NodeType.ClassDeclaration, name, extendsList, implementsList, members); + } + + public typeCheck(typeFlow: TypeFlow) { + return typeFlow.typeCheckClass(this); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitJavascriptClass(this); + } + } + + export class InterfaceDeclaration extends TypeDeclaration { + constructor (name: Identifier, + members: ASTList, + extendsList: ASTList, + implementsList: ASTList) { + super(NodeType.InterfaceDeclaration, name, extendsList, implementsList, members); + } + + public typeCheck(typeFlow: TypeFlow) { + return typeFlow.typeCheckInterface(this); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + } + } + + export class Statement extends ModuleElement { + constructor (nodeType: NodeType) { + super(nodeType); + this.flags |= ASTFlags.IsStatement; + } + + public isLoop() { return false; } + + public isStatementOrExpression() { return true; } + + public isCompoundStatement() { return this.isLoop(); } + + public typeCheck(typeFlow: TypeFlow) { + this.type = typeFlow.voidType; + return this; + } + } + + export class LabeledStatement extends Statement { + constructor (public labels: ASTList, public stmt: AST) { + super(NodeType.LabeledStatement); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if (this.labels) { + var labelsLen = this.labels.members.length; + for (var i = 0; i < labelsLen; i++) { + this.labels.members[i].emit(emitter, tokenId, startLine); + } + } + this.stmt.emit(emitter, tokenId, true); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + + public typeCheck(typeFlow: TypeFlow) { + typeFlow.typeCheck(this.labels); + this.stmt = this.stmt.typeCheck(typeFlow); + return this; + } + + public addToControlFlow(context: ControlFlowContext): void { + var beforeBB = context.current; + var bb = new BasicBlock(); + context.current = bb; + beforeBB.addSuccessor(bb); + } + } + + export class Block extends Statement { + constructor (public statements: ASTList, + public isStatementBlock: boolean) { + super(NodeType.Block); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if (this.isStatementBlock) { + emitter.writeLineToOutput(" {"); + emitter.indenter.increaseIndent(); + } else { + emitter.setInVarBlock(this.statements.members.length); + } + var temp = emitter.setInObjectLiteral(false); + if (this.statements) { + emitter.emitJavascriptList(this.statements, null, TokenID.Semicolon, true, false, false); + } + if (this.isStatementBlock) { + emitter.indenter.decreaseIndent(); + emitter.emitIndent(); + emitter.writeToOutput("}"); + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + + public addToControlFlow(context: ControlFlowContext) { + var afterIfNeeded = new BasicBlock(); + context.pushStatement(this, context.current, afterIfNeeded); + if (this.statements) { + context.walk(this.statements, this); + } + context.walker.options.goChildren = false; + context.popStatement(); + if (afterIfNeeded.predecessors.length > 0) { + context.current.addSuccessor(afterIfNeeded); + context.current = afterIfNeeded; + } + } + + public typeCheck(typeFlow: TypeFlow) { + if (!typeFlow.checker.styleSettings.emptyBlocks) { + if ((this.statements === null) || (this.statements.members.length == 0)) { + typeFlow.checker.errorReporter.styleError(this, "empty block"); + } + } + + typeFlow.typeCheck(this.statements); + return this; + } + } + + export class Jump extends Statement { + public target: string = null; + public hasExplicitTarget() { return (this.target); } + public resolvedTarget: Statement = null; + + constructor (nodeType: NodeType) { + super(nodeType); + } + + public setResolvedTarget(parser: Parser, stmt: Statement): boolean { + if (stmt.isLoop()) { + this.resolvedTarget = stmt; + return true; + } + if (this.nodeType === NodeType.Continue) { + parser.reportParseError("continue statement applies only to loops"); + return false; + } + else { + if ((stmt.nodeType == NodeType.Switch) || this.hasExplicitTarget()) { + this.resolvedTarget = stmt; + return true; + } + else { + parser.reportParseError("break statement with no label can apply only to a loop or switch statement"); + return false; + } + } + } + + public addToControlFlow(context: ControlFlowContext): void { + super.addToControlFlow(context); + context.unconditionalBranch(this.resolvedTarget, (this.nodeType == NodeType.Continue)); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if (this.nodeType == NodeType.Break) { + emitter.writeToOutput("break"); + } + else { + emitter.writeToOutput("continue"); + } + if (this.hasExplicitTarget()) { + emitter.writeToOutput(" " + this.target); + } + emitter.recordSourceMappingEnd(this); + emitter.writeToOutput(";"); + emitter.emitParensAndCommentsInPlace(this, false); + } + } + + export class WhileStatement extends Statement { + public body: AST = null; + + constructor (public cond: AST) { + super(NodeType.While); + } + + public isLoop() { return true; } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("while("); + emitter.emitJavascript(this.cond, TokenID.While, false); + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, false, false); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + + public typeCheck(typeFlow: TypeFlow) { + return typeFlow.typeCheckWhile(this); + } + + public addToControlFlow(context: ControlFlowContext): void { + var loopHeader = context.current; + var loopStart = new BasicBlock(); + var afterLoop = new BasicBlock(); + + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + context.addContent(this.cond); + var condBlock = context.current; + var targetInfo: ITargetInfo = null; + if (this.body) { + context.current = new BasicBlock(); + condBlock.addSuccessor(context.current); + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if (!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + } + context.current = afterLoop; + condBlock.addSuccessor(afterLoop); + // TODO: check for while (true) and then only continue if afterLoop has predecessors + context.noContinuation = false; + context.walker.options.goChildren = false; + } + } + + export class DoWhileStatement extends Statement { + public body: AST = null; + public whileAST: AST = null; + public cond: AST = null; + public isLoop() { return true; } + + constructor () { + super(NodeType.DoWhile); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("do"); + emitter.emitJavascriptStatements(this.body, true, false); + emitter.recordSourceMappingStart(this.whileAST); + emitter.writeToOutput("while"); + emitter.recordSourceMappingEnd(this.whileAST); + emitter.writeToOutput('('); + emitter.emitJavascript(this.cond, TokenID.CloseParen, false); + emitter.writeToOutput(")"); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + + public typeCheck(typeFlow: TypeFlow) { + return typeFlow.typeCheckDoWhile(this); + } + + public addToControlFlow(context: ControlFlowContext): void { + var loopHeader = context.current; + var loopStart = new BasicBlock(); + var afterLoop = new BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + var targetInfo: ITargetInfo = null; + if (this.body) { + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if (!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + context.addContent(this.cond); + // TODO: check for while (true) + context.current = afterLoop; + loopEnd.addSuccessor(afterLoop); + } + else { + context.addUnreachable(this.cond); + } + context.walker.options.goChildren = false; + } + } + + export class IfStatement extends Statement { + public thenBod: AST; + public elseBod: AST = null; + public statement: ASTSpan = new ASTSpan(); + + constructor (public cond: AST) { + super(NodeType.If); + } + + public isCompoundStatement() { return true; } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("if("); + emitter.emitJavascript(this.cond, TokenID.If, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascriptStatements(this.thenBod, true, false); + if (this.elseBod) { + emitter.writeToOutput(" else"); + emitter.emitJavascriptStatements(this.elseBod, true, true); + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + + public typeCheck(typeFlow: TypeFlow) { + return typeFlow.typeCheckIf(this); + } + + public addToControlFlow(context: ControlFlowContext): void { + this.cond.addToControlFlow(context); + var afterIf = new BasicBlock(); + var beforeIf = context.current; + context.pushStatement(this, beforeIf, afterIf); + var hasContinuation = false; + context.current = new BasicBlock(); + beforeIf.addSuccessor(context.current); + context.walk(this.thenBod, this); + if (!context.noContinuation) { + hasContinuation = true; + context.current.addSuccessor(afterIf); + } + if (this.elseBod) { + // current block will be thenBod + context.current = new BasicBlock(); + context.noContinuation = false; + beforeIf.addSuccessor(context.current); + context.walk(this.elseBod, this); + if (!context.noContinuation) { + hasContinuation = true; + context.current.addSuccessor(afterIf); + } + else { + // thenBod created continuation for if statement + if (hasContinuation) { + context.noContinuation = false; + } + } + } + else { + beforeIf.addSuccessor(afterIf); + context.noContinuation = false; + hasContinuation = true; + } + var targetInfo = context.popStatement(); + if (afterIf.predecessors.length > 0) { + context.noContinuation = false; + hasContinuation = true; + } + if (hasContinuation) { + context.current = afterIf; + } + context.walker.options.goChildren = false; + } + } + + export class ReturnStatement extends Statement { + public returnExpression: AST = null; + + constructor () { + super(NodeType.Return); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + if (this.returnExpression) { + emitter.writeToOutput("return "); + emitter.emitJavascript(this.returnExpression, TokenID.Semicolon, false); + } + else { + emitter.writeToOutput("return;"); + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + + public addToControlFlow(context: ControlFlowContext): void { + super.addToControlFlow(context); + context.returnStmt(); + } + + public typeCheck(typeFlow: TypeFlow) { + return typeFlow.typeCheckReturn(this); + } + } + + export class EndCode extends AST { + constructor () { + super(NodeType.EndCode); + } + } + + export class ForInStatement extends Statement { + constructor (public lval: AST, public obj: AST) { + super(NodeType.ForIn); + if (this.lval && (this.lval.nodeType == NodeType.VarDecl)) { + (this.lval).varFlags |= VarFlags.AutoInit; + } + } + public statement: ASTSpan = new ASTSpan(); + public body: AST; + + public isLoop() { return true; } + + public isFiltered() { + if (this.body) { + var singleItem: AST = null; + if (this.body.nodeType == NodeType.List) { + var stmts = this.body; + if (stmts.members.length == 1) { + singleItem = stmts.members[0]; + } + } + else { + singleItem = this.body; + } + // match template for filtering 'own' properties from obj + if (singleItem !== null) { + if (singleItem.nodeType == NodeType.Block) { + var block = singleItem; + if ((block.statements !== null) && (block.statements.members.length == 1)) { + singleItem = block.statements.members[0]; + } + } + if (singleItem.nodeType == NodeType.If) { + var cond = (singleItem).cond; + if (cond.nodeType == NodeType.Call) { + var target = (cond).target; + if (target.nodeType == NodeType.Dot) { + var binex = target; + if ((binex.operand1.nodeType == NodeType.Name) && + (this.obj.nodeType == NodeType.Name) && + ((binex.operand1).actualText == (this.obj).actualText)) { + var prop = binex.operand2; + if (prop.actualText == "hasOwnProperty") { + var args = (cond).arguments; + if ((args !== null) && (args.members.length == 1)) { + var arg = args.members[0]; + if ((arg.nodeType == NodeType.Name) && + (this.lval.nodeType == NodeType.Name)) { + if (((this.lval).actualText) == (arg).actualText) { + return true; + } + } + } + } + } + } + } + } + } + } + return false; + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("for("); + emitter.emitJavascript(this.lval, TokenID.For, false); + emitter.writeToOutput(" in "); + emitter.emitJavascript(this.obj, TokenID.For, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascriptStatements(this.body, true, false); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + + public typeCheck(typeFlow: TypeFlow) { + if (typeFlow.checker.styleSettings.forin) { + if (!this.isFiltered()) { + typeFlow.checker.errorReporter.styleError(this, "no hasOwnProperty filter"); + } + } + return typeFlow.typeCheckForIn(this); + } + + public addToControlFlow(context: ControlFlowContext): void { + if (this.lval) { + context.addContent(this.lval); + } + if (this.obj) { + context.addContent(this.obj); + } + + var loopHeader = context.current; + var loopStart = new BasicBlock(); + var afterLoop = new BasicBlock(); + + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + if (this.body) { + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + context.popStatement(); + } + if (!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + } + context.current = afterLoop; + context.noContinuation = false; + loopHeader.addSuccessor(afterLoop); + context.walker.options.goChildren = false; + } + } + + export class ForStatement extends Statement { + public cond: AST; + public body: AST; + public incr: AST; + + constructor (public init: AST) { + super(NodeType.For); + } + + public isLoop() { return true; } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("for("); + if (this.init) { + if (this.init.nodeType != NodeType.List) { + emitter.emitJavascript(this.init, TokenID.For, false); + } + else { + emitter.setInVarBlock((this.init).members.length); + emitter.emitJavascriptList(this.init, null, TokenID.For, false, false, false); + } + } + emitter.writeToOutput("; "); + emitter.emitJavascript(this.cond, TokenID.For, false); + emitter.writeToOutput("; "); + emitter.emitJavascript(this.incr, TokenID.For, false); + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, true, false); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + + public typeCheck(typeFlow: TypeFlow) { + return typeFlow.typeCheckFor(this); + } + + public addToControlFlow(context: ControlFlowContext): void { + if (this.init) { + context.addContent(this.init); + } + var loopHeader = context.current; + var loopStart = new BasicBlock(); + var afterLoop = new BasicBlock(); + + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + var condBlock: BasicBlock = null; + var continueTarget = loopStart; + var incrBB: BasicBlock = null; + if (this.incr) { + incrBB = new BasicBlock(); + continueTarget = incrBB; + } + if (this.cond) { + condBlock = context.current; + context.addContent(this.cond); + context.current = new BasicBlock(); + condBlock.addSuccessor(context.current); + } + var targetInfo: ITargetInfo = null; + if (this.body) { + context.pushStatement(this, continueTarget, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if (this.incr) { + if (context.noContinuation) { + if (incrBB.predecessors.length == 0) { + context.addUnreachable(this.incr); + } + } + else { + context.current.addSuccessor(incrBB); + context.current = incrBB; + context.addContent(this.incr); + } + } + var loopEnd = context.current; + if (!(context.noContinuation)) { + loopEnd.addSuccessor(loopStart); + + } + if (condBlock) { + condBlock.addSuccessor(afterLoop); + context.noContinuation = false; + } + if (afterLoop.predecessors.length > 0) { + context.noContinuation = false; + context.current = afterLoop; + } + context.walker.options.goChildren = false; + } + } + + export class WithStatement extends Statement { + public body: AST; + + public isCompoundStatement() { return true; } + + public withSym: WithSymbol = null; + + constructor (public expr: AST) { + super(NodeType.With); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("with ("); + if (this.expr) { + emitter.emitJavascript(this.expr, TokenID.With, false); + } + + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, true, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + + public typeCheck(typeFlow: TypeFlow) { + return typeFlow.typeCheckWith(this); + } + } + + export class SwitchStatement extends Statement { + public caseList: ASTList; + public defaultCase: CaseStatement = null; + public statement: ASTSpan = new ASTSpan(); + + constructor (public val: AST) { + super(NodeType.Switch); + } + + public isCompoundStatement() { return true; } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("switch("); + emitter.emitJavascript(this.val, TokenID.Identifier, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.writeLineToOutput(" {"); + emitter.indenter.increaseIndent(); + var casesLen = this.caseList.members.length; + for (var i = 0; i < casesLen; i++) { + var caseExpr = this.caseList.members[i]; + emitter.emitJavascript(caseExpr, TokenID.Case, true); + emitter.writeLineToOutput(""); + } + emitter.indenter.decreaseIndent(); + emitter.emitIndent(); + emitter.writeToOutput("}"); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + + public typeCheck(typeFlow: TypeFlow) { + var len = this.caseList.members.length; + this.val = typeFlow.typeCheck(this.val); + for (var i = 0; i < len; i++) { + this.caseList.members[i] = typeFlow.typeCheck(this.caseList.members[i]); + } + this.defaultCase = typeFlow.typeCheck(this.defaultCase); + this.type = typeFlow.voidType; + return this; + } + + // if there are break statements that match this switch, then just link cond block with block after switch + public addToControlFlow(context: ControlFlowContext) { + var condBlock = context.current; + context.addContent(this.val); + var execBlock = new BasicBlock(); + var afterSwitch = new BasicBlock(); + + condBlock.addSuccessor(execBlock); + context.pushSwitch(execBlock); + context.current = execBlock; + context.pushStatement(this, execBlock, afterSwitch); + context.walk(this.caseList, this); + context.popSwitch(); + var targetInfo = context.popStatement(); + var hasCondContinuation = (this.defaultCase == null); + if (this.defaultCase == null) { + condBlock.addSuccessor(afterSwitch); + } + if (afterSwitch.predecessors.length > 0) { + context.noContinuation = false; + context.current = afterSwitch; + } + else { + context.noContinuation = true; + } + context.walker.options.goChildren = false; + } + } + + export class CaseStatement extends Statement { + public expr: AST = null; + public body: ASTList; + + constructor () { + super(NodeType.Case); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if (this.expr) { + emitter.writeToOutput("case "); + emitter.emitJavascript(this.expr, TokenID.Identifier, false); + } + else { + emitter.writeToOutput("default"); + } + emitter.writeToOutput(":"); + emitter.emitJavascriptStatements(this.body, false, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + + public typeCheck(typeFlow: TypeFlow) { + this.expr = typeFlow.typeCheck(this.expr); + typeFlow.typeCheck(this.body); + this.type = typeFlow.voidType; + return this; + } + + // TODO: more reasoning about unreachable cases (such as duplicate literals as case expressions) + // for now, assume all cases are reachable, regardless of whether some cases fall through + public addToControlFlow(context: ControlFlowContext) { + var execBlock = new BasicBlock(); + var sw = context.currentSwitch[context.currentSwitch.length - 1]; + // TODO: fall-through from previous (+ to end of switch) + if (this.expr) { + var exprBlock = new BasicBlock(); + context.current = exprBlock; + sw.addSuccessor(exprBlock); + context.addContent(this.expr); + exprBlock.addSuccessor(execBlock); + } + else { + sw.addSuccessor(execBlock); + } + context.current = execBlock; + if (this.body) { + context.walk(this.body, this); + } + context.noContinuation = false; + context.walker.options.goChildren = false; + } + } + + export class TypeReference extends AST { + constructor (public term: AST, public arrayCount: number) { + super(NodeType.TypeRef); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + throw new Error("should not emit a type ref"); + } + + public typeCheck(typeFlow: TypeFlow) { + var prevInTCTR = typeFlow.inTypeRefTypeCheck; + typeFlow.inTypeRefTypeCheck = true; + var typeLink = getTypeLink(this, typeFlow.checker, true); + typeFlow.checker.resolveTypeLink(typeFlow.scope, typeLink, false); + + if (this.term) { + typeFlow.typeCheck(this.term); + } + + typeFlow.checkForVoidConstructor(typeLink.type, this); + + this.type = typeLink.type; + + // in error recovery cases, there may not be a term + if (this.term) { + this.term.type = this.type; + } + + typeFlow.inTypeRefTypeCheck = prevInTCTR; + return this; + } + } + + export class TryFinally extends Statement { + constructor (public tryNode: AST, public finallyNode: Finally) { + super(NodeType.TryFinally); + } + + public isCompoundStatement() { return true; } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.tryNode, TokenID.Try, false); + emitter.emitJavascript(this.finallyNode, TokenID.Finally, false); + emitter.recordSourceMappingEnd(this); + } + + public typeCheck(typeFlow: TypeFlow) { + this.tryNode = typeFlow.typeCheck(this.tryNode); + this.finallyNode = typeFlow.typeCheck(this.finallyNode); + this.type = typeFlow.voidType; + return this; + } + + public addToControlFlow(context: ControlFlowContext) { + var afterFinally = new BasicBlock(); + context.walk(this.tryNode, this); + var finBlock = new BasicBlock(); + if (context.current) { + context.current.addSuccessor(finBlock); + } + context.current = finBlock; + context.pushStatement(this, null, afterFinally); + context.walk(this.finallyNode, this); + if (!context.noContinuation && context.current) { + context.current.addSuccessor(afterFinally); + } + if (afterFinally.predecessors.length > 0) { + context.current = afterFinally; + } + else { + context.noContinuation = true; + } + context.popStatement(); + context.walker.options.goChildren = false; + } + } + + export class TryCatch extends Statement { + constructor (public tryNode: Try, public catchNode: Catch) { + super(NodeType.TryCatch); + } + + public isCompoundStatement() { return true; } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.tryNode, TokenID.Try, false); + emitter.emitJavascript(this.catchNode, TokenID.Catch, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + + public addToControlFlow(context: ControlFlowContext) { + var beforeTry = context.current; + var tryBlock = new BasicBlock(); + beforeTry.addSuccessor(tryBlock); + context.current = tryBlock; + var afterTryCatch = new BasicBlock(); + context.pushStatement(this, null, afterTryCatch); + context.walk(this.tryNode, this); + if (!context.noContinuation) { + if (context.current) { + context.current.addSuccessor(afterTryCatch); + } + } + context.current = new BasicBlock(); + beforeTry.addSuccessor(context.current); + context.walk(this.catchNode, this); + context.popStatement(); + if (!context.noContinuation) { + if (context.current) { + context.current.addSuccessor(afterTryCatch); + } + } + context.current = afterTryCatch; + context.walker.options.goChildren = false; + } + + public typeCheck(typeFlow: TypeFlow) { + this.tryNode = typeFlow.typeCheck(this.tryNode); + this.catchNode = typeFlow.typeCheck(this.catchNode); + this.type = typeFlow.voidType; + return this; + } + } + + export class Try extends Statement { + constructor (public body: AST) { + super(NodeType.Try); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("try "); + emitter.emitJavascript(this.body, TokenID.Try, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + + public typeCheck(typeFlow: TypeFlow) { + this.body = typeFlow.typeCheck(this.body); + return this; + } + + public addToControlFlow(context: ControlFlowContext) { + if (this.body) { + context.walk(this.body, this); + } + context.walker.options.goChildren = false; + context.noContinuation = false; + } + } + + export class Catch extends Statement { + constructor (public param: VarDecl, public body: AST) { + super(NodeType.Catch); + if (this.param) { + this.param.varFlags |= VarFlags.AutoInit; + } + } + public statement: ASTSpan = new ASTSpan(); + public containedScope: SymbolScope = null; + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(" "); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("catch ("); + emitter.emitJavascript(this.param, TokenID.OpenParen, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascript(this.body, TokenID.Catch, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + + public addToControlFlow(context: ControlFlowContext) { + if (this.param) { + context.addContent(this.param); + var bodBlock = new BasicBlock(); + context.current.addSuccessor(bodBlock); + context.current = bodBlock; + } + if (this.body) { + context.walk(this.body, this); + } + context.noContinuation = false; + context.walker.options.goChildren = false; + } + + public typeCheck(typeFlow: TypeFlow) { + var prevScope = typeFlow.scope; + typeFlow.scope = this.containedScope; + this.param = typeFlow.typeCheck(this.param); + var exceptVar = new ValueLocation(); + var varSym = new VariableSymbol((this.param).id.text, + this.param.minChar, + typeFlow.checker.locationInfo.unitIndex, + exceptVar); + exceptVar.symbol = varSym; + exceptVar.typeLink = new TypeLink(); + // var type for now (add syntax for type annotation) + exceptVar.typeLink.type = typeFlow.anyType; + var thisFnc = typeFlow.thisFnc; + if (thisFnc && thisFnc.type) { + exceptVar.symbol.container = thisFnc.type.symbol; + } + else { + exceptVar.symbol.container = null; + } + this.param.sym = exceptVar.symbol; + typeFlow.scope.enter(exceptVar.symbol.container, this.param, exceptVar.symbol, + typeFlow.checker.errorReporter, false, false, false); + this.body = typeFlow.typeCheck(this.body); + + // if we're in provisional typecheck mode, clean up the symbol entry + // REVIEW: This is obviously bad form, since we're counting on the internal + // layout of the symbol table, but this is also the only place where we insert + // symbols during typecheck + if (typeFlow.checker.inProvisionalTypecheckMode()) { + var table = typeFlow.scope.getTable(); + (table).secondaryTable.table[exceptVar.symbol.name] = undefined; + } + this.type = typeFlow.voidType; + typeFlow.scope = prevScope; + return this; + } + } + + export class Finally extends Statement { + constructor (public body: AST) { + super(NodeType.Finally); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("finally"); + emitter.emitJavascript(this.body, TokenID.Finally, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + + public addToControlFlow(context: ControlFlowContext) { + if (this.body) { + context.walk(this.body, this); + } + context.walker.options.goChildren = false; + context.noContinuation = false; + } + + public typeCheck(typeFlow: TypeFlow) { + this.body = typeFlow.typeCheck(this.body); + return this; + } + } + + export class Comment extends AST { + + public text: string[] = null; + + constructor (public content: string, public isBlockComment: boolean, public endsLine) { + super(NodeType.Comment); + } + + public getText(): string[] { + if (this.text == null) { + if (this.isBlockComment) { + this.text = this.content.split("\n"); + for (var i = 0; i < this.text.length; i++) { + this.text[i] = this.text[i].replace(/^\s+|\s+$/g, ''); + } + } + else { + this.text = [(this.content.replace(/^\s+|\s+$/g, ''))]; + } + } + + return this.text; + } + } + + export class DebuggerStatement extends Statement { + constructor () { + super(NodeType.Debugger); + } + + public emit(emitter: Emitter, tokenId: TokenID, startLine: boolean) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeLineToOutput("debugger;"); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + } +} + +//// [parserRealSource11.js] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. +var __extends = this.__extends || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + __.prototype = b.prototype; + d.prototype = new __(); +}; +/// +var TypeScript; +(function (TypeScript) { + var ASTSpan = (function () { + function ASTSpan() { + this.minChar = -1; // -1 = "undefined" or "compiler generated" + this.limChar = -1; // -1 = "undefined" or "compiler generated" + } + return ASTSpan; + })(); + TypeScript.ASTSpan = ASTSpan; + var AST = (function (_super) { + __extends(AST, _super); + function AST(nodeType) { + _super.call(this); + this.nodeType = nodeType; + this.type = null; + this.flags = ASTFlags.Writeable; + // REVIEW: for diagnostic purposes + this.passCreated = CompilerDiagnostics.analysisPass; + this.preComments = null; + this.postComments = null; + this.isParenthesized = false; + } + AST.prototype.isExpression = function () { + return false; + }; + AST.prototype.isStatementOrExpression = function () { + return false; + }; + AST.prototype.isCompoundStatement = function () { + return false; + }; + AST.prototype.isLeaf = function () { + return this.isStatementOrExpression() && (!this.isCompoundStatement()); + }; + AST.prototype.typeCheck = function (typeFlow) { + switch (this.nodeType) { + case NodeType.Error: + case NodeType.EmptyExpr: + this.type = typeFlow.anyType; + break; + case NodeType.This: + return typeFlow.typeCheckThis(this); + case NodeType.Null: + this.type = typeFlow.nullType; + break; + case NodeType.False: + case NodeType.True: + this.type = typeFlow.booleanType; + break; + case NodeType.Super: + return typeFlow.typeCheckSuper(this); + case NodeType.EndCode: + case NodeType.Empty: + case NodeType.Void: + this.type = typeFlow.voidType; + break; + default: + throw new Error("please implement in derived class"); + } + return this; + }; + AST.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + switch (this.nodeType) { + case NodeType.This: + emitter.recordSourceMappingStart(this); + if (emitter.thisFnc && (hasFlag(emitter.thisFnc.fncFlags, FncFlags.IsFatArrowFunction))) { + emitter.writeToOutput("_this"); + } + else { + emitter.writeToOutput("this"); + } + emitter.recordSourceMappingEnd(this); + break; + case NodeType.Null: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("null"); + emitter.recordSourceMappingEnd(this); + break; + case NodeType.False: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("false"); + emitter.recordSourceMappingEnd(this); + break; + case NodeType.True: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("true"); + emitter.recordSourceMappingEnd(this); + break; + case NodeType.Super: + emitter.recordSourceMappingStart(this); + emitter.emitSuperReference(); + emitter.recordSourceMappingEnd(this); + break; + case NodeType.EndCode: + break; + case NodeType.Error: + case NodeType.EmptyExpr: + break; + case NodeType.Empty: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("; "); + emitter.recordSourceMappingEnd(this); + break; + case NodeType.Void: + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("void "); + emitter.recordSourceMappingEnd(this); + break; + default: + throw new Error("please implement in derived class"); + } + emitter.emitParensAndCommentsInPlace(this, false); + }; + AST.prototype.print = function (context) { + context.startLine(); + var lineCol = { line: -1, col: -1 }; + var limLineCol = { line: -1, col: -1 }; + if (context.parser !== null) { + context.parser.getSourceLineCol(lineCol, this.minChar); + context.parser.getSourceLineCol(limLineCol, this.limChar); + context.write("(" + lineCol.line + "," + lineCol.col + ")--" + "(" + limLineCol.line + "," + limLineCol.col + "): "); + } + var lab = this.printLabel(); + if (hasFlag(this.flags, ASTFlags.Error)) { + lab += " (Error)"; + } + context.writeLine(lab); + }; + AST.prototype.printLabel = function () { + if (nodeTypeTable[this.nodeType] !== undefined) { + return nodeTypeTable[this.nodeType]; + } + else { + return NodeType._map[this.nodeType]; + } + }; + AST.prototype.addToControlFlow = function (context) { + // by default, AST adds itself to current basic block and does not check its children + context.walker.options.goChildren = false; + context.addContent(this); + }; + AST.prototype.netFreeUses = function (container, freeUses) { + }; + AST.prototype.treeViewLabel = function () { + return NodeType._map[this.nodeType]; + }; + AST.getResolvedIdentifierName = function (name) { + if (!name) + return ""; + var resolved = ""; + var start = 0; + var i = 0; + while (i <= name.length - 6) { + // Look for escape sequence \uxxxx + if (name.charAt(i) == '\\' && name.charAt(i + 1) == 'u') { + var charCode = parseInt(name.substr(i + 2, 4), 16); + resolved += name.substr(start, i - start); + resolved += String.fromCharCode(charCode); + i += 6; + start = i; + continue; + } + i++; + } + // Append remaining string + resolved += name.substring(start); + return resolved; + }; + return AST; + })(ASTSpan); + TypeScript.AST = AST; + var IncompleteAST = (function (_super) { + __extends(IncompleteAST, _super); + function IncompleteAST(min, lim) { + _super.call(this, NodeType.Error); + this.minChar = min; + this.limChar = lim; + } + return IncompleteAST; + })(AST); + TypeScript.IncompleteAST = IncompleteAST; + var ASTList = (function (_super) { + __extends(ASTList, _super); + function ASTList() { + _super.call(this, NodeType.List); + this.enclosingScope = null; + this.members = new AST[]; + } + ASTList.prototype.addToControlFlow = function (context) { + var len = this.members.length; + for (var i = 0; i < len; i++) { + if (context.noContinuation) { + context.addUnreachable(this.members[i]); + break; + } + else { + this.members[i] = context.walk(this.members[i], this); + } + } + context.walker.options.goChildren = false; + }; + ASTList.prototype.append = function (ast) { + this.members[this.members.length] = ast; + return this; + }; + ASTList.prototype.appendAll = function (ast) { + if (ast.nodeType == NodeType.List) { + var list = ast; + for (var i = 0, len = list.members.length; i < len; i++) { + this.append(list.members[i]); + } + } + else { + this.append(ast); + } + return this; + }; + ASTList.prototype.emit = function (emitter, tokenId, startLine) { + emitter.recordSourceMappingStart(this); + emitter.emitJavascriptList(this, null, TokenID.Semicolon, startLine, false, false); + emitter.recordSourceMappingEnd(this); + }; + ASTList.prototype.typeCheck = function (typeFlow) { + var len = this.members.length; + typeFlow.nestingLevel++; + for (var i = 0; i < len; i++) { + if (this.members[i]) { + this.members[i] = this.members[i].typeCheck(typeFlow); + } + } + typeFlow.nestingLevel--; + return this; + }; + return ASTList; + })(AST); + TypeScript.ASTList = ASTList; + var Identifier = (function (_super) { + __extends(Identifier, _super); + // 'actualText' is the text that the user has entered for the identifier. the text might + // include any Unicode escape sequences (e.g.: \u0041 for 'A'). 'text', however, contains + // the resolved value of any escape sequences in the actual text; so in the previous + // example, actualText = '\u0041', text = 'A'. + // + // For purposes of finding a symbol, use text, as this will allow you to match all + // variations of the variable text. For full-fidelity translation of the user input, such + // as emitting, use the actualText field. + // + // Note: + // To change text, and to avoid running into a situation where 'actualText' does not + // match 'text', always use setText. + function Identifier(actualText, hasEscapeSequence) { + _super.call(this, NodeType.Name); + this.actualText = actualText; + this.hasEscapeSequence = hasEscapeSequence; + this.sym = null; + this.cloId = -1; + this.setText(actualText, hasEscapeSequence); + } + Identifier.prototype.setText = function (actualText, hasEscapeSequence) { + this.actualText = actualText; + if (hasEscapeSequence) { + this.text = AST.getResolvedIdentifierName(actualText); + } + else { + this.text = actualText; + } + }; + Identifier.prototype.isMissing = function () { + return false; + }; + Identifier.prototype.isLeaf = function () { + return true; + }; + Identifier.prototype.treeViewLabel = function () { + return "id: " + this.actualText; + }; + Identifier.prototype.printLabel = function () { + if (this.actualText) { + return "id: " + this.actualText; + } + else { + return "name node"; + } + }; + Identifier.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckName(this); + }; + Identifier.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptName(this, true); + }; + Identifier.fromToken = function (token) { + return new Identifier(token.getText(), token.hasEscapeSequence); + }; + return Identifier; + })(AST); + TypeScript.Identifier = Identifier; + var MissingIdentifier = (function (_super) { + __extends(MissingIdentifier, _super); + function MissingIdentifier() { + _super.call(this, "__missing"); + } + MissingIdentifier.prototype.isMissing = function () { + return true; + }; + MissingIdentifier.prototype.emit = function (emitter, tokenId, startLine) { + // Emit nothing for a missing ID + }; + return MissingIdentifier; + })(Identifier); + TypeScript.MissingIdentifier = MissingIdentifier; + var Label = (function (_super) { + __extends(Label, _super); + function Label(id) { + _super.call(this, NodeType.Label); + this.id = id; + } + Label.prototype.printLabel = function () { + return this.id.actualText + ":"; + }; + Label.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.voidType; + return this; + }; + Label.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.recordSourceMappingStart(this.id); + emitter.writeToOutput(this.id.actualText); + emitter.recordSourceMappingEnd(this.id); + emitter.writeLineToOutput(":"); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return Label; + })(AST); + TypeScript.Label = Label; + var Expression = (function (_super) { + __extends(Expression, _super); + function Expression(nodeType) { + _super.call(this, nodeType); + } + Expression.prototype.isExpression = function () { + return true; + }; + Expression.prototype.isStatementOrExpression = function () { + return true; + }; + return Expression; + })(AST); + TypeScript.Expression = Expression; + var UnaryExpression = (function (_super) { + __extends(UnaryExpression, _super); + function UnaryExpression(nodeType, operand) { + _super.call(this, nodeType); + this.operand = operand; + this.targetType = null; // Target type for an object literal (null if no target type) + this.castTerm = null; + } + UnaryExpression.prototype.addToControlFlow = function (context) { + _super.prototype.addToControlFlow.call(this, context); + // TODO: add successor as catch block/finally block if present + if (this.nodeType == NodeType.Throw) { + context.returnStmt(); + } + }; + UnaryExpression.prototype.typeCheck = function (typeFlow) { + switch (this.nodeType) { + case NodeType.Not: + return typeFlow.typeCheckBitNot(this); + case NodeType.LogNot: + return typeFlow.typeCheckLogNot(this); + case NodeType.Pos: + case NodeType.Neg: + return typeFlow.typeCheckUnaryNumberOperator(this); + case NodeType.IncPost: + case NodeType.IncPre: + case NodeType.DecPost: + case NodeType.DecPre: + return typeFlow.typeCheckIncOrDec(this); + case NodeType.ArrayLit: + typeFlow.typeCheckArrayLit(this); + return this; + case NodeType.ObjectLit: + typeFlow.typeCheckObjectLit(this); + return this; + case NodeType.Throw: + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.voidType; + return this; + case NodeType.Typeof: + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.stringType; + return this; + case NodeType.Delete: + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.booleanType; + break; + case NodeType.TypeAssertion: + this.castTerm = typeFlow.typeCheck(this.castTerm); + var applyTargetType = !this.operand.isParenthesized; + var targetType = applyTargetType ? this.castTerm.type : null; + typeFlow.checker.typeCheckWithContextualType(targetType, typeFlow.checker.inProvisionalTypecheckMode(), true, this.operand); + typeFlow.castWithCoercion(this.operand, this.castTerm.type, false, true); + this.type = this.castTerm.type; + return this; + case NodeType.Void: + // REVIEW - Although this is good to do for completeness's sake, + // this shouldn't be strictly necessary from the void operator's + // point of view + this.operand = typeFlow.typeCheck(this.operand); + this.type = typeFlow.checker.undefinedType; + break; + default: + throw new Error("please implement in derived class"); + } + return this; + }; + UnaryExpression.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + switch (this.nodeType) { + case NodeType.IncPost: + emitter.emitJavascript(this.operand, TokenID.PlusPlus, false); + emitter.writeToOutput("++"); + break; + case NodeType.LogNot: + emitter.writeToOutput("!"); + emitter.emitJavascript(this.operand, TokenID.Exclamation, false); + break; + case NodeType.DecPost: + emitter.emitJavascript(this.operand, TokenID.MinusMinus, false); + emitter.writeToOutput("--"); + break; + case NodeType.ObjectLit: + emitter.emitObjectLiteral(this.operand); + break; + case NodeType.ArrayLit: + emitter.emitArrayLiteral(this.operand); + break; + case NodeType.Not: + emitter.writeToOutput("~"); + emitter.emitJavascript(this.operand, TokenID.Tilde, false); + break; + case NodeType.Neg: + emitter.writeToOutput("-"); + if (this.operand.nodeType == NodeType.Neg) { + this.operand.isParenthesized = true; + } + emitter.emitJavascript(this.operand, TokenID.Minus, false); + break; + case NodeType.Pos: + emitter.writeToOutput("+"); + if (this.operand.nodeType == NodeType.Pos) { + this.operand.isParenthesized = true; + } + emitter.emitJavascript(this.operand, TokenID.Plus, false); + break; + case NodeType.IncPre: + emitter.writeToOutput("++"); + emitter.emitJavascript(this.operand, TokenID.PlusPlus, false); + break; + case NodeType.DecPre: + emitter.writeToOutput("--"); + emitter.emitJavascript(this.operand, TokenID.MinusMinus, false); + break; + case NodeType.Throw: + emitter.writeToOutput("throw "); + emitter.emitJavascript(this.operand, TokenID.Tilde, false); + emitter.writeToOutput(";"); + break; + case NodeType.Typeof: + emitter.writeToOutput("typeof "); + emitter.emitJavascript(this.operand, TokenID.Tilde, false); + break; + case NodeType.Delete: + emitter.writeToOutput("delete "); + emitter.emitJavascript(this.operand, TokenID.Tilde, false); + break; + case NodeType.Void: + emitter.writeToOutput("void "); + emitter.emitJavascript(this.operand, TokenID.Tilde, false); + break; + case NodeType.TypeAssertion: + emitter.emitJavascript(this.operand, TokenID.Tilde, false); + break; + default: + throw new Error("please implement in derived class"); + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return UnaryExpression; + })(Expression); + TypeScript.UnaryExpression = UnaryExpression; + var CallExpression = (function (_super) { + __extends(CallExpression, _super); + function CallExpression(nodeType, target, arguments) { + _super.call(this, nodeType); + this.target = target; + this.arguments = arguments; + this.signature = null; + this.minChar = this.target.minChar; + } + CallExpression.prototype.typeCheck = function (typeFlow) { + if (this.nodeType == NodeType.New) { + return typeFlow.typeCheckNew(this); + } + else { + return typeFlow.typeCheckCall(this); + } + }; + CallExpression.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if (this.nodeType == NodeType.New) { + emitter.emitNew(this.target, this.arguments); + } + else { + emitter.emitCall(this, this.target, this.arguments); + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return CallExpression; + })(Expression); + TypeScript.CallExpression = CallExpression; + var BinaryExpression = (function (_super) { + __extends(BinaryExpression, _super); + function BinaryExpression(nodeType, operand1, operand2) { + _super.call(this, nodeType); + this.operand1 = operand1; + this.operand2 = operand2; + } + BinaryExpression.prototype.typeCheck = function (typeFlow) { + switch (this.nodeType) { + case NodeType.Dot: + return typeFlow.typeCheckDotOperator(this); + case NodeType.Asg: + return typeFlow.typeCheckAsgOperator(this); + case NodeType.Add: + case NodeType.Sub: + case NodeType.Mul: + case NodeType.Div: + case NodeType.Mod: + case NodeType.Or: + case NodeType.And: + return typeFlow.typeCheckArithmeticOperator(this, false); + case NodeType.Xor: + return typeFlow.typeCheckBitwiseOperator(this, false); + case NodeType.Ne: + case NodeType.Eq: + var text; + if (typeFlow.checker.styleSettings.eqeqeq) { + text = nodeTypeTable[this.nodeType]; + typeFlow.checker.errorReporter.styleError(this, "use of " + text); + } + else if (typeFlow.checker.styleSettings.eqnull) { + text = nodeTypeTable[this.nodeType]; + if ((this.operand2 !== null) && (this.operand2.nodeType == NodeType.Null)) { + typeFlow.checker.errorReporter.styleError(this, "use of " + text + " to compare with null"); + } + } + case NodeType.Eqv: + case NodeType.NEqv: + case NodeType.Lt: + case NodeType.Le: + case NodeType.Ge: + case NodeType.Gt: + return typeFlow.typeCheckBooleanOperator(this); + case NodeType.Index: + return typeFlow.typeCheckIndex(this); + case NodeType.Member: + this.type = typeFlow.voidType; + return this; + case NodeType.LogOr: + return typeFlow.typeCheckLogOr(this); + case NodeType.LogAnd: + return typeFlow.typeCheckLogAnd(this); + case NodeType.AsgAdd: + case NodeType.AsgSub: + case NodeType.AsgMul: + case NodeType.AsgDiv: + case NodeType.AsgMod: + case NodeType.AsgOr: + case NodeType.AsgAnd: + return typeFlow.typeCheckArithmeticOperator(this, true); + case NodeType.AsgXor: + return typeFlow.typeCheckBitwiseOperator(this, true); + case NodeType.Lsh: + case NodeType.Rsh: + case NodeType.Rs2: + return typeFlow.typeCheckShift(this, false); + case NodeType.AsgLsh: + case NodeType.AsgRsh: + case NodeType.AsgRs2: + return typeFlow.typeCheckShift(this, true); + case NodeType.Comma: + return typeFlow.typeCheckCommaOperator(this); + case NodeType.InstOf: + return typeFlow.typeCheckInstOf(this); + case NodeType.In: + return typeFlow.typeCheckInOperator(this); + case NodeType.From: + typeFlow.checker.errorReporter.simpleError(this, "Illegal use of 'from' keyword in binary expression"); + break; + default: + throw new Error("please implement in derived class"); + } + return this; + }; + BinaryExpression.prototype.emit = function (emitter, tokenId, startLine) { + var binTokenId = nodeTypeToTokTable[this.nodeType]; + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if (binTokenId != undefined) { + emitter.emitJavascript(this.operand1, binTokenId, false); + if (tokenTable[binTokenId].text == "instanceof") { + emitter.writeToOutput(" instanceof "); + } + else if (tokenTable[binTokenId].text == "in") { + emitter.writeToOutput(" in "); + } + else { + emitter.writeToOutputTrimmable(" " + tokenTable[binTokenId].text + " "); + } + emitter.emitJavascript(this.operand2, binTokenId, false); + } + else { + switch (this.nodeType) { + case NodeType.Dot: + if (!emitter.tryEmitConstant(this)) { + emitter.emitJavascript(this.operand1, TokenID.Dot, false); + emitter.writeToOutput("."); + emitter.emitJavascriptName(this.operand2, false); + } + break; + case NodeType.Index: + emitter.emitIndex(this.operand1, this.operand2); + break; + case NodeType.Member: + if (this.operand2.nodeType == NodeType.FuncDecl && this.operand2.isAccessor()) { + var funcDecl = this.operand2; + if (hasFlag(funcDecl.fncFlags, FncFlags.GetAccessor)) { + emitter.writeToOutput("get "); + } + else { + emitter.writeToOutput("set "); + } + emitter.emitJavascript(this.operand1, TokenID.Colon, false); + } + else { + emitter.emitJavascript(this.operand1, TokenID.Colon, false); + emitter.writeToOutputTrimmable(": "); + } + emitter.emitJavascript(this.operand2, TokenID.Comma, false); + break; + case NodeType.Comma: + emitter.emitJavascript(this.operand1, TokenID.Comma, false); + if (emitter.emitState.inObjectLiteral) { + emitter.writeLineToOutput(", "); + } + else { + emitter.writeToOutput(","); + } + emitter.emitJavascript(this.operand2, TokenID.Comma, false); + break; + case NodeType.Is: + throw new Error("should be de-sugared during type check"); + default: + throw new Error("please implement in derived class"); + } + } + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return BinaryExpression; + })(Expression); + TypeScript.BinaryExpression = BinaryExpression; + var ConditionalExpression = (function (_super) { + __extends(ConditionalExpression, _super); + function ConditionalExpression(operand1, operand2, operand3) { + _super.call(this, NodeType.ConditionalExpression); + this.operand1 = operand1; + this.operand2 = operand2; + this.operand3 = operand3; + } + ConditionalExpression.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckQMark(this); + }; + ConditionalExpression.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.operand1, TokenID.Question, false); + emitter.writeToOutput(" ? "); + emitter.emitJavascript(this.operand2, TokenID.Question, false); + emitter.writeToOutput(" : "); + emitter.emitJavascript(this.operand3, TokenID.Question, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return ConditionalExpression; + })(Expression); + TypeScript.ConditionalExpression = ConditionalExpression; + var NumberLiteral = (function (_super) { + __extends(NumberLiteral, _super); + function NumberLiteral(value, hasEmptyFraction) { + _super.call(this, NodeType.NumberLit); + this.value = value; + this.hasEmptyFraction = hasEmptyFraction; + this.isNegativeZero = false; + } + NumberLiteral.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.doubleType; + return this; + }; + NumberLiteral.prototype.treeViewLabel = function () { + return "num: " + this.printLabel(); + }; + NumberLiteral.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if (this.isNegativeZero) { + emitter.writeToOutput("-"); + } + emitter.writeToOutput(this.value.toString()); + if (this.hasEmptyFraction) + emitter.writeToOutput(".0"); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + NumberLiteral.prototype.printLabel = function () { + if (Math.floor(this.value) != this.value) { + return this.value.toFixed(2).toString(); + } + else if (this.hasEmptyFraction) { + return this.value.toString() + ".0"; + } + else { + return this.value.toString(); + } + }; + return NumberLiteral; + })(Expression); + TypeScript.NumberLiteral = NumberLiteral; + var RegexLiteral = (function (_super) { + __extends(RegexLiteral, _super); + function RegexLiteral(regex) { + _super.call(this, NodeType.Regex); + this.regex = regex; + } + RegexLiteral.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.regexType; + return this; + }; + RegexLiteral.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(this.regex.toString()); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return RegexLiteral; + })(Expression); + TypeScript.RegexLiteral = RegexLiteral; + var StringLiteral = (function (_super) { + __extends(StringLiteral, _super); + function StringLiteral(text) { + _super.call(this, NodeType.QString); + this.text = text; + } + StringLiteral.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitStringLiteral(this.text); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + StringLiteral.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.stringType; + return this; + }; + StringLiteral.prototype.treeViewLabel = function () { + return "st: " + this.text; + }; + StringLiteral.prototype.printLabel = function () { + return this.text; + }; + return StringLiteral; + })(Expression); + TypeScript.StringLiteral = StringLiteral; + var ModuleElement = (function (_super) { + __extends(ModuleElement, _super); + function ModuleElement(nodeType) { + _super.call(this, nodeType); + } + return ModuleElement; + })(AST); + TypeScript.ModuleElement = ModuleElement; + var ImportDeclaration = (function (_super) { + __extends(ImportDeclaration, _super); + function ImportDeclaration(id, alias) { + _super.call(this, NodeType.ImportDeclaration); + this.id = id; + this.alias = alias; + this.varFlags = VarFlags.None; + this.isDynamicImport = false; + } + ImportDeclaration.prototype.isStatementOrExpression = function () { + return true; + }; + ImportDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + var mod = this.alias.type; + // REVIEW: Only modules may be aliased for now, though there's no real + // restriction on what the type symbol may be + if (!this.isDynamicImport || (this.id.sym && !this.id.sym.onlyReferencedAsTypeRef)) { + var prevModAliasId = emitter.modAliasId; + var prevFirstModAlias = emitter.firstModAlias; + emitter.recordSourceMappingStart(this); + emitter.emitParensAndCommentsInPlace(this, true); + emitter.writeToOutput("var " + this.id.actualText + " = "); + emitter.modAliasId = this.id.actualText; + emitter.firstModAlias = this.firstAliasedModToString(); + emitter.emitJavascript(this.alias, TokenID.Tilde, false); + // the dynamic import case will insert the semi-colon automatically + if (!this.isDynamicImport) { + emitter.writeToOutput(";"); + } + emitter.emitParensAndCommentsInPlace(this, false); + emitter.recordSourceMappingEnd(this); + emitter.modAliasId = prevModAliasId; + emitter.firstModAlias = prevFirstModAlias; + } + }; + ImportDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckImportDecl(this); + }; + ImportDeclaration.prototype.getAliasName = function (aliasAST) { + if (aliasAST === void 0) { aliasAST = this.alias; } + if (aliasAST.nodeType == NodeType.Name) { + return aliasAST.actualText; + } + else { + var dotExpr = aliasAST; + return this.getAliasName(dotExpr.operand1) + "." + this.getAliasName(dotExpr.operand2); + } + }; + ImportDeclaration.prototype.firstAliasedModToString = function () { + if (this.alias.nodeType == NodeType.Name) { + return this.alias.actualText; + } + else { + var dotExpr = this.alias; + var firstMod = dotExpr.operand1; + return firstMod.actualText; + } + }; + return ImportDeclaration; + })(ModuleElement); + TypeScript.ImportDeclaration = ImportDeclaration; + var BoundDecl = (function (_super) { + __extends(BoundDecl, _super); + function BoundDecl(id, nodeType, nestingLevel) { + _super.call(this, nodeType); + this.id = id; + this.nestingLevel = nestingLevel; + this.init = null; + this.typeExpr = null; + this.varFlags = VarFlags.None; + this.sym = null; + } + BoundDecl.prototype.isStatementOrExpression = function () { + return true; + }; + BoundDecl.prototype.isPrivate = function () { + return hasFlag(this.varFlags, VarFlags.Private); + }; + BoundDecl.prototype.isPublic = function () { + return hasFlag(this.varFlags, VarFlags.Public); + }; + BoundDecl.prototype.isProperty = function () { + return hasFlag(this.varFlags, VarFlags.Property); + }; + BoundDecl.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckBoundDecl(this); + }; + BoundDecl.prototype.printLabel = function () { + return this.treeViewLabel(); + }; + return BoundDecl; + })(AST); + TypeScript.BoundDecl = BoundDecl; + var VarDecl = (function (_super) { + __extends(VarDecl, _super); + function VarDecl(id, nest) { + _super.call(this, id, NodeType.VarDecl, nest); + } + VarDecl.prototype.isAmbient = function () { + return hasFlag(this.varFlags, VarFlags.Ambient); + }; + VarDecl.prototype.isExported = function () { + return hasFlag(this.varFlags, VarFlags.Exported); + }; + VarDecl.prototype.isStatic = function () { + return hasFlag(this.varFlags, VarFlags.Static); + }; + VarDecl.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptVarDecl(this, tokenId); + }; + VarDecl.prototype.treeViewLabel = function () { + return "var " + this.id.actualText; + }; + return VarDecl; + })(BoundDecl); + TypeScript.VarDecl = VarDecl; + var ArgDecl = (function (_super) { + __extends(ArgDecl, _super); + function ArgDecl(id) { + _super.call(this, id, NodeType.ArgDecl, 0); + this.isOptional = false; + this.parameterPropertySym = null; + } + ArgDecl.prototype.isOptionalArg = function () { + return this.isOptional || this.init; + }; + ArgDecl.prototype.treeViewLabel = function () { + return "arg: " + this.id.actualText; + }; + ArgDecl.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(this.id.actualText); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return ArgDecl; + })(BoundDecl); + TypeScript.ArgDecl = ArgDecl; + var internalId = 0; + var FuncDecl = (function (_super) { + __extends(FuncDecl, _super); + function FuncDecl(name, bod, isConstructor, arguments, vars, scopes, statics, nodeType) { + _super.call(this, nodeType); + this.name = name; + this.bod = bod; + this.isConstructor = isConstructor; + this.arguments = arguments; + this.vars = vars; + this.scopes = scopes; + this.statics = statics; + this.hint = null; + this.fncFlags = FncFlags.None; + this.returnTypeAnnotation = null; + this.variableArgList = false; + this.jumpRefs = null; + this.internalNameCache = null; + this.tmp1Declared = false; + this.enclosingFnc = null; + this.freeVariables = []; + this.unitIndex = -1; + this.classDecl = null; + this.boundToProperty = null; + this.isOverload = false; + this.innerStaticFuncs = []; + this.isTargetTypedAsMethod = false; + this.isInlineCallLiteral = false; + this.accessorSymbol = null; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + this.returnStatementsWithExpressions = []; + this.scopeType = null; // Type of the FuncDecl, before target typing + this.endingToken = null; + } + FuncDecl.prototype.internalName = function () { + if (this.internalNameCache == null) { + var extName = this.getNameText(); + if (extName) { + this.internalNameCache = "_internal_" + extName; + } + else { + this.internalNameCache = "_internal_" + internalId++; + } + } + return this.internalNameCache; + }; + FuncDecl.prototype.hasSelfReference = function () { + return hasFlag(this.fncFlags, FncFlags.HasSelfReference); + }; + FuncDecl.prototype.setHasSelfReference = function () { + this.fncFlags |= FncFlags.HasSelfReference; + }; + FuncDecl.prototype.addCloRef = function (id, sym) { + if (this.envids == null) { + this.envids = new Identifier[]; + } + this.envids[this.envids.length] = id; + var outerFnc = this.enclosingFnc; + if (sym) { + while (outerFnc && (outerFnc.type.symbol != sym.container)) { + outerFnc.addJumpRef(sym); + outerFnc = outerFnc.enclosingFnc; + } + } + return this.envids.length - 1; + }; + FuncDecl.prototype.addJumpRef = function (sym) { + if (this.jumpRefs == null) { + this.jumpRefs = new Identifier[]; + } + var id = new Identifier(sym.name); + this.jumpRefs[this.jumpRefs.length] = id; + id.sym = sym; + id.cloId = this.addCloRef(id, null); + }; + FuncDecl.prototype.buildControlFlow = function () { + var entry = new BasicBlock(); + var exit = new BasicBlock(); + var context = new ControlFlowContext(entry, exit); + var controlFlowPrefix = function (ast, parent, walker) { + ast.addToControlFlow(walker.state); + return ast; + }; + var walker = getAstWalkerFactory().getWalker(controlFlowPrefix, null, null, context); + context.walker = walker; + walker.walk(this.bod, this); + return context; + }; + FuncDecl.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckFunction(this); + }; + FuncDecl.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptFunction(this); + }; + FuncDecl.prototype.getNameText = function () { + if (this.name) { + return this.name.actualText; + } + else { + return this.hint; + } + }; + FuncDecl.prototype.isMethod = function () { + return (this.fncFlags & FncFlags.Method) != FncFlags.None; + }; + FuncDecl.prototype.isCallMember = function () { + return hasFlag(this.fncFlags, FncFlags.CallMember); + }; + FuncDecl.prototype.isConstructMember = function () { + return hasFlag(this.fncFlags, FncFlags.ConstructMember); + }; + FuncDecl.prototype.isIndexerMember = function () { + return hasFlag(this.fncFlags, FncFlags.IndexerMember); + }; + FuncDecl.prototype.isSpecialFn = function () { + return this.isCallMember() || this.isIndexerMember() || this.isConstructMember(); + }; + FuncDecl.prototype.isAnonymousFn = function () { + return this.name === null; + }; + FuncDecl.prototype.isAccessor = function () { + return hasFlag(this.fncFlags, FncFlags.GetAccessor) || hasFlag(this.fncFlags, FncFlags.SetAccessor); + }; + FuncDecl.prototype.isGetAccessor = function () { + return hasFlag(this.fncFlags, FncFlags.GetAccessor); + }; + FuncDecl.prototype.isSetAccessor = function () { + return hasFlag(this.fncFlags, FncFlags.SetAccessor); + }; + FuncDecl.prototype.isAmbient = function () { + return hasFlag(this.fncFlags, FncFlags.Ambient); + }; + FuncDecl.prototype.isExported = function () { + return hasFlag(this.fncFlags, FncFlags.Exported); + }; + FuncDecl.prototype.isPrivate = function () { + return hasFlag(this.fncFlags, FncFlags.Private); + }; + FuncDecl.prototype.isPublic = function () { + return hasFlag(this.fncFlags, FncFlags.Public); + }; + FuncDecl.prototype.isStatic = function () { + return hasFlag(this.fncFlags, FncFlags.Static); + }; + FuncDecl.prototype.treeViewLabel = function () { + if (this.name == null) { + return "funcExpr"; + } + else { + return "func: " + this.name.actualText; + } + }; + FuncDecl.prototype.ClearFlags = function () { + this.fncFlags = FncFlags.None; + }; + FuncDecl.prototype.isSignature = function () { + return (this.fncFlags & FncFlags.Signature) != FncFlags.None; + }; + FuncDecl.prototype.hasStaticDeclarations = function () { + return (!this.isConstructor && (this.statics.members.length > 0 || this.innerStaticFuncs.length > 0)); + }; + return FuncDecl; + })(AST); + TypeScript.FuncDecl = FuncDecl; + var LocationInfo = (function () { + function LocationInfo(filename, lineMap, unitIndex) { + this.filename = filename; + this.lineMap = lineMap; + this.unitIndex = unitIndex; + } + return LocationInfo; + })(); + TypeScript.LocationInfo = LocationInfo; + TypeScript.unknownLocationInfo = new LocationInfo("unknown", null, -1); + var Script = (function (_super) { + __extends(Script, _super); + function Script(vars, scopes) { + _super.call(this, new Identifier("script"), null, false, null, vars, scopes, null, NodeType.Script); + this.locationInfo = null; + this.referencedFiles = []; + this.requiresGlobal = false; + this.requiresInherits = false; + this.isResident = false; + this.isDeclareFile = false; + this.hasBeenTypeChecked = false; + this.topLevelMod = null; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + // Remember if the script contains Unicode chars, that is needed when generating code for this script object to decide the output file correct encoding. + this.containsUnicodeChar = false; + this.containsUnicodeCharInComment = false; + this.vars = vars; + this.scopes = scopes; + } + Script.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckScript(this); + }; + Script.prototype.treeViewLabel = function () { + return "Script"; + }; + Script.prototype.emitRequired = function () { + if (!this.isDeclareFile && !this.isResident && this.bod) { + for (var i = 0, len = this.bod.members.length; i < len; i++) { + var stmt = this.bod.members[i]; + if (stmt.nodeType == NodeType.ModuleDeclaration) { + if (!hasFlag(stmt.modFlags, ModuleFlags.ShouldEmitModuleDecl | ModuleFlags.Ambient)) { + return true; + } + } + else if (stmt.nodeType == NodeType.ClassDeclaration) { + if (!hasFlag(stmt.varFlags, VarFlags.Ambient)) { + return true; + } + } + else if (stmt.nodeType == NodeType.VarDecl) { + if (!hasFlag(stmt.varFlags, VarFlags.Ambient)) { + return true; + } + } + else if (stmt.nodeType == NodeType.FuncDecl) { + if (!stmt.isSignature()) { + return true; + } + } + else if (stmt.nodeType != NodeType.InterfaceDeclaration && stmt.nodeType != NodeType.Empty) { + return true; + } + } + } + return false; + }; + Script.prototype.emit = function (emitter, tokenId, startLine) { + if (this.emitRequired()) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascriptList(this.bod, null, TokenID.Semicolon, true, false, false, true, this.requiresInherits); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + }; + return Script; + })(FuncDecl); + TypeScript.Script = Script; + var NamedDeclaration = (function (_super) { + __extends(NamedDeclaration, _super); + function NamedDeclaration(nodeType, name, members) { + _super.call(this, nodeType); + this.name = name; + this.members = members; + this.leftCurlyCount = 0; + this.rightCurlyCount = 0; + } + return NamedDeclaration; + })(ModuleElement); + TypeScript.NamedDeclaration = NamedDeclaration; + var ModuleDeclaration = (function (_super) { + __extends(ModuleDeclaration, _super); + function ModuleDeclaration(name, members, vars, scopes, endingToken) { + _super.call(this, NodeType.ModuleDeclaration, name, members); + this.endingToken = endingToken; + this.modFlags = ModuleFlags.ShouldEmitModuleDecl; + this.amdDependencies = []; + // Remember if the module contains Unicode chars, that is needed for dynamic module as we will generate a file for each. + this.containsUnicodeChar = false; + this.containsUnicodeCharInComment = false; + this.vars = vars; + this.scopes = scopes; + this.prettyName = this.name.actualText; + } + ModuleDeclaration.prototype.isExported = function () { + return hasFlag(this.modFlags, ModuleFlags.Exported); + }; + ModuleDeclaration.prototype.isAmbient = function () { + return hasFlag(this.modFlags, ModuleFlags.Ambient); + }; + ModuleDeclaration.prototype.isEnum = function () { + return hasFlag(this.modFlags, ModuleFlags.IsEnum); + }; + ModuleDeclaration.prototype.recordNonInterface = function () { + this.modFlags &= ~ModuleFlags.ShouldEmitModuleDecl; + }; + ModuleDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckModule(this); + }; + ModuleDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + if (!hasFlag(this.modFlags, ModuleFlags.ShouldEmitModuleDecl)) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascriptModule(this); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + } + }; + return ModuleDeclaration; + })(NamedDeclaration); + TypeScript.ModuleDeclaration = ModuleDeclaration; + var TypeDeclaration = (function (_super) { + __extends(TypeDeclaration, _super); + function TypeDeclaration(nodeType, name, extendsList, implementsList, members) { + _super.call(this, nodeType, name, members); + this.extendsList = extendsList; + this.implementsList = implementsList; + this.varFlags = VarFlags.None; + } + TypeDeclaration.prototype.isExported = function () { + return hasFlag(this.varFlags, VarFlags.Exported); + }; + TypeDeclaration.prototype.isAmbient = function () { + return hasFlag(this.varFlags, VarFlags.Ambient); + }; + return TypeDeclaration; + })(NamedDeclaration); + TypeScript.TypeDeclaration = TypeDeclaration; + var ClassDeclaration = (function (_super) { + __extends(ClassDeclaration, _super); + function ClassDeclaration(name, members, extendsList, implementsList) { + _super.call(this, NodeType.ClassDeclaration, name, extendsList, implementsList, members); + this.knownMemberNames = {}; + this.constructorDecl = null; + this.constructorNestingLevel = 0; + this.endingToken = null; + } + ClassDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckClass(this); + }; + ClassDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitJavascriptClass(this); + }; + return ClassDeclaration; + })(TypeDeclaration); + TypeScript.ClassDeclaration = ClassDeclaration; + var InterfaceDeclaration = (function (_super) { + __extends(InterfaceDeclaration, _super); + function InterfaceDeclaration(name, members, extendsList, implementsList) { + _super.call(this, NodeType.InterfaceDeclaration, name, extendsList, implementsList, members); + } + InterfaceDeclaration.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckInterface(this); + }; + InterfaceDeclaration.prototype.emit = function (emitter, tokenId, startLine) { + }; + return InterfaceDeclaration; + })(TypeDeclaration); + TypeScript.InterfaceDeclaration = InterfaceDeclaration; + var Statement = (function (_super) { + __extends(Statement, _super); + function Statement(nodeType) { + _super.call(this, nodeType); + this.flags |= ASTFlags.IsStatement; + } + Statement.prototype.isLoop = function () { + return false; + }; + Statement.prototype.isStatementOrExpression = function () { + return true; + }; + Statement.prototype.isCompoundStatement = function () { + return this.isLoop(); + }; + Statement.prototype.typeCheck = function (typeFlow) { + this.type = typeFlow.voidType; + return this; + }; + return Statement; + })(ModuleElement); + TypeScript.Statement = Statement; + var LabeledStatement = (function (_super) { + __extends(LabeledStatement, _super); + function LabeledStatement(labels, stmt) { + _super.call(this, NodeType.LabeledStatement); + this.labels = labels; + this.stmt = stmt; + } + LabeledStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if (this.labels) { + var labelsLen = this.labels.members.length; + for (var i = 0; i < labelsLen; i++) { + this.labels.members[i].emit(emitter, tokenId, startLine); + } + } + this.stmt.emit(emitter, tokenId, true); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + LabeledStatement.prototype.typeCheck = function (typeFlow) { + typeFlow.typeCheck(this.labels); + this.stmt = this.stmt.typeCheck(typeFlow); + return this; + }; + LabeledStatement.prototype.addToControlFlow = function (context) { + var beforeBB = context.current; + var bb = new BasicBlock(); + context.current = bb; + beforeBB.addSuccessor(bb); + }; + return LabeledStatement; + })(Statement); + TypeScript.LabeledStatement = LabeledStatement; + var Block = (function (_super) { + __extends(Block, _super); + function Block(statements, isStatementBlock) { + _super.call(this, NodeType.Block); + this.statements = statements; + this.isStatementBlock = isStatementBlock; + } + Block.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if (this.isStatementBlock) { + emitter.writeLineToOutput(" {"); + emitter.indenter.increaseIndent(); + } + else { + emitter.setInVarBlock(this.statements.members.length); + } + var temp = emitter.setInObjectLiteral(false); + if (this.statements) { + emitter.emitJavascriptList(this.statements, null, TokenID.Semicolon, true, false, false); + } + if (this.isStatementBlock) { + emitter.indenter.decreaseIndent(); + emitter.emitIndent(); + emitter.writeToOutput("}"); + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Block.prototype.addToControlFlow = function (context) { + var afterIfNeeded = new BasicBlock(); + context.pushStatement(this, context.current, afterIfNeeded); + if (this.statements) { + context.walk(this.statements, this); + } + context.walker.options.goChildren = false; + context.popStatement(); + if (afterIfNeeded.predecessors.length > 0) { + context.current.addSuccessor(afterIfNeeded); + context.current = afterIfNeeded; + } + }; + Block.prototype.typeCheck = function (typeFlow) { + if (!typeFlow.checker.styleSettings.emptyBlocks) { + if ((this.statements === null) || (this.statements.members.length == 0)) { + typeFlow.checker.errorReporter.styleError(this, "empty block"); + } + } + typeFlow.typeCheck(this.statements); + return this; + }; + return Block; + })(Statement); + TypeScript.Block = Block; + var Jump = (function (_super) { + __extends(Jump, _super); + function Jump(nodeType) { + _super.call(this, nodeType); + this.target = null; + this.resolvedTarget = null; + } + Jump.prototype.hasExplicitTarget = function () { + return (this.target); + }; + Jump.prototype.setResolvedTarget = function (parser, stmt) { + if (stmt.isLoop()) { + this.resolvedTarget = stmt; + return true; + } + if (this.nodeType === NodeType.Continue) { + parser.reportParseError("continue statement applies only to loops"); + return false; + } + else { + if ((stmt.nodeType == NodeType.Switch) || this.hasExplicitTarget()) { + this.resolvedTarget = stmt; + return true; + } + else { + parser.reportParseError("break statement with no label can apply only to a loop or switch statement"); + return false; + } + } + }; + Jump.prototype.addToControlFlow = function (context) { + _super.prototype.addToControlFlow.call(this, context); + context.unconditionalBranch(this.resolvedTarget, (this.nodeType == NodeType.Continue)); + }; + Jump.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if (this.nodeType == NodeType.Break) { + emitter.writeToOutput("break"); + } + else { + emitter.writeToOutput("continue"); + } + if (this.hasExplicitTarget()) { + emitter.writeToOutput(" " + this.target); + } + emitter.recordSourceMappingEnd(this); + emitter.writeToOutput(";"); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return Jump; + })(Statement); + TypeScript.Jump = Jump; + var WhileStatement = (function (_super) { + __extends(WhileStatement, _super); + function WhileStatement(cond) { + _super.call(this, NodeType.While); + this.cond = cond; + this.body = null; + } + WhileStatement.prototype.isLoop = function () { + return true; + }; + WhileStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("while("); + emitter.emitJavascript(this.cond, TokenID.While, false); + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, false, false); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + WhileStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckWhile(this); + }; + WhileStatement.prototype.addToControlFlow = function (context) { + var loopHeader = context.current; + var loopStart = new BasicBlock(); + var afterLoop = new BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + context.addContent(this.cond); + var condBlock = context.current; + var targetInfo = null; + if (this.body) { + context.current = new BasicBlock(); + condBlock.addSuccessor(context.current); + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if (!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + } + context.current = afterLoop; + condBlock.addSuccessor(afterLoop); + // TODO: check for while (true) and then only continue if afterLoop has predecessors + context.noContinuation = false; + context.walker.options.goChildren = false; + }; + return WhileStatement; + })(Statement); + TypeScript.WhileStatement = WhileStatement; + var DoWhileStatement = (function (_super) { + __extends(DoWhileStatement, _super); + function DoWhileStatement() { + _super.call(this, NodeType.DoWhile); + this.body = null; + this.whileAST = null; + this.cond = null; + } + DoWhileStatement.prototype.isLoop = function () { + return true; + }; + DoWhileStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("do"); + emitter.emitJavascriptStatements(this.body, true, false); + emitter.recordSourceMappingStart(this.whileAST); + emitter.writeToOutput("while"); + emitter.recordSourceMappingEnd(this.whileAST); + emitter.writeToOutput('('); + emitter.emitJavascript(this.cond, TokenID.CloseParen, false); + emitter.writeToOutput(")"); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + DoWhileStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckDoWhile(this); + }; + DoWhileStatement.prototype.addToControlFlow = function (context) { + var loopHeader = context.current; + var loopStart = new BasicBlock(); + var afterLoop = new BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + var targetInfo = null; + if (this.body) { + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if (!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + context.addContent(this.cond); + // TODO: check for while (true) + context.current = afterLoop; + loopEnd.addSuccessor(afterLoop); + } + else { + context.addUnreachable(this.cond); + } + context.walker.options.goChildren = false; + }; + return DoWhileStatement; + })(Statement); + TypeScript.DoWhileStatement = DoWhileStatement; + var IfStatement = (function (_super) { + __extends(IfStatement, _super); + function IfStatement(cond) { + _super.call(this, NodeType.If); + this.cond = cond; + this.elseBod = null; + this.statement = new ASTSpan(); + } + IfStatement.prototype.isCompoundStatement = function () { + return true; + }; + IfStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("if("); + emitter.emitJavascript(this.cond, TokenID.If, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascriptStatements(this.thenBod, true, false); + if (this.elseBod) { + emitter.writeToOutput(" else"); + emitter.emitJavascriptStatements(this.elseBod, true, true); + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + IfStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckIf(this); + }; + IfStatement.prototype.addToControlFlow = function (context) { + this.cond.addToControlFlow(context); + var afterIf = new BasicBlock(); + var beforeIf = context.current; + context.pushStatement(this, beforeIf, afterIf); + var hasContinuation = false; + context.current = new BasicBlock(); + beforeIf.addSuccessor(context.current); + context.walk(this.thenBod, this); + if (!context.noContinuation) { + hasContinuation = true; + context.current.addSuccessor(afterIf); + } + if (this.elseBod) { + // current block will be thenBod + context.current = new BasicBlock(); + context.noContinuation = false; + beforeIf.addSuccessor(context.current); + context.walk(this.elseBod, this); + if (!context.noContinuation) { + hasContinuation = true; + context.current.addSuccessor(afterIf); + } + else { + // thenBod created continuation for if statement + if (hasContinuation) { + context.noContinuation = false; + } + } + } + else { + beforeIf.addSuccessor(afterIf); + context.noContinuation = false; + hasContinuation = true; + } + var targetInfo = context.popStatement(); + if (afterIf.predecessors.length > 0) { + context.noContinuation = false; + hasContinuation = true; + } + if (hasContinuation) { + context.current = afterIf; + } + context.walker.options.goChildren = false; + }; + return IfStatement; + })(Statement); + TypeScript.IfStatement = IfStatement; + var ReturnStatement = (function (_super) { + __extends(ReturnStatement, _super); + function ReturnStatement() { + _super.call(this, NodeType.Return); + this.returnExpression = null; + } + ReturnStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + if (this.returnExpression) { + emitter.writeToOutput("return "); + emitter.emitJavascript(this.returnExpression, TokenID.Semicolon, false); + } + else { + emitter.writeToOutput("return;"); + } + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + ReturnStatement.prototype.addToControlFlow = function (context) { + _super.prototype.addToControlFlow.call(this, context); + context.returnStmt(); + }; + ReturnStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckReturn(this); + }; + return ReturnStatement; + })(Statement); + TypeScript.ReturnStatement = ReturnStatement; + var EndCode = (function (_super) { + __extends(EndCode, _super); + function EndCode() { + _super.call(this, NodeType.EndCode); + } + return EndCode; + })(AST); + TypeScript.EndCode = EndCode; + var ForInStatement = (function (_super) { + __extends(ForInStatement, _super); + function ForInStatement(lval, obj) { + _super.call(this, NodeType.ForIn); + this.lval = lval; + this.obj = obj; + this.statement = new ASTSpan(); + if (this.lval && (this.lval.nodeType == NodeType.VarDecl)) { + this.lval.varFlags |= VarFlags.AutoInit; + } + } + ForInStatement.prototype.isLoop = function () { + return true; + }; + ForInStatement.prototype.isFiltered = function () { + if (this.body) { + var singleItem = null; + if (this.body.nodeType == NodeType.List) { + var stmts = this.body; + if (stmts.members.length == 1) { + singleItem = stmts.members[0]; + } + } + else { + singleItem = this.body; + } + // match template for filtering 'own' properties from obj + if (singleItem !== null) { + if (singleItem.nodeType == NodeType.Block) { + var block = singleItem; + if ((block.statements !== null) && (block.statements.members.length == 1)) { + singleItem = block.statements.members[0]; + } + } + if (singleItem.nodeType == NodeType.If) { + var cond = singleItem.cond; + if (cond.nodeType == NodeType.Call) { + var target = cond.target; + if (target.nodeType == NodeType.Dot) { + var binex = target; + if ((binex.operand1.nodeType == NodeType.Name) && (this.obj.nodeType == NodeType.Name) && (binex.operand1.actualText == this.obj.actualText)) { + var prop = binex.operand2; + if (prop.actualText == "hasOwnProperty") { + var args = cond.arguments; + if ((args !== null) && (args.members.length == 1)) { + var arg = args.members[0]; + if ((arg.nodeType == NodeType.Name) && (this.lval.nodeType == NodeType.Name)) { + if ((this.lval.actualText) == arg.actualText) { + return true; + } + } + } + } + } + } + } + } + } + } + return false; + }; + ForInStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("for("); + emitter.emitJavascript(this.lval, TokenID.For, false); + emitter.writeToOutput(" in "); + emitter.emitJavascript(this.obj, TokenID.For, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascriptStatements(this.body, true, false); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + ForInStatement.prototype.typeCheck = function (typeFlow) { + if (typeFlow.checker.styleSettings.forin) { + if (!this.isFiltered()) { + typeFlow.checker.errorReporter.styleError(this, "no hasOwnProperty filter"); + } + } + return typeFlow.typeCheckForIn(this); + }; + ForInStatement.prototype.addToControlFlow = function (context) { + if (this.lval) { + context.addContent(this.lval); + } + if (this.obj) { + context.addContent(this.obj); + } + var loopHeader = context.current; + var loopStart = new BasicBlock(); + var afterLoop = new BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + if (this.body) { + context.pushStatement(this, loopStart, afterLoop); + context.walk(this.body, this); + context.popStatement(); + } + if (!(context.noContinuation)) { + var loopEnd = context.current; + loopEnd.addSuccessor(loopStart); + } + context.current = afterLoop; + context.noContinuation = false; + loopHeader.addSuccessor(afterLoop); + context.walker.options.goChildren = false; + }; + return ForInStatement; + })(Statement); + TypeScript.ForInStatement = ForInStatement; + var ForStatement = (function (_super) { + __extends(ForStatement, _super); + function ForStatement(init) { + _super.call(this, NodeType.For); + this.init = init; + } + ForStatement.prototype.isLoop = function () { + return true; + }; + ForStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.writeToOutput("for("); + if (this.init) { + if (this.init.nodeType != NodeType.List) { + emitter.emitJavascript(this.init, TokenID.For, false); + } + else { + emitter.setInVarBlock(this.init.members.length); + emitter.emitJavascriptList(this.init, null, TokenID.For, false, false, false); + } + } + emitter.writeToOutput("; "); + emitter.emitJavascript(this.cond, TokenID.For, false); + emitter.writeToOutput("; "); + emitter.emitJavascript(this.incr, TokenID.For, false); + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, true, false); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + ForStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckFor(this); + }; + ForStatement.prototype.addToControlFlow = function (context) { + if (this.init) { + context.addContent(this.init); + } + var loopHeader = context.current; + var loopStart = new BasicBlock(); + var afterLoop = new BasicBlock(); + loopHeader.addSuccessor(loopStart); + context.current = loopStart; + var condBlock = null; + var continueTarget = loopStart; + var incrBB = null; + if (this.incr) { + incrBB = new BasicBlock(); + continueTarget = incrBB; + } + if (this.cond) { + condBlock = context.current; + context.addContent(this.cond); + context.current = new BasicBlock(); + condBlock.addSuccessor(context.current); + } + var targetInfo = null; + if (this.body) { + context.pushStatement(this, continueTarget, afterLoop); + context.walk(this.body, this); + targetInfo = context.popStatement(); + } + if (this.incr) { + if (context.noContinuation) { + if (incrBB.predecessors.length == 0) { + context.addUnreachable(this.incr); + } + } + else { + context.current.addSuccessor(incrBB); + context.current = incrBB; + context.addContent(this.incr); + } + } + var loopEnd = context.current; + if (!(context.noContinuation)) { + loopEnd.addSuccessor(loopStart); + } + if (condBlock) { + condBlock.addSuccessor(afterLoop); + context.noContinuation = false; + } + if (afterLoop.predecessors.length > 0) { + context.noContinuation = false; + context.current = afterLoop; + } + context.walker.options.goChildren = false; + }; + return ForStatement; + })(Statement); + TypeScript.ForStatement = ForStatement; + var WithStatement = (function (_super) { + __extends(WithStatement, _super); + function WithStatement(expr) { + _super.call(this, NodeType.With); + this.expr = expr; + this.withSym = null; + } + WithStatement.prototype.isCompoundStatement = function () { + return true; + }; + WithStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("with ("); + if (this.expr) { + emitter.emitJavascript(this.expr, TokenID.With, false); + } + emitter.writeToOutput(")"); + emitter.emitJavascriptStatements(this.body, true, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + WithStatement.prototype.typeCheck = function (typeFlow) { + return typeFlow.typeCheckWith(this); + }; + return WithStatement; + })(Statement); + TypeScript.WithStatement = WithStatement; + var SwitchStatement = (function (_super) { + __extends(SwitchStatement, _super); + function SwitchStatement(val) { + _super.call(this, NodeType.Switch); + this.val = val; + this.defaultCase = null; + this.statement = new ASTSpan(); + } + SwitchStatement.prototype.isCompoundStatement = function () { + return true; + }; + SwitchStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + var temp = emitter.setInObjectLiteral(false); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("switch("); + emitter.emitJavascript(this.val, TokenID.Identifier, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.writeLineToOutput(" {"); + emitter.indenter.increaseIndent(); + var casesLen = this.caseList.members.length; + for (var i = 0; i < casesLen; i++) { + var caseExpr = this.caseList.members[i]; + emitter.emitJavascript(caseExpr, TokenID.Case, true); + emitter.writeLineToOutput(""); + } + emitter.indenter.decreaseIndent(); + emitter.emitIndent(); + emitter.writeToOutput("}"); + emitter.setInObjectLiteral(temp); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + SwitchStatement.prototype.typeCheck = function (typeFlow) { + var len = this.caseList.members.length; + this.val = typeFlow.typeCheck(this.val); + for (var i = 0; i < len; i++) { + this.caseList.members[i] = typeFlow.typeCheck(this.caseList.members[i]); + } + this.defaultCase = typeFlow.typeCheck(this.defaultCase); + this.type = typeFlow.voidType; + return this; + }; + // if there are break statements that match this switch, then just link cond block with block after switch + SwitchStatement.prototype.addToControlFlow = function (context) { + var condBlock = context.current; + context.addContent(this.val); + var execBlock = new BasicBlock(); + var afterSwitch = new BasicBlock(); + condBlock.addSuccessor(execBlock); + context.pushSwitch(execBlock); + context.current = execBlock; + context.pushStatement(this, execBlock, afterSwitch); + context.walk(this.caseList, this); + context.popSwitch(); + var targetInfo = context.popStatement(); + var hasCondContinuation = (this.defaultCase == null); + if (this.defaultCase == null) { + condBlock.addSuccessor(afterSwitch); + } + if (afterSwitch.predecessors.length > 0) { + context.noContinuation = false; + context.current = afterSwitch; + } + else { + context.noContinuation = true; + } + context.walker.options.goChildren = false; + }; + return SwitchStatement; + })(Statement); + TypeScript.SwitchStatement = SwitchStatement; + var CaseStatement = (function (_super) { + __extends(CaseStatement, _super); + function CaseStatement() { + _super.call(this, NodeType.Case); + this.expr = null; + } + CaseStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + if (this.expr) { + emitter.writeToOutput("case "); + emitter.emitJavascript(this.expr, TokenID.Identifier, false); + } + else { + emitter.writeToOutput("default"); + } + emitter.writeToOutput(":"); + emitter.emitJavascriptStatements(this.body, false, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + CaseStatement.prototype.typeCheck = function (typeFlow) { + this.expr = typeFlow.typeCheck(this.expr); + typeFlow.typeCheck(this.body); + this.type = typeFlow.voidType; + return this; + }; + // TODO: more reasoning about unreachable cases (such as duplicate literals as case expressions) + // for now, assume all cases are reachable, regardless of whether some cases fall through + CaseStatement.prototype.addToControlFlow = function (context) { + var execBlock = new BasicBlock(); + var sw = context.currentSwitch[context.currentSwitch.length - 1]; + // TODO: fall-through from previous (+ to end of switch) + if (this.expr) { + var exprBlock = new BasicBlock(); + context.current = exprBlock; + sw.addSuccessor(exprBlock); + context.addContent(this.expr); + exprBlock.addSuccessor(execBlock); + } + else { + sw.addSuccessor(execBlock); + } + context.current = execBlock; + if (this.body) { + context.walk(this.body, this); + } + context.noContinuation = false; + context.walker.options.goChildren = false; + }; + return CaseStatement; + })(Statement); + TypeScript.CaseStatement = CaseStatement; + var TypeReference = (function (_super) { + __extends(TypeReference, _super); + function TypeReference(term, arrayCount) { + _super.call(this, NodeType.TypeRef); + this.term = term; + this.arrayCount = arrayCount; + } + TypeReference.prototype.emit = function (emitter, tokenId, startLine) { + throw new Error("should not emit a type ref"); + }; + TypeReference.prototype.typeCheck = function (typeFlow) { + var prevInTCTR = typeFlow.inTypeRefTypeCheck; + typeFlow.inTypeRefTypeCheck = true; + var typeLink = getTypeLink(this, typeFlow.checker, true); + typeFlow.checker.resolveTypeLink(typeFlow.scope, typeLink, false); + if (this.term) { + typeFlow.typeCheck(this.term); + } + typeFlow.checkForVoidConstructor(typeLink.type, this); + this.type = typeLink.type; + // in error recovery cases, there may not be a term + if (this.term) { + this.term.type = this.type; + } + typeFlow.inTypeRefTypeCheck = prevInTCTR; + return this; + }; + return TypeReference; + })(AST); + TypeScript.TypeReference = TypeReference; + var TryFinally = (function (_super) { + __extends(TryFinally, _super); + function TryFinally(tryNode, finallyNode) { + _super.call(this, NodeType.TryFinally); + this.tryNode = tryNode; + this.finallyNode = finallyNode; + } + TryFinally.prototype.isCompoundStatement = function () { + return true; + }; + TryFinally.prototype.emit = function (emitter, tokenId, startLine) { + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.tryNode, TokenID.Try, false); + emitter.emitJavascript(this.finallyNode, TokenID.Finally, false); + emitter.recordSourceMappingEnd(this); + }; + TryFinally.prototype.typeCheck = function (typeFlow) { + this.tryNode = typeFlow.typeCheck(this.tryNode); + this.finallyNode = typeFlow.typeCheck(this.finallyNode); + this.type = typeFlow.voidType; + return this; + }; + TryFinally.prototype.addToControlFlow = function (context) { + var afterFinally = new BasicBlock(); + context.walk(this.tryNode, this); + var finBlock = new BasicBlock(); + if (context.current) { + context.current.addSuccessor(finBlock); + } + context.current = finBlock; + context.pushStatement(this, null, afterFinally); + context.walk(this.finallyNode, this); + if (!context.noContinuation && context.current) { + context.current.addSuccessor(afterFinally); + } + if (afterFinally.predecessors.length > 0) { + context.current = afterFinally; + } + else { + context.noContinuation = true; + } + context.popStatement(); + context.walker.options.goChildren = false; + }; + return TryFinally; + })(Statement); + TypeScript.TryFinally = TryFinally; + var TryCatch = (function (_super) { + __extends(TryCatch, _super); + function TryCatch(tryNode, catchNode) { + _super.call(this, NodeType.TryCatch); + this.tryNode = tryNode; + this.catchNode = catchNode; + } + TryCatch.prototype.isCompoundStatement = function () { + return true; + }; + TryCatch.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.emitJavascript(this.tryNode, TokenID.Try, false); + emitter.emitJavascript(this.catchNode, TokenID.Catch, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + TryCatch.prototype.addToControlFlow = function (context) { + var beforeTry = context.current; + var tryBlock = new BasicBlock(); + beforeTry.addSuccessor(tryBlock); + context.current = tryBlock; + var afterTryCatch = new BasicBlock(); + context.pushStatement(this, null, afterTryCatch); + context.walk(this.tryNode, this); + if (!context.noContinuation) { + if (context.current) { + context.current.addSuccessor(afterTryCatch); + } + } + context.current = new BasicBlock(); + beforeTry.addSuccessor(context.current); + context.walk(this.catchNode, this); + context.popStatement(); + if (!context.noContinuation) { + if (context.current) { + context.current.addSuccessor(afterTryCatch); + } + } + context.current = afterTryCatch; + context.walker.options.goChildren = false; + }; + TryCatch.prototype.typeCheck = function (typeFlow) { + this.tryNode = typeFlow.typeCheck(this.tryNode); + this.catchNode = typeFlow.typeCheck(this.catchNode); + this.type = typeFlow.voidType; + return this; + }; + return TryCatch; + })(Statement); + TypeScript.TryCatch = TryCatch; + var Try = (function (_super) { + __extends(Try, _super); + function Try(body) { + _super.call(this, NodeType.Try); + this.body = body; + } + Try.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("try "); + emitter.emitJavascript(this.body, TokenID.Try, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Try.prototype.typeCheck = function (typeFlow) { + this.body = typeFlow.typeCheck(this.body); + return this; + }; + Try.prototype.addToControlFlow = function (context) { + if (this.body) { + context.walk(this.body, this); + } + context.walker.options.goChildren = false; + context.noContinuation = false; + }; + return Try; + })(Statement); + TypeScript.Try = Try; + var Catch = (function (_super) { + __extends(Catch, _super); + function Catch(param, body) { + _super.call(this, NodeType.Catch); + this.param = param; + this.body = body; + this.statement = new ASTSpan(); + this.containedScope = null; + if (this.param) { + this.param.varFlags |= VarFlags.AutoInit; + } + } + Catch.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput(" "); + emitter.recordSourceMappingStart(this.statement); + emitter.writeToOutput("catch ("); + emitter.emitJavascript(this.param, TokenID.OpenParen, false); + emitter.writeToOutput(")"); + emitter.recordSourceMappingEnd(this.statement); + emitter.emitJavascript(this.body, TokenID.Catch, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Catch.prototype.addToControlFlow = function (context) { + if (this.param) { + context.addContent(this.param); + var bodBlock = new BasicBlock(); + context.current.addSuccessor(bodBlock); + context.current = bodBlock; + } + if (this.body) { + context.walk(this.body, this); + } + context.noContinuation = false; + context.walker.options.goChildren = false; + }; + Catch.prototype.typeCheck = function (typeFlow) { + var prevScope = typeFlow.scope; + typeFlow.scope = this.containedScope; + this.param = typeFlow.typeCheck(this.param); + var exceptVar = new ValueLocation(); + var varSym = new VariableSymbol(this.param.id.text, this.param.minChar, typeFlow.checker.locationInfo.unitIndex, exceptVar); + exceptVar.symbol = varSym; + exceptVar.typeLink = new TypeLink(); + // var type for now (add syntax for type annotation) + exceptVar.typeLink.type = typeFlow.anyType; + var thisFnc = typeFlow.thisFnc; + if (thisFnc && thisFnc.type) { + exceptVar.symbol.container = thisFnc.type.symbol; + } + else { + exceptVar.symbol.container = null; + } + this.param.sym = exceptVar.symbol; + typeFlow.scope.enter(exceptVar.symbol.container, this.param, exceptVar.symbol, typeFlow.checker.errorReporter, false, false, false); + this.body = typeFlow.typeCheck(this.body); + // if we're in provisional typecheck mode, clean up the symbol entry + // REVIEW: This is obviously bad form, since we're counting on the internal + // layout of the symbol table, but this is also the only place where we insert + // symbols during typecheck + if (typeFlow.checker.inProvisionalTypecheckMode()) { + var table = typeFlow.scope.getTable(); + table.secondaryTable.table[exceptVar.symbol.name] = undefined; + } + this.type = typeFlow.voidType; + typeFlow.scope = prevScope; + return this; + }; + return Catch; + })(Statement); + TypeScript.Catch = Catch; + var Finally = (function (_super) { + __extends(Finally, _super); + function Finally(body) { + _super.call(this, NodeType.Finally); + this.body = body; + } + Finally.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeToOutput("finally"); + emitter.emitJavascript(this.body, TokenID.Finally, false); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + Finally.prototype.addToControlFlow = function (context) { + if (this.body) { + context.walk(this.body, this); + } + context.walker.options.goChildren = false; + context.noContinuation = false; + }; + Finally.prototype.typeCheck = function (typeFlow) { + this.body = typeFlow.typeCheck(this.body); + return this; + }; + return Finally; + })(Statement); + TypeScript.Finally = Finally; + var Comment = (function (_super) { + __extends(Comment, _super); + function Comment(content, isBlockComment, endsLine) { + _super.call(this, NodeType.Comment); + this.content = content; + this.isBlockComment = isBlockComment; + this.endsLine = endsLine; + this.text = null; + } + Comment.prototype.getText = function () { + if (this.text == null) { + if (this.isBlockComment) { + this.text = this.content.split("\n"); + for (var i = 0; i < this.text.length; i++) { + this.text[i] = this.text[i].replace(/^\s+|\s+$/g, ''); + } + } + else { + this.text = [(this.content.replace(/^\s+|\s+$/g, ''))]; + } + } + return this.text; + }; + return Comment; + })(AST); + TypeScript.Comment = Comment; + var DebuggerStatement = (function (_super) { + __extends(DebuggerStatement, _super); + function DebuggerStatement() { + _super.call(this, NodeType.Debugger); + } + DebuggerStatement.prototype.emit = function (emitter, tokenId, startLine) { + emitter.emitParensAndCommentsInPlace(this, true); + emitter.recordSourceMappingStart(this); + emitter.writeLineToOutput("debugger;"); + emitter.recordSourceMappingEnd(this); + emitter.emitParensAndCommentsInPlace(this, false); + }; + return DebuggerStatement; + })(Statement); + TypeScript.DebuggerStatement = DebuggerStatement; +})(TypeScript || (TypeScript = {})); diff --git a/tests/baselines/reference/parserRealSource12.js b/tests/baselines/reference/parserRealSource12.js new file mode 100644 index 00000000000..831c121ab08 --- /dev/null +++ b/tests/baselines/reference/parserRealSource12.js @@ -0,0 +1,1032 @@ +//// [parserRealSource12.ts] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. + +/// + +module TypeScript { + export interface IAstWalker { + walk(ast: AST, parent: AST): AST; + options: AstWalkOptions; + state: any; // user state object + } + + export class AstWalkOptions { + public goChildren = true; + public goNextSibling = true; + public reverseSiblings = false; // visit siblings in reverse execution order + + public stopWalk(stop:boolean = true) { + this.goChildren = !stop; + this.goNextSibling = !stop; + } + } + + export interface IAstWalkCallback { + (ast: AST, parent: AST, walker: IAstWalker): AST; + } + + export interface IAstWalkChildren { + (preAst: AST, parent: AST, walker: IAstWalker): void; + } + + class AstWalker implements IAstWalker { + constructor ( + private childrenWalkers: IAstWalkChildren[], + private pre: IAstWalkCallback, + private post: IAstWalkCallback, + public options: AstWalkOptions, + public state: any) { + } + + public walk(ast: AST, parent: AST): AST { + var preAst = this.pre(ast, parent, this); + if (preAst === undefined) { + preAst = ast; + } + if (this.options.goChildren) { + var svGoSib = this.options.goNextSibling; + this.options.goNextSibling = true; + // Call the "walkChildren" function corresponding to "nodeType". + this.childrenWalkers[ast.nodeType](ast, parent, this); + this.options.goNextSibling = svGoSib; + } + else { + // no go only applies to children of node issuing it + this.options.goChildren = true; + } + if (this.post) { + var postAst = this.post(preAst, parent, this); + if (postAst === undefined) { + postAst = preAst; + } + return postAst; + } + else { + return preAst; + } + } + } + + export class AstWalkerFactory { + private childrenWalkers: IAstWalkChildren[] = []; + + constructor () { + this.initChildrenWalkers(); + } + + public walk(ast: AST, pre: IAstWalkCallback, post?: IAstWalkCallback, options?: AstWalkOptions, state?: any): AST { + return this.getWalker(pre, post, options, state).walk(ast, null) + } + + public getWalker(pre: IAstWalkCallback, post?: IAstWalkCallback, options?: AstWalkOptions, state?: any): IAstWalker { + return this.getSlowWalker(pre, post, options, state); + } + + private getSlowWalker(pre: IAstWalkCallback, post?: IAstWalkCallback, options?: AstWalkOptions, state?: any): IAstWalker { + if (!options) { + options = new AstWalkOptions(); + } + + return new AstWalker(this.childrenWalkers, pre, post, options, state); + } + + private initChildrenWalkers(): void { + this.childrenWalkers[NodeType.None] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Empty] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.EmptyExpr] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.True] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.False] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.This] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Super] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.QString] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Regex] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Null] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.ArrayLit] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.ObjectLit] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.Void] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.Comma] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Pos] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.Neg] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.Delete] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.Await] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.In] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Dot] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.From] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Is] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.InstOf] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Typeof] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.NumberLit] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Name] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.TypeRef] = ChildrenWalkers.walkTypeReferenceChildren; + this.childrenWalkers[NodeType.Index] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Call] = ChildrenWalkers.walkCallExpressionChildren; + this.childrenWalkers[NodeType.New] = ChildrenWalkers.walkCallExpressionChildren; + this.childrenWalkers[NodeType.Asg] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgAdd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgSub] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgDiv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgMul] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgMod] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgAnd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgXor] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgOr] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgLsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgRsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgRs2] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.ConditionalExpression] = ChildrenWalkers.walkTrinaryExpressionChildren; + this.childrenWalkers[NodeType.LogOr] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.LogAnd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Or] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Xor] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.And] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Eq] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Ne] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Eqv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.NEqv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Lt] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Le] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Gt] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Ge] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Add] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Sub] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Mul] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Div] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Mod] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Lsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Rsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Rs2] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Not] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.LogNot] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.IncPre] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.DecPre] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.IncPost] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.DecPost] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.TypeAssertion] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.FuncDecl] = ChildrenWalkers.walkFuncDeclChildren; + this.childrenWalkers[NodeType.Member] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.VarDecl] = ChildrenWalkers.walkBoundDeclChildren; + this.childrenWalkers[NodeType.ArgDecl] = ChildrenWalkers.walkBoundDeclChildren; + this.childrenWalkers[NodeType.Return] = ChildrenWalkers.walkReturnStatementChildren; + this.childrenWalkers[NodeType.Break] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Continue] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Throw] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.For] = ChildrenWalkers.walkForStatementChildren; + this.childrenWalkers[NodeType.ForIn] = ChildrenWalkers.walkForInStatementChildren; + this.childrenWalkers[NodeType.If] = ChildrenWalkers.walkIfStatementChildren; + this.childrenWalkers[NodeType.While] = ChildrenWalkers.walkWhileStatementChildren; + this.childrenWalkers[NodeType.DoWhile] = ChildrenWalkers.walkDoWhileStatementChildren; + this.childrenWalkers[NodeType.Block] = ChildrenWalkers.walkBlockChildren; + this.childrenWalkers[NodeType.Case] = ChildrenWalkers.walkCaseStatementChildren; + this.childrenWalkers[NodeType.Switch] = ChildrenWalkers.walkSwitchStatementChildren; + this.childrenWalkers[NodeType.Try] = ChildrenWalkers.walkTryChildren; + this.childrenWalkers[NodeType.TryCatch] = ChildrenWalkers.walkTryCatchChildren; + this.childrenWalkers[NodeType.TryFinally] = ChildrenWalkers.walkTryFinallyChildren; + this.childrenWalkers[NodeType.Finally] = ChildrenWalkers.walkFinallyChildren; + this.childrenWalkers[NodeType.Catch] = ChildrenWalkers.walkCatchChildren; + this.childrenWalkers[NodeType.List] = ChildrenWalkers.walkListChildren; + this.childrenWalkers[NodeType.Script] = ChildrenWalkers.walkScriptChildren; + this.childrenWalkers[NodeType.ClassDeclaration] = ChildrenWalkers.walkClassDeclChildren; + this.childrenWalkers[NodeType.InterfaceDeclaration] = ChildrenWalkers.walkTypeDeclChildren; + this.childrenWalkers[NodeType.ModuleDeclaration] = ChildrenWalkers.walkModuleDeclChildren; + this.childrenWalkers[NodeType.ImportDeclaration] = ChildrenWalkers.walkImportDeclChildren; + this.childrenWalkers[NodeType.With] = ChildrenWalkers.walkWithStatementChildren; + this.childrenWalkers[NodeType.Label] = ChildrenWalkers.walkLabelChildren; + this.childrenWalkers[NodeType.LabeledStatement] = ChildrenWalkers.walkLabeledStatementChildren; + this.childrenWalkers[NodeType.EBStart] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.GotoEB] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.EndCode] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Error] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Comment] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Debugger] = ChildrenWalkers.walkNone; + + // Verify the code is up to date with the enum + for (var e in (NodeType)._map) { + if ((this.childrenWalkers)[e] === undefined) { + throw new Error("initWalkers function is not up to date with enum content!"); + } + } + } + } + + var globalAstWalkerFactory: AstWalkerFactory; + + export function getAstWalkerFactory(): AstWalkerFactory { + if (!globalAstWalkerFactory) { + globalAstWalkerFactory = new AstWalkerFactory(); + } + return globalAstWalkerFactory; + } + + module ChildrenWalkers { + export function walkNone(preAst: ASTList, parent: AST, walker: IAstWalker): void { + // Nothing to do + } + + export function walkListChildren(preAst: ASTList, parent: AST, walker: IAstWalker): void { + var len = preAst.members.length; + if (walker.options.reverseSiblings) { + for (var i = len - 1; i >= 0; i--) { + if (walker.options.goNextSibling) { + preAst.members[i] = walker.walk(preAst.members[i], preAst); + } + } + } + else { + for (var i = 0; i < len; i++) { + if (walker.options.goNextSibling) { + preAst.members[i] = walker.walk(preAst.members[i], preAst); + } + } + } + } + + export function walkUnaryExpressionChildren(preAst: UnaryExpression, parent: AST, walker: IAstWalker): void { + if (preAst.castTerm) { + preAst.castTerm = walker.walk(preAst.castTerm, preAst); + } + if (preAst.operand) { + preAst.operand = walker.walk(preAst.operand, preAst); + } + } + + export function walkBinaryExpressionChildren(preAst: BinaryExpression, parent: AST, walker: IAstWalker): void { + if (walker.options.reverseSiblings) { + if (preAst.operand2) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + if ((preAst.operand1) && (walker.options.goNextSibling)) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + } else { + if (preAst.operand1) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + if ((preAst.operand2) && (walker.options.goNextSibling)) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + } + } + + export function walkTypeReferenceChildren(preAst: TypeReference, parent: AST, walker: IAstWalker): void { + if (preAst.term) { + preAst.term = walker.walk(preAst.term, preAst); + } + } + + export function walkCallExpressionChildren(preAst: CallExpression, parent: AST, walker: IAstWalker): void { + if (!walker.options.reverseSiblings) { + preAst.target = walker.walk(preAst.target, preAst); + } + if (preAst.arguments && (walker.options.goNextSibling)) { + preAst.arguments = walker.walk(preAst.arguments, preAst); + } + if ((walker.options.reverseSiblings) && (walker.options.goNextSibling)) { + preAst.target = walker.walk(preAst.target, preAst); + } + } + + export function walkTrinaryExpressionChildren(preAst: ConditionalExpression, parent: AST, walker: IAstWalker): void { + if (preAst.operand1) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + if (preAst.operand2 && (walker.options.goNextSibling)) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + if (preAst.operand3 && (walker.options.goNextSibling)) { + preAst.operand3 = walker.walk(preAst.operand3, preAst); + } + } + + export function walkFuncDeclChildren(preAst: FuncDecl, parent: AST, walker: IAstWalker): void { + if (preAst.name) { + preAst.name = walker.walk(preAst.name, preAst); + } + if (preAst.arguments && (preAst.arguments.members.length > 0) && (walker.options.goNextSibling)) { + preAst.arguments = walker.walk(preAst.arguments, preAst); + } + if (preAst.returnTypeAnnotation && (walker.options.goNextSibling)) { + preAst.returnTypeAnnotation = walker.walk(preAst.returnTypeAnnotation, preAst); + } + if (preAst.bod && (preAst.bod.members.length > 0) && (walker.options.goNextSibling)) { + preAst.bod = walker.walk(preAst.bod, preAst); + } + } + + export function walkBoundDeclChildren(preAst: BoundDecl, parent: AST, walker: IAstWalker): void { + if (preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + if (preAst.init) { + preAst.init = walker.walk(preAst.init, preAst); + } + if ((preAst.typeExpr) && (walker.options.goNextSibling)) { + preAst.typeExpr = walker.walk(preAst.typeExpr, preAst); + } + } + + export function walkReturnStatementChildren(preAst: ReturnStatement, parent: AST, walker: IAstWalker): void { + if (preAst.returnExpression) { + preAst.returnExpression = walker.walk(preAst.returnExpression, preAst); + } + } + + export function walkForStatementChildren(preAst: ForStatement, parent: AST, walker: IAstWalker): void { + if (preAst.init) { + preAst.init = walker.walk(preAst.init, preAst); + } + + if (preAst.cond && walker.options.goNextSibling) { + preAst.cond = walker.walk(preAst.cond, preAst); + } + + if (preAst.incr && walker.options.goNextSibling) { + preAst.incr = walker.walk(preAst.incr, preAst); + } + + if (preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + + export function walkForInStatementChildren(preAst: ForInStatement, parent: AST, walker: IAstWalker): void { + preAst.lval = walker.walk(preAst.lval, preAst); + if (walker.options.goNextSibling) { + preAst.obj = walker.walk(preAst.obj, preAst); + } + if (preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + + export function walkIfStatementChildren(preAst: IfStatement, parent: AST, walker: IAstWalker): void { + preAst.cond = walker.walk(preAst.cond, preAst); + if (preAst.thenBod && (walker.options.goNextSibling)) { + preAst.thenBod = walker.walk(preAst.thenBod, preAst); + } + if (preAst.elseBod && (walker.options.goNextSibling)) { + preAst.elseBod = walker.walk(preAst.elseBod, preAst); + } + } + + export function walkWhileStatementChildren(preAst: WhileStatement, parent: AST, walker: IAstWalker): void { + preAst.cond = walker.walk(preAst.cond, preAst); + if (preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + + export function walkDoWhileStatementChildren(preAst: DoWhileStatement, parent: AST, walker: IAstWalker): void { + preAst.cond = walker.walk(preAst.cond, preAst); + if (preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + + export function walkBlockChildren(preAst: Block, parent: AST, walker: IAstWalker): void { + if (preAst.statements) { + preAst.statements = walker.walk(preAst.statements, preAst); + } + } + + export function walkCaseStatementChildren(preAst: CaseStatement, parent: AST, walker: IAstWalker): void { + if (preAst.expr) { + preAst.expr = walker.walk(preAst.expr, preAst); + } + + if (preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + + export function walkSwitchStatementChildren(preAst: SwitchStatement, parent: AST, walker: IAstWalker): void { + if (preAst.val) { + preAst.val = walker.walk(preAst.val, preAst); + } + + if ((preAst.caseList) && walker.options.goNextSibling) { + preAst.caseList = walker.walk(preAst.caseList, preAst); + } + } + + export function walkTryChildren(preAst: Try, parent: AST, walker: IAstWalker): void { + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + + export function walkTryCatchChildren(preAst: TryCatch, parent: AST, walker: IAstWalker): void { + if (preAst.tryNode) { + preAst.tryNode = walker.walk(preAst.tryNode, preAst); + } + + if ((preAst.catchNode) && walker.options.goNextSibling) { + preAst.catchNode = walker.walk(preAst.catchNode, preAst); + } + } + + export function walkTryFinallyChildren(preAst: TryFinally, parent: AST, walker: IAstWalker): void { + if (preAst.tryNode) { + preAst.tryNode = walker.walk(preAst.tryNode, preAst); + } + + if (preAst.finallyNode && walker.options.goNextSibling) { + preAst.finallyNode = walker.walk(preAst.finallyNode, preAst); + } + } + + export function walkFinallyChildren(preAst: Finally, parent: AST, walker: IAstWalker): void { + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + + export function walkCatchChildren(preAst: Catch, parent: AST, walker: IAstWalker): void { + if (preAst.param) { + preAst.param = walker.walk(preAst.param, preAst); + } + + if ((preAst.body) && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + + export function walkRecordChildren(preAst: NamedDeclaration, parent: AST, walker: IAstWalker): void { + preAst.name = walker.walk(preAst.name, preAst); + if (walker.options.goNextSibling && preAst.members) { + preAst.members = walker.walk(preAst.members, preAst); + } + + } + + export function walkNamedTypeChildren(preAst: TypeDeclaration, parent: AST, walker: IAstWalker): void { + walkRecordChildren(preAst, parent, walker); + } + + export function walkClassDeclChildren(preAst: ClassDeclaration, parent: AST, walker: IAstWalker): void { + walkNamedTypeChildren(preAst, parent, walker); + + if (walker.options.goNextSibling && preAst.extendsList) { + preAst.extendsList = walker.walk(preAst.extendsList, preAst); + } + + if (walker.options.goNextSibling && preAst.implementsList) { + preAst.implementsList = walker.walk(preAst.implementsList, preAst); + } + } + + export function walkScriptChildren(preAst: Script, parent: AST, walker: IAstWalker): void { + if (preAst.bod) { + preAst.bod = walker.walk(preAst.bod, preAst); + } + } + + export function walkTypeDeclChildren(preAst: InterfaceDeclaration, parent: AST, walker: IAstWalker): void { + walkNamedTypeChildren(preAst, parent, walker); + + // walked arguments as part of members + if (walker.options.goNextSibling && preAst.extendsList) { + preAst.extendsList = walker.walk(preAst.extendsList, preAst); + } + + if (walker.options.goNextSibling && preAst.implementsList) { + preAst.implementsList = walker.walk(preAst.implementsList, preAst); + } + } + + export function walkModuleDeclChildren(preAst: ModuleDeclaration, parent: AST, walker: IAstWalker): void { + walkRecordChildren(preAst, parent, walker); + } + + export function walkImportDeclChildren(preAst: ImportDeclaration, parent: AST, walker: IAstWalker): void { + if (preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + if (preAst.alias) { + preAst.alias = walker.walk(preAst.alias, preAst); + } + } + + export function walkWithStatementChildren(preAst: WithStatement, parent: AST, walker: IAstWalker): void { + if (preAst.expr) { + preAst.expr = walker.walk(preAst.expr, preAst); + } + + if (preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + + export function walkLabelChildren(preAst: Label, parent: AST, walker: IAstWalker): void { + //TODO: Walk "id"? + } + + export function walkLabeledStatementChildren(preAst: LabeledStatement, parent: AST, walker: IAstWalker): void { + preAst.labels = walker.walk(preAst.labels, preAst); + if (walker.options.goNextSibling) { + preAst.stmt = walker.walk(preAst.stmt, preAst); + } + } + } +} + +//// [parserRealSource12.js] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. +/// +var TypeScript; +(function (TypeScript) { + var AstWalkOptions = (function () { + function AstWalkOptions() { + this.goChildren = true; + this.goNextSibling = true; + this.reverseSiblings = false; // visit siblings in reverse execution order + } + AstWalkOptions.prototype.stopWalk = function (stop) { + if (stop === void 0) { stop = true; } + this.goChildren = !stop; + this.goNextSibling = !stop; + }; + return AstWalkOptions; + })(); + TypeScript.AstWalkOptions = AstWalkOptions; + var AstWalker = (function () { + function AstWalker(childrenWalkers, pre, post, options, state) { + this.childrenWalkers = childrenWalkers; + this.pre = pre; + this.post = post; + this.options = options; + this.state = state; + } + AstWalker.prototype.walk = function (ast, parent) { + var preAst = this.pre(ast, parent, this); + if (preAst === undefined) { + preAst = ast; + } + if (this.options.goChildren) { + var svGoSib = this.options.goNextSibling; + this.options.goNextSibling = true; + // Call the "walkChildren" function corresponding to "nodeType". + this.childrenWalkers[ast.nodeType](ast, parent, this); + this.options.goNextSibling = svGoSib; + } + else { + // no go only applies to children of node issuing it + this.options.goChildren = true; + } + if (this.post) { + var postAst = this.post(preAst, parent, this); + if (postAst === undefined) { + postAst = preAst; + } + return postAst; + } + else { + return preAst; + } + }; + return AstWalker; + })(); + var AstWalkerFactory = (function () { + function AstWalkerFactory() { + this.childrenWalkers = []; + this.initChildrenWalkers(); + } + AstWalkerFactory.prototype.walk = function (ast, pre, post, options, state) { + return this.getWalker(pre, post, options, state).walk(ast, null); + }; + AstWalkerFactory.prototype.getWalker = function (pre, post, options, state) { + return this.getSlowWalker(pre, post, options, state); + }; + AstWalkerFactory.prototype.getSlowWalker = function (pre, post, options, state) { + if (!options) { + options = new AstWalkOptions(); + } + return new AstWalker(this.childrenWalkers, pre, post, options, state); + }; + AstWalkerFactory.prototype.initChildrenWalkers = function () { + this.childrenWalkers[NodeType.None] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Empty] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.EmptyExpr] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.True] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.False] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.This] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Super] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.QString] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Regex] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Null] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.ArrayLit] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.ObjectLit] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.Void] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.Comma] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Pos] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.Neg] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.Delete] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.Await] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.In] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Dot] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.From] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Is] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.InstOf] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Typeof] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.NumberLit] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Name] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.TypeRef] = ChildrenWalkers.walkTypeReferenceChildren; + this.childrenWalkers[NodeType.Index] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Call] = ChildrenWalkers.walkCallExpressionChildren; + this.childrenWalkers[NodeType.New] = ChildrenWalkers.walkCallExpressionChildren; + this.childrenWalkers[NodeType.Asg] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgAdd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgSub] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgDiv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgMul] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgMod] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgAnd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgXor] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgOr] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgLsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgRsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.AsgRs2] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.ConditionalExpression] = ChildrenWalkers.walkTrinaryExpressionChildren; + this.childrenWalkers[NodeType.LogOr] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.LogAnd] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Or] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Xor] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.And] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Eq] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Ne] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Eqv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.NEqv] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Lt] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Le] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Gt] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Ge] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Add] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Sub] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Mul] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Div] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Mod] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Lsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Rsh] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Rs2] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.Not] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.LogNot] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.IncPre] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.DecPre] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.IncPost] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.DecPost] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.TypeAssertion] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.FuncDecl] = ChildrenWalkers.walkFuncDeclChildren; + this.childrenWalkers[NodeType.Member] = ChildrenWalkers.walkBinaryExpressionChildren; + this.childrenWalkers[NodeType.VarDecl] = ChildrenWalkers.walkBoundDeclChildren; + this.childrenWalkers[NodeType.ArgDecl] = ChildrenWalkers.walkBoundDeclChildren; + this.childrenWalkers[NodeType.Return] = ChildrenWalkers.walkReturnStatementChildren; + this.childrenWalkers[NodeType.Break] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Continue] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Throw] = ChildrenWalkers.walkUnaryExpressionChildren; + this.childrenWalkers[NodeType.For] = ChildrenWalkers.walkForStatementChildren; + this.childrenWalkers[NodeType.ForIn] = ChildrenWalkers.walkForInStatementChildren; + this.childrenWalkers[NodeType.If] = ChildrenWalkers.walkIfStatementChildren; + this.childrenWalkers[NodeType.While] = ChildrenWalkers.walkWhileStatementChildren; + this.childrenWalkers[NodeType.DoWhile] = ChildrenWalkers.walkDoWhileStatementChildren; + this.childrenWalkers[NodeType.Block] = ChildrenWalkers.walkBlockChildren; + this.childrenWalkers[NodeType.Case] = ChildrenWalkers.walkCaseStatementChildren; + this.childrenWalkers[NodeType.Switch] = ChildrenWalkers.walkSwitchStatementChildren; + this.childrenWalkers[NodeType.Try] = ChildrenWalkers.walkTryChildren; + this.childrenWalkers[NodeType.TryCatch] = ChildrenWalkers.walkTryCatchChildren; + this.childrenWalkers[NodeType.TryFinally] = ChildrenWalkers.walkTryFinallyChildren; + this.childrenWalkers[NodeType.Finally] = ChildrenWalkers.walkFinallyChildren; + this.childrenWalkers[NodeType.Catch] = ChildrenWalkers.walkCatchChildren; + this.childrenWalkers[NodeType.List] = ChildrenWalkers.walkListChildren; + this.childrenWalkers[NodeType.Script] = ChildrenWalkers.walkScriptChildren; + this.childrenWalkers[NodeType.ClassDeclaration] = ChildrenWalkers.walkClassDeclChildren; + this.childrenWalkers[NodeType.InterfaceDeclaration] = ChildrenWalkers.walkTypeDeclChildren; + this.childrenWalkers[NodeType.ModuleDeclaration] = ChildrenWalkers.walkModuleDeclChildren; + this.childrenWalkers[NodeType.ImportDeclaration] = ChildrenWalkers.walkImportDeclChildren; + this.childrenWalkers[NodeType.With] = ChildrenWalkers.walkWithStatementChildren; + this.childrenWalkers[NodeType.Label] = ChildrenWalkers.walkLabelChildren; + this.childrenWalkers[NodeType.LabeledStatement] = ChildrenWalkers.walkLabeledStatementChildren; + this.childrenWalkers[NodeType.EBStart] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.GotoEB] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.EndCode] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Error] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Comment] = ChildrenWalkers.walkNone; + this.childrenWalkers[NodeType.Debugger] = ChildrenWalkers.walkNone; + // Verify the code is up to date with the enum + for (var e in NodeType._map) { + if (this.childrenWalkers[e] === undefined) { + throw new Error("initWalkers function is not up to date with enum content!"); + } + } + }; + return AstWalkerFactory; + })(); + TypeScript.AstWalkerFactory = AstWalkerFactory; + var globalAstWalkerFactory; + function getAstWalkerFactory() { + if (!globalAstWalkerFactory) { + globalAstWalkerFactory = new AstWalkerFactory(); + } + return globalAstWalkerFactory; + } + TypeScript.getAstWalkerFactory = getAstWalkerFactory; + var ChildrenWalkers; + (function (ChildrenWalkers) { + function walkNone(preAst, parent, walker) { + // Nothing to do + } + ChildrenWalkers.walkNone = walkNone; + function walkListChildren(preAst, parent, walker) { + var len = preAst.members.length; + if (walker.options.reverseSiblings) { + for (var i = len - 1; i >= 0; i--) { + if (walker.options.goNextSibling) { + preAst.members[i] = walker.walk(preAst.members[i], preAst); + } + } + } + else { + for (var i = 0; i < len; i++) { + if (walker.options.goNextSibling) { + preAst.members[i] = walker.walk(preAst.members[i], preAst); + } + } + } + } + ChildrenWalkers.walkListChildren = walkListChildren; + function walkUnaryExpressionChildren(preAst, parent, walker) { + if (preAst.castTerm) { + preAst.castTerm = walker.walk(preAst.castTerm, preAst); + } + if (preAst.operand) { + preAst.operand = walker.walk(preAst.operand, preAst); + } + } + ChildrenWalkers.walkUnaryExpressionChildren = walkUnaryExpressionChildren; + function walkBinaryExpressionChildren(preAst, parent, walker) { + if (walker.options.reverseSiblings) { + if (preAst.operand2) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + if ((preAst.operand1) && (walker.options.goNextSibling)) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + } + else { + if (preAst.operand1) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + if ((preAst.operand2) && (walker.options.goNextSibling)) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + } + } + ChildrenWalkers.walkBinaryExpressionChildren = walkBinaryExpressionChildren; + function walkTypeReferenceChildren(preAst, parent, walker) { + if (preAst.term) { + preAst.term = walker.walk(preAst.term, preAst); + } + } + ChildrenWalkers.walkTypeReferenceChildren = walkTypeReferenceChildren; + function walkCallExpressionChildren(preAst, parent, walker) { + if (!walker.options.reverseSiblings) { + preAst.target = walker.walk(preAst.target, preAst); + } + if (preAst.arguments && (walker.options.goNextSibling)) { + preAst.arguments = walker.walk(preAst.arguments, preAst); + } + if ((walker.options.reverseSiblings) && (walker.options.goNextSibling)) { + preAst.target = walker.walk(preAst.target, preAst); + } + } + ChildrenWalkers.walkCallExpressionChildren = walkCallExpressionChildren; + function walkTrinaryExpressionChildren(preAst, parent, walker) { + if (preAst.operand1) { + preAst.operand1 = walker.walk(preAst.operand1, preAst); + } + if (preAst.operand2 && (walker.options.goNextSibling)) { + preAst.operand2 = walker.walk(preAst.operand2, preAst); + } + if (preAst.operand3 && (walker.options.goNextSibling)) { + preAst.operand3 = walker.walk(preAst.operand3, preAst); + } + } + ChildrenWalkers.walkTrinaryExpressionChildren = walkTrinaryExpressionChildren; + function walkFuncDeclChildren(preAst, parent, walker) { + if (preAst.name) { + preAst.name = walker.walk(preAst.name, preAst); + } + if (preAst.arguments && (preAst.arguments.members.length > 0) && (walker.options.goNextSibling)) { + preAst.arguments = walker.walk(preAst.arguments, preAst); + } + if (preAst.returnTypeAnnotation && (walker.options.goNextSibling)) { + preAst.returnTypeAnnotation = walker.walk(preAst.returnTypeAnnotation, preAst); + } + if (preAst.bod && (preAst.bod.members.length > 0) && (walker.options.goNextSibling)) { + preAst.bod = walker.walk(preAst.bod, preAst); + } + } + ChildrenWalkers.walkFuncDeclChildren = walkFuncDeclChildren; + function walkBoundDeclChildren(preAst, parent, walker) { + if (preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + if (preAst.init) { + preAst.init = walker.walk(preAst.init, preAst); + } + if ((preAst.typeExpr) && (walker.options.goNextSibling)) { + preAst.typeExpr = walker.walk(preAst.typeExpr, preAst); + } + } + ChildrenWalkers.walkBoundDeclChildren = walkBoundDeclChildren; + function walkReturnStatementChildren(preAst, parent, walker) { + if (preAst.returnExpression) { + preAst.returnExpression = walker.walk(preAst.returnExpression, preAst); + } + } + ChildrenWalkers.walkReturnStatementChildren = walkReturnStatementChildren; + function walkForStatementChildren(preAst, parent, walker) { + if (preAst.init) { + preAst.init = walker.walk(preAst.init, preAst); + } + if (preAst.cond && walker.options.goNextSibling) { + preAst.cond = walker.walk(preAst.cond, preAst); + } + if (preAst.incr && walker.options.goNextSibling) { + preAst.incr = walker.walk(preAst.incr, preAst); + } + if (preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkForStatementChildren = walkForStatementChildren; + function walkForInStatementChildren(preAst, parent, walker) { + preAst.lval = walker.walk(preAst.lval, preAst); + if (walker.options.goNextSibling) { + preAst.obj = walker.walk(preAst.obj, preAst); + } + if (preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkForInStatementChildren = walkForInStatementChildren; + function walkIfStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if (preAst.thenBod && (walker.options.goNextSibling)) { + preAst.thenBod = walker.walk(preAst.thenBod, preAst); + } + if (preAst.elseBod && (walker.options.goNextSibling)) { + preAst.elseBod = walker.walk(preAst.elseBod, preAst); + } + } + ChildrenWalkers.walkIfStatementChildren = walkIfStatementChildren; + function walkWhileStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if (preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkWhileStatementChildren = walkWhileStatementChildren; + function walkDoWhileStatementChildren(preAst, parent, walker) { + preAst.cond = walker.walk(preAst.cond, preAst); + if (preAst.body && (walker.options.goNextSibling)) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkDoWhileStatementChildren = walkDoWhileStatementChildren; + function walkBlockChildren(preAst, parent, walker) { + if (preAst.statements) { + preAst.statements = walker.walk(preAst.statements, preAst); + } + } + ChildrenWalkers.walkBlockChildren = walkBlockChildren; + function walkCaseStatementChildren(preAst, parent, walker) { + if (preAst.expr) { + preAst.expr = walker.walk(preAst.expr, preAst); + } + if (preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkCaseStatementChildren = walkCaseStatementChildren; + function walkSwitchStatementChildren(preAst, parent, walker) { + if (preAst.val) { + preAst.val = walker.walk(preAst.val, preAst); + } + if ((preAst.caseList) && walker.options.goNextSibling) { + preAst.caseList = walker.walk(preAst.caseList, preAst); + } + } + ChildrenWalkers.walkSwitchStatementChildren = walkSwitchStatementChildren; + function walkTryChildren(preAst, parent, walker) { + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkTryChildren = walkTryChildren; + function walkTryCatchChildren(preAst, parent, walker) { + if (preAst.tryNode) { + preAst.tryNode = walker.walk(preAst.tryNode, preAst); + } + if ((preAst.catchNode) && walker.options.goNextSibling) { + preAst.catchNode = walker.walk(preAst.catchNode, preAst); + } + } + ChildrenWalkers.walkTryCatchChildren = walkTryCatchChildren; + function walkTryFinallyChildren(preAst, parent, walker) { + if (preAst.tryNode) { + preAst.tryNode = walker.walk(preAst.tryNode, preAst); + } + if (preAst.finallyNode && walker.options.goNextSibling) { + preAst.finallyNode = walker.walk(preAst.finallyNode, preAst); + } + } + ChildrenWalkers.walkTryFinallyChildren = walkTryFinallyChildren; + function walkFinallyChildren(preAst, parent, walker) { + if (preAst.body) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkFinallyChildren = walkFinallyChildren; + function walkCatchChildren(preAst, parent, walker) { + if (preAst.param) { + preAst.param = walker.walk(preAst.param, preAst); + } + if ((preAst.body) && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkCatchChildren = walkCatchChildren; + function walkRecordChildren(preAst, parent, walker) { + preAst.name = walker.walk(preAst.name, preAst); + if (walker.options.goNextSibling && preAst.members) { + preAst.members = walker.walk(preAst.members, preAst); + } + } + ChildrenWalkers.walkRecordChildren = walkRecordChildren; + function walkNamedTypeChildren(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker); + } + ChildrenWalkers.walkNamedTypeChildren = walkNamedTypeChildren; + function walkClassDeclChildren(preAst, parent, walker) { + walkNamedTypeChildren(preAst, parent, walker); + if (walker.options.goNextSibling && preAst.extendsList) { + preAst.extendsList = walker.walk(preAst.extendsList, preAst); + } + if (walker.options.goNextSibling && preAst.implementsList) { + preAst.implementsList = walker.walk(preAst.implementsList, preAst); + } + } + ChildrenWalkers.walkClassDeclChildren = walkClassDeclChildren; + function walkScriptChildren(preAst, parent, walker) { + if (preAst.bod) { + preAst.bod = walker.walk(preAst.bod, preAst); + } + } + ChildrenWalkers.walkScriptChildren = walkScriptChildren; + function walkTypeDeclChildren(preAst, parent, walker) { + walkNamedTypeChildren(preAst, parent, walker); + // walked arguments as part of members + if (walker.options.goNextSibling && preAst.extendsList) { + preAst.extendsList = walker.walk(preAst.extendsList, preAst); + } + if (walker.options.goNextSibling && preAst.implementsList) { + preAst.implementsList = walker.walk(preAst.implementsList, preAst); + } + } + ChildrenWalkers.walkTypeDeclChildren = walkTypeDeclChildren; + function walkModuleDeclChildren(preAst, parent, walker) { + walkRecordChildren(preAst, parent, walker); + } + ChildrenWalkers.walkModuleDeclChildren = walkModuleDeclChildren; + function walkImportDeclChildren(preAst, parent, walker) { + if (preAst.id) { + preAst.id = walker.walk(preAst.id, preAst); + } + if (preAst.alias) { + preAst.alias = walker.walk(preAst.alias, preAst); + } + } + ChildrenWalkers.walkImportDeclChildren = walkImportDeclChildren; + function walkWithStatementChildren(preAst, parent, walker) { + if (preAst.expr) { + preAst.expr = walker.walk(preAst.expr, preAst); + } + if (preAst.body && walker.options.goNextSibling) { + preAst.body = walker.walk(preAst.body, preAst); + } + } + ChildrenWalkers.walkWithStatementChildren = walkWithStatementChildren; + function walkLabelChildren(preAst, parent, walker) { + //TODO: Walk "id"? + } + ChildrenWalkers.walkLabelChildren = walkLabelChildren; + function walkLabeledStatementChildren(preAst, parent, walker) { + preAst.labels = walker.walk(preAst.labels, preAst); + if (walker.options.goNextSibling) { + preAst.stmt = walker.walk(preAst.stmt, preAst); + } + } + ChildrenWalkers.walkLabeledStatementChildren = walkLabeledStatementChildren; + })(ChildrenWalkers || (ChildrenWalkers = {})); +})(TypeScript || (TypeScript = {})); diff --git a/tests/baselines/reference/parserRealSource13.js b/tests/baselines/reference/parserRealSource13.js new file mode 100644 index 00000000000..7c1ecdc7372 --- /dev/null +++ b/tests/baselines/reference/parserRealSource13.js @@ -0,0 +1,183 @@ +//// [parserRealSource13.ts] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. + +/// + +module TypeScript.AstWalkerWithDetailCallback { + export interface AstWalkerDetailCallback { + EmptyCallback? (pre, ast: AST): boolean; + EmptyExprCallback? (pre, ast: AST): boolean; + TrueCallback? (pre, ast: AST): boolean; + FalseCallback? (pre, ast: AST): boolean; + ThisCallback? (pre, ast: AST): boolean; + SuperCallback? (pre, ast: AST): boolean; + QStringCallback? (pre, ast: AST): boolean; + RegexCallback? (pre, ast: AST): boolean; + NullCallback? (pre, ast: AST): boolean; + ArrayLitCallback? (pre, ast: AST): boolean; + ObjectLitCallback? (pre, ast: AST): boolean; + VoidCallback? (pre, ast: AST): boolean; + CommaCallback? (pre, ast: AST): boolean; + PosCallback? (pre, ast: AST): boolean; + NegCallback? (pre, ast: AST): boolean; + DeleteCallback? (pre, ast: AST): boolean; + AwaitCallback? (pre, ast: AST): boolean; + InCallback? (pre, ast: AST): boolean; + DotCallback? (pre, ast: AST): boolean; + FromCallback? (pre, ast: AST): boolean; + IsCallback? (pre, ast: AST): boolean; + InstOfCallback? (pre, ast: AST): boolean; + TypeofCallback? (pre, ast: AST): boolean; + NumberLitCallback? (pre, ast: AST): boolean; + NameCallback? (pre, identifierAst: Identifier): boolean; + TypeRefCallback? (pre, ast: AST): boolean; + IndexCallback? (pre, ast: AST): boolean; + CallCallback? (pre, ast: AST): boolean; + NewCallback? (pre, ast: AST): boolean; + AsgCallback? (pre, ast: AST): boolean; + AsgAddCallback? (pre, ast: AST): boolean; + AsgSubCallback? (pre, ast: AST): boolean; + AsgDivCallback? (pre, ast: AST): boolean; + AsgMulCallback? (pre, ast: AST): boolean; + AsgModCallback? (pre, ast: AST): boolean; + AsgAndCallback? (pre, ast: AST): boolean; + AsgXorCallback? (pre, ast: AST): boolean; + AsgOrCallback? (pre, ast: AST): boolean; + AsgLshCallback? (pre, ast: AST): boolean; + AsgRshCallback? (pre, ast: AST): boolean; + AsgRs2Callback? (pre, ast: AST): boolean; + QMarkCallback? (pre, ast: AST): boolean; + LogOrCallback? (pre, ast: AST): boolean; + LogAndCallback? (pre, ast: AST): boolean; + OrCallback? (pre, ast: AST): boolean; + XorCallback? (pre, ast: AST): boolean; + AndCallback? (pre, ast: AST): boolean; + EqCallback? (pre, ast: AST): boolean; + NeCallback? (pre, ast: AST): boolean; + EqvCallback? (pre, ast: AST): boolean; + NEqvCallback? (pre, ast: AST): boolean; + LtCallback? (pre, ast: AST): boolean; + LeCallback? (pre, ast: AST): boolean; + GtCallback? (pre, ast: AST): boolean; + GeCallback? (pre, ast: AST): boolean; + AddCallback? (pre, ast: AST): boolean; + SubCallback? (pre, ast: AST): boolean; + MulCallback? (pre, ast: AST): boolean; + DivCallback? (pre, ast: AST): boolean; + ModCallback? (pre, ast: AST): boolean; + LshCallback? (pre, ast: AST): boolean; + RshCallback? (pre, ast: AST): boolean; + Rs2Callback? (pre, ast: AST): boolean; + NotCallback? (pre, ast: AST): boolean; + LogNotCallback? (pre, ast: AST): boolean; + IncPreCallback? (pre, ast: AST): boolean; + DecPreCallback? (pre, ast: AST): boolean; + IncPostCallback? (pre, ast: AST): boolean; + DecPostCallback? (pre, ast: AST): boolean; + TypeAssertionCallback? (pre, ast: AST): boolean; + FuncDeclCallback? (pre, funcDecl: FuncDecl): boolean; + MemberCallback? (pre, ast: AST): boolean; + VarDeclCallback? (pre, varDecl: VarDecl): boolean; + ArgDeclCallback? (pre, ast: AST): boolean; + ReturnCallback? (pre, ast: AST): boolean; + BreakCallback? (pre, ast: AST): boolean; + ContinueCallback? (pre, ast: AST): boolean; + ThrowCallback? (pre, ast: AST): boolean; + ForCallback? (pre, ast: AST): boolean; + ForInCallback? (pre, ast: AST): boolean; + IfCallback? (pre, ast: AST): boolean; + WhileCallback? (pre, ast: AST): boolean; + DoWhileCallback? (pre, ast: AST): boolean; + BlockCallback? (pre, block: Block): boolean; + CaseCallback? (pre, ast: AST): boolean; + SwitchCallback? (pre, ast: AST): boolean; + TryCallback? (pre, ast: AST): boolean; + TryCatchCallback? (pre, ast: AST): boolean; + TryFinallyCallback? (pre, ast: AST): boolean; + FinallyCallback? (pre, ast: AST): boolean; + CatchCallback? (pre, ast: AST): boolean; + ListCallback? (pre, astList: ASTList): boolean; + ScriptCallback? (pre, script: Script): boolean; + ClassDeclarationCallback? (pre, ast: AST): boolean; + InterfaceDeclarationCallback? (pre, interfaceDecl: InterfaceDeclaration): boolean; + ModuleDeclarationCallback? (pre, moduleDecl: ModuleDeclaration): boolean; + ImportDeclarationCallback? (pre, ast: AST): boolean; + WithCallback? (pre, ast: AST): boolean; + LabelCallback? (pre, labelAST: AST): boolean; + LabeledStatementCallback? (pre, ast: AST): boolean; + EBStartCallback? (pre, ast: AST): boolean; + GotoEBCallback? (pre, ast: AST): boolean; + EndCodeCallback? (pre, ast: AST): boolean; + ErrorCallback? (pre, ast: AST): boolean; + CommentCallback? (pre, ast: AST): boolean; + DebuggerCallback? (pre, ast: AST): boolean; + DefaultCallback? (pre, ast: AST): boolean; + } + + export function walk(script: Script, callback: AstWalkerDetailCallback): void { + var pre = (cur: AST, parent: AST) => { + walker.options.goChildren = AstWalkerCallback(true, cur, callback); + return cur; + } + + var post = (cur: AST, parent: AST) => { + AstWalkerCallback(false, cur, callback); + return cur; + } + + var walker = TypeScript.getAstWalkerFactory().getWalker(pre, post); + walker.walk(script, null); + } + + function AstWalkerCallback(pre: boolean, ast: AST, callback: AstWalkerDetailCallback): boolean { + // See if the Callback needs to be handled using specific one or default one + var nodeType = ast.nodeType; + var callbackString = (NodeType)._map[nodeType] + "Callback"; + if (callback[callbackString]) { + return callback[callbackString](pre, ast); + } + + if (callback.DefaultCallback) { + return callback.DefaultCallback(pre, ast); + } + + return true; + } +} + +//// [parserRealSource13.js] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. +/// +var TypeScript; +(function (TypeScript) { + var AstWalkerWithDetailCallback; + (function (AstWalkerWithDetailCallback) { + function walk(script, callback) { + var pre = function (cur, parent) { + walker.options.goChildren = AstWalkerCallback(true, cur, callback); + return cur; + }; + var post = function (cur, parent) { + AstWalkerCallback(false, cur, callback); + return cur; + }; + var walker = TypeScript.getAstWalkerFactory().getWalker(pre, post); + walker.walk(script, null); + } + AstWalkerWithDetailCallback.walk = walk; + function AstWalkerCallback(pre, ast, callback) { + // See if the Callback needs to be handled using specific one or default one + var nodeType = ast.nodeType; + var callbackString = NodeType._map[nodeType] + "Callback"; + if (callback[callbackString]) { + return callback[callbackString](pre, ast); + } + if (callback.DefaultCallback) { + return callback.DefaultCallback(pre, ast); + } + return true; + } + })(AstWalkerWithDetailCallback = TypeScript.AstWalkerWithDetailCallback || (TypeScript.AstWalkerWithDetailCallback = {})); +})(TypeScript || (TypeScript = {})); diff --git a/tests/baselines/reference/parserRealSource14.js b/tests/baselines/reference/parserRealSource14.js new file mode 100644 index 00000000000..9b9ee2bcf84 --- /dev/null +++ b/tests/baselines/reference/parserRealSource14.js @@ -0,0 +1,956 @@ +//// [parserRealSource14.ts] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. + +/// + +module TypeScript { + export function lastOf(items: any[]): any { + return (items === null || items.length === 0) ? null : items[items.length - 1]; + } + + export function max(a: number, b: number): number { + return a >= b ? a : b; + } + + export function min(a: number, b: number): number { + return a <= b ? a : b; + } + + // + // Helper class representing a path from a root ast node to a (grand)child ast node. + // This is helpful as our tree don't have parents. + // + export class AstPath { + public asts: TypeScript.AST[] = []; + public top: number = -1; + + static reverseIndexOf(items: any[], index: number): any { + return (items === null || items.length <= index) ? null : items[items.length - index - 1]; + } + + public clone(): AstPath { + var clone = new AstPath(); + clone.asts = this.asts.map((value) => { return value; }); + clone.top = this.top; + return clone; + } + + public pop(): TypeScript.AST { + var head = this.ast(); + this.up(); + + while (this.asts.length > this.count()) { + this.asts.pop(); + } + return head; + } + + public push(ast: TypeScript.AST) { + while (this.asts.length > this.count()) { + this.asts.pop(); + } + this.top = this.asts.length; + this.asts.push(ast); + } + + public up() { + if (this.top <= -1) + throw new Error("Invalid call to 'up'"); + this.top--; + } + + public down() { + if (this.top == this.ast.length - 1) + throw new Error("Invalid call to 'down'"); + this.top++; + } + + public nodeType(): TypeScript.NodeType { + if (this.ast() == null) + return TypeScript.NodeType.None; + return this.ast().nodeType; + } + + public ast() { + return AstPath.reverseIndexOf(this.asts, this.asts.length - (this.top + 1)); + } + + public parent() { + return AstPath.reverseIndexOf(this.asts, this.asts.length - this.top); + } + + public count() { + return this.top + 1; + } + + public get(index: number): TypeScript.AST { + return this.asts[index]; + } + + public isNameOfClass(): boolean { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === TypeScript.NodeType.Name) && + (this.parent().nodeType === TypeScript.NodeType.ClassDeclaration) && + ((this.parent()).name === this.ast()); + } + + public isNameOfInterface(): boolean { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === TypeScript.NodeType.Name) && + (this.parent().nodeType === TypeScript.NodeType.InterfaceDeclaration) && + ((this.parent()).name === this.ast()); + } + + public isNameOfArgument(): boolean { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === TypeScript.NodeType.Name) && + (this.parent().nodeType === TypeScript.NodeType.ArgDecl) && + ((this.parent()).id === this.ast()); + } + + public isNameOfVariable(): boolean { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === TypeScript.NodeType.Name) && + (this.parent().nodeType === TypeScript.NodeType.VarDecl) && + ((this.parent()).id === this.ast()); + } + + public isNameOfModule(): boolean { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === TypeScript.NodeType.Name) && + (this.parent().nodeType === TypeScript.NodeType.ModuleDeclaration) && + ((this.parent()).name === this.ast()); + } + + public isNameOfFunction(): boolean { + if (this.ast() === null || this.parent() === null) + return false; + + return (this.ast().nodeType === TypeScript.NodeType.Name) && + (this.parent().nodeType === TypeScript.NodeType.FuncDecl) && + ((this.parent()).name === this.ast()); + } + + public isChildOfScript(): boolean { + var ast = lastOf(this.asts); + return this.count() >= 3 && + this.asts[this.top] === ast && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && + this.asts[this.top - 2].nodeType === TypeScript.NodeType.Script; + } + + public isChildOfModule(): boolean { + var ast = lastOf(this.asts); + return this.count() >= 3 && + this.asts[this.top] === ast && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && + this.asts[this.top - 2].nodeType === TypeScript.NodeType.ModuleDeclaration; + } + + public isChildOfClass(): boolean { + var ast = lastOf(this.asts); + return this.count() >= 3 && + this.asts[this.top] === ast && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && + this.asts[this.top - 2].nodeType === TypeScript.NodeType.ClassDeclaration; + } + + public isArgumentOfClassConstructor(): boolean { + var ast = lastOf(this.asts); + return this.count() >= 5 && + this.asts[this.top] === ast && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && + this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && + this.asts[this.top - 3].nodeType === TypeScript.NodeType.List && + this.asts[this.top - 4].nodeType === TypeScript.NodeType.ClassDeclaration && + ((this.asts[this.top - 2]).isConstructor) && + ((this.asts[this.top - 2]).arguments === this.asts[this.top - 1]) && + ((this.asts[this.top - 4]).constructorDecl === this.asts[this.top - 2]); + } + + public isChildOfInterface(): boolean { + var ast = lastOf(this.asts); + return this.count() >= 3 && + this.asts[this.top] === ast && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && + this.asts[this.top - 2].nodeType === TypeScript.NodeType.InterfaceDeclaration; + } + + public isTopLevelImplicitModule() { + return this.count() >= 1 && + this.asts[this.top].nodeType === TypeScript.NodeType.ModuleDeclaration && + TypeScript.hasFlag((this.asts[this.top]).modFlags, TypeScript.ModuleFlags.IsWholeFile); + } + + public isBodyOfTopLevelImplicitModule() { + return this.count() >= 2 && + this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && + (this.asts[this.top - 1]).members == this.asts[this.top - 0] && + TypeScript.hasFlag((this.asts[this.top - 1]).modFlags, TypeScript.ModuleFlags.IsWholeFile); + } + + public isBodyOfScript(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.Script && + (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; + } + + public isBodyOfSwitch(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.Switch && + (this.asts[this.top - 1]).caseList == this.asts[this.top - 0]; + } + + public isBodyOfModule(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && + (this.asts[this.top - 1]).members == this.asts[this.top - 0]; + } + + public isBodyOfClass(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.ClassDeclaration && + (this.asts[this.top - 1]).members == this.asts[this.top - 0]; + } + + public isBodyOfFunction(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && + (this.asts[this.top - 1]).bod == this.asts[this.top - 0]; + } + + public isBodyOfInterface(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.InterfaceDeclaration && + (this.asts[this.top - 1]).members == this.asts[this.top - 0]; + } + + public isBodyOfBlock(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.Block && + (this.asts[this.top - 1]).statements == this.asts[this.top - 0]; + } + + public isBodyOfFor(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.For && + (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + } + + public isBodyOfCase(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.Case && + (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + } + + public isBodyOfTry(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.Try && + (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + } + + public isBodyOfCatch(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.Catch && + (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + } + + public isBodyOfDoWhile(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.DoWhile && + (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + } + + public isBodyOfWhile(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.While && + (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + } + + public isBodyOfForIn(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.ForIn && + (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + } + + public isBodyOfWith(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.With && + (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + } + + public isBodyOfFinally(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.Finally && + (this.asts[this.top - 1]).body == this.asts[this.top - 0]; + } + + public isCaseOfSwitch(): boolean { + return this.count() >= 3 && + this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && + (this.asts[this.top - 2]).caseList == this.asts[this.top - 1]; + } + + public isDefaultCaseOfSwitch(): boolean { + return this.count() >= 3 && + this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && + (this.asts[this.top - 2]).caseList == this.asts[this.top - 1] && + (this.asts[this.top - 2]).defaultCase == this.asts[this.top - 0]; + } + + public isListOfObjectLit(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && + this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && + (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; + } + + public isBodyOfObjectLit(): boolean { + return this.isListOfObjectLit(); + } + + public isEmptyListOfObjectLit(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && + this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && + (this.asts[this.top - 1]).operand == this.asts[this.top - 0] && + (this.asts[this.top - 0]).members.length == 0; + } + + public isMemberOfObjectLit(): boolean { + return this.count() >= 3 && + this.asts[this.top - 2].nodeType === TypeScript.NodeType.ObjectLit && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && + this.asts[this.top - 0].nodeType === TypeScript.NodeType.Member && + (this.asts[this.top - 2]).operand == this.asts[this.top - 1]; + } + + public isNameOfMemberOfObjectLit(): boolean { + return this.count() >= 4 && + this.asts[this.top - 3].nodeType === TypeScript.NodeType.ObjectLit && + this.asts[this.top - 2].nodeType === TypeScript.NodeType.List && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && + this.asts[this.top - 0].nodeType === TypeScript.NodeType.Name && + (this.asts[this.top - 3]).operand == this.asts[this.top - 2]; + } + + public isListOfArrayLit(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.ArrayLit && + this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && + (this.asts[this.top - 1]).operand == this.asts[this.top - 0]; + } + + public isTargetOfMember(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && + (this.asts[this.top - 1]).operand1 === this.asts[this.top - 0]; + } + + public isMemberOfMember(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && + (this.asts[this.top - 1]).operand2 === this.asts[this.top - 0]; + } + + public isItemOfList(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.List; + //(this.asts[this.top - 1]).operand2 === this.asts[this.top - 0]; + } + + public isThenOfIf(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && + (this.asts[this.top - 1]).thenBod == this.asts[this.top - 0]; + } + + public isElseOfIf(): boolean { + return this.count() >= 2 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && + (this.asts[this.top - 1]).elseBod == this.asts[this.top - 0]; + } + + public isBodyOfDefaultCase(): boolean { + return this.isBodyOfCase(); + } + + public isSingleStatementList(): boolean { + return this.count() >= 1 && + this.asts[this.top].nodeType === TypeScript.NodeType.List && + (this.asts[this.top]).members.length === 1; + } + + public isArgumentListOfFunction(): boolean { + return this.count() >= 2 && + this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && + (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; + } + + public isArgumentOfFunction(): boolean { + return this.count() >= 3 && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && + this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && + (this.asts[this.top - 2]).arguments === this.asts[this.top - 1]; + } + + public isArgumentListOfCall(): boolean { + return this.count() >= 2 && + this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.Call && + (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; + } + + public isArgumentListOfNew(): boolean { + return this.count() >= 2 && + this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && + this.asts[this.top - 1].nodeType === TypeScript.NodeType.New && + (this.asts[this.top - 1]).arguments === this.asts[this.top - 0]; + } + + public isSynthesizedBlock(): boolean { + return this.count() >= 1 && + this.asts[this.top - 0].nodeType === TypeScript.NodeType.Block && + (this.asts[this.top - 0]).isStatementBlock === false; + } + } + + export function isValidAstNode(ast: TypeScript.ASTSpan): boolean { + if (ast === null) + return false; + + if (ast.minChar === -1 || ast.limChar === -1) + return false; + + return true; + } + + export class AstPathContext { + public path = new TypeScript.AstPath(); + } + + export enum GetAstPathOptions { + Default = 0, + EdgeInclusive = 1, + //We need this options dealing with an AST coming from an incomplete AST. For example: + // class foo { // r + // If we ask for the AST at the position after the "r" character, we won't see we are + // inside a comment, because the "class" AST node has a limChar corresponding to the position of + // the "{" character, meaning we don't traverse the tree down to the stmt list of the class, meaning + // we don't find the "precomment" attached to the errorneous empty stmt. + //TODO: It would be nice to be able to get rid of this. + DontPruneSearchBasedOnPosition = 1 << 1, + } + + /// + /// Return the stack of AST nodes containing "position" + /// + export function getAstPathToPosition(script: TypeScript.AST, pos: number, options = GetAstPathOptions.Default): TypeScript.AstPath { + var lookInComments = (comments: TypeScript.Comment[]) => { + if (comments && comments.length > 0) { + for (var i = 0; i < comments.length; i++) { + var minChar = comments[i].minChar; + var limChar = comments[i].limChar; + if (!comments[i].isBlockComment) { + limChar++; // For single line comments, include 1 more character (for the newline) + } + if (pos >= minChar && pos < limChar) { + ctx.path.push(comments[i]); + } + } + } + } + + var pre = function (cur: TypeScript.AST, parent: TypeScript.AST, walker: IAstWalker) { + if (isValidAstNode(cur)) { + + // Add "cur" to the stack if it contains our position + // For "identifier" nodes, we need a special case: A position equal to "limChar" is + // valid, since the position corresponds to a caret position (in between characters) + // For example: + // bar + // 0123 + // If "position == 3", the caret is at the "right" of the "r" character, which should be considered valid + var inclusive = + hasFlag(options, GetAstPathOptions.EdgeInclusive) || + cur.nodeType === TypeScript.NodeType.Name || + pos === script.limChar; // Special "EOF" case + + var minChar = cur.minChar; + var limChar = cur.limChar + (inclusive ? 1 : 0) + if (pos >= minChar && pos < limChar) { + + // TODO: Since AST is sometimes not correct wrt to position, only add "cur" if it's better + // than top of the stack. + var previous = ctx.path.ast(); + if (previous == null || (cur.minChar >= previous.minChar && cur.limChar <= previous.limChar)) { + ctx.path.push(cur); + } + else { + //logger.log("TODO: Ignoring node because minChar, limChar not better than previous node in stack"); + } + } + + // The AST walker skips comments, but we might be in one, so check the pre/post comments for this node manually + if (pos < limChar) { + lookInComments(cur.preComments); + } + if (pos >= minChar) { + lookInComments(cur.postComments); + } + + if (!hasFlag(options, GetAstPathOptions.DontPruneSearchBasedOnPosition)) { + // Don't go further down the tree if pos is outside of [minChar, limChar] + walker.options.goChildren = (minChar <= pos && pos <= limChar); + } + } + return cur; + } + + var ctx = new AstPathContext(); + TypeScript.getAstWalkerFactory().walk(script, pre, null, null, ctx); + return ctx.path; + } + + // + // Find a source text offset that is safe for lexing tokens at the given position. + // This is used when "position" might be inside a comment or string, etc. + // + export function getTokenizationOffset(script: TypeScript.Script, position: number): number { + var bestOffset = 0; + var pre = (cur: TypeScript.AST, parent: TypeScript.AST, walker: TypeScript.IAstWalker): TypeScript.AST => { + if (TypeScript.isValidAstNode(cur)) { + // Did we find a closer offset? + if (cur.minChar <= position) { + bestOffset = max(bestOffset, cur.minChar); + } + + // Stop the walk if this node is not related to "minChar" + if (cur.minChar > position || cur.limChar < bestOffset) { + walker.options.goChildren = false; + } + } + + return cur; + } + + TypeScript.getAstWalkerFactory().walk(script, pre); + return bestOffset; + } + + /// + /// Simple function to Walk an AST using a simple callback function. + /// + export function walkAST(ast: TypeScript.AST, callback: (path: AstPath, walker: TypeScript.IAstWalker) => void ): void { + var pre = function (cur: TypeScript.AST, parent: TypeScript.AST, walker: TypeScript.IAstWalker) { + var path: TypeScript.AstPath = walker.state; + path.push(cur); + callback(path, walker); + return cur; + } + var post = function (cur: TypeScript.AST, parent: TypeScript.AST, walker: TypeScript.IAstWalker) { + var path: TypeScript.AstPath = walker.state; + path.pop(); + return cur; + } + + var path = new AstPath(); + TypeScript.getAstWalkerFactory().walk(ast, pre, post, null, path); + } +} + + +//// [parserRealSource14.js] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. +/// +var TypeScript; +(function (TypeScript) { + function lastOf(items) { + return (items === null || items.length === 0) ? null : items[items.length - 1]; + } + TypeScript.lastOf = lastOf; + function max(a, b) { + return a >= b ? a : b; + } + TypeScript.max = max; + function min(a, b) { + return a <= b ? a : b; + } + TypeScript.min = min; + // + // Helper class representing a path from a root ast node to a (grand)child ast node. + // This is helpful as our tree don't have parents. + // + var AstPath = (function () { + function AstPath() { + this.asts = []; + this.top = -1; + } + AstPath.reverseIndexOf = function (items, index) { + return (items === null || items.length <= index) ? null : items[items.length - index - 1]; + }; + AstPath.prototype.clone = function () { + var clone = new AstPath(); + clone.asts = this.asts.map(function (value) { + return value; + }); + clone.top = this.top; + return clone; + }; + AstPath.prototype.pop = function () { + var head = this.ast(); + this.up(); + while (this.asts.length > this.count()) { + this.asts.pop(); + } + return head; + }; + AstPath.prototype.push = function (ast) { + while (this.asts.length > this.count()) { + this.asts.pop(); + } + this.top = this.asts.length; + this.asts.push(ast); + }; + AstPath.prototype.up = function () { + if (this.top <= -1) + throw new Error("Invalid call to 'up'"); + this.top--; + }; + AstPath.prototype.down = function () { + if (this.top == this.ast.length - 1) + throw new Error("Invalid call to 'down'"); + this.top++; + }; + AstPath.prototype.nodeType = function () { + if (this.ast() == null) + return TypeScript.NodeType.None; + return this.ast().nodeType; + }; + AstPath.prototype.ast = function () { + return AstPath.reverseIndexOf(this.asts, this.asts.length - (this.top + 1)); + }; + AstPath.prototype.parent = function () { + return AstPath.reverseIndexOf(this.asts, this.asts.length - this.top); + }; + AstPath.prototype.count = function () { + return this.top + 1; + }; + AstPath.prototype.get = function (index) { + return this.asts[index]; + }; + AstPath.prototype.isNameOfClass = function () { + if (this.ast() === null || this.parent() === null) + return false; + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ClassDeclaration) && (this.parent().name === this.ast()); + }; + AstPath.prototype.isNameOfInterface = function () { + if (this.ast() === null || this.parent() === null) + return false; + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.InterfaceDeclaration) && (this.parent().name === this.ast()); + }; + AstPath.prototype.isNameOfArgument = function () { + if (this.ast() === null || this.parent() === null) + return false; + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ArgDecl) && (this.parent().id === this.ast()); + }; + AstPath.prototype.isNameOfVariable = function () { + if (this.ast() === null || this.parent() === null) + return false; + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.VarDecl) && (this.parent().id === this.ast()); + }; + AstPath.prototype.isNameOfModule = function () { + if (this.ast() === null || this.parent() === null) + return false; + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.ModuleDeclaration) && (this.parent().name === this.ast()); + }; + AstPath.prototype.isNameOfFunction = function () { + if (this.ast() === null || this.parent() === null) + return false; + return (this.ast().nodeType === TypeScript.NodeType.Name) && (this.parent().nodeType === TypeScript.NodeType.FuncDecl) && (this.parent().name === this.ast()); + }; + AstPath.prototype.isChildOfScript = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Script; + }; + AstPath.prototype.isChildOfModule = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ModuleDeclaration; + }; + AstPath.prototype.isChildOfClass = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ClassDeclaration; + }; + AstPath.prototype.isArgumentOfClassConstructor = function () { + var ast = lastOf(this.asts); + return this.count() >= 5 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && this.asts[this.top - 3].nodeType === TypeScript.NodeType.List && this.asts[this.top - 4].nodeType === TypeScript.NodeType.ClassDeclaration && (this.asts[this.top - 2].isConstructor) && (this.asts[this.top - 2].arguments === this.asts[this.top - 1]) && (this.asts[this.top - 4].constructorDecl === this.asts[this.top - 2]); + }; + AstPath.prototype.isChildOfInterface = function () { + var ast = lastOf(this.asts); + return this.count() >= 3 && this.asts[this.top] === ast && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.InterfaceDeclaration; + }; + AstPath.prototype.isTopLevelImplicitModule = function () { + return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.ModuleDeclaration && TypeScript.hasFlag(this.asts[this.top].modFlags, TypeScript.ModuleFlags.IsWholeFile); + }; + AstPath.prototype.isBodyOfTopLevelImplicitModule = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && this.asts[this.top - 1].members == this.asts[this.top - 0] && TypeScript.hasFlag(this.asts[this.top - 1].modFlags, TypeScript.ModuleFlags.IsWholeFile); + }; + AstPath.prototype.isBodyOfScript = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Script && this.asts[this.top - 1].bod == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfSwitch = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].caseList == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfModule = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ModuleDeclaration && this.asts[this.top - 1].members == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfClass = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ClassDeclaration && this.asts[this.top - 1].members == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfFunction = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && this.asts[this.top - 1].bod == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfInterface = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.InterfaceDeclaration && this.asts[this.top - 1].members == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfBlock = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Block && this.asts[this.top - 1].statements == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfFor = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.For && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfCase = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Case && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfTry = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Try && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfCatch = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Catch && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfDoWhile = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.DoWhile && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfWhile = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.While && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfForIn = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ForIn && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfWith = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.With && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfFinally = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Finally && this.asts[this.top - 1].body == this.asts[this.top - 0]; + }; + AstPath.prototype.isCaseOfSwitch = function () { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].caseList == this.asts[this.top - 1]; + }; + AstPath.prototype.isDefaultCaseOfSwitch = function () { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.Switch && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].caseList == this.asts[this.top - 1] && this.asts[this.top - 2].defaultCase == this.asts[this.top - 0]; + }; + AstPath.prototype.isListOfObjectLit = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].operand == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfObjectLit = function () { + return this.isListOfObjectLit(); + }; + AstPath.prototype.isEmptyListOfObjectLit = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].operand == this.asts[this.top - 0] && this.asts[this.top - 0].members.length == 0; + }; + AstPath.prototype.isMemberOfObjectLit = function () { + return this.count() >= 3 && this.asts[this.top - 2].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Member && this.asts[this.top - 2].operand == this.asts[this.top - 1]; + }; + AstPath.prototype.isNameOfMemberOfObjectLit = function () { + return this.count() >= 4 && this.asts[this.top - 3].nodeType === TypeScript.NodeType.ObjectLit && this.asts[this.top - 2].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Name && this.asts[this.top - 3].operand == this.asts[this.top - 2]; + }; + AstPath.prototype.isListOfArrayLit = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.ArrayLit && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].operand == this.asts[this.top - 0]; + }; + AstPath.prototype.isTargetOfMember = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && this.asts[this.top - 1].operand1 === this.asts[this.top - 0]; + }; + AstPath.prototype.isMemberOfMember = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Member && this.asts[this.top - 1].operand2 === this.asts[this.top - 0]; + }; + AstPath.prototype.isItemOfList = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List; + //(this.asts[this.top - 1]).operand2 === this.asts[this.top - 0]; + }; + AstPath.prototype.isThenOfIf = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && this.asts[this.top - 1].thenBod == this.asts[this.top - 0]; + }; + AstPath.prototype.isElseOfIf = function () { + return this.count() >= 2 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.If && this.asts[this.top - 1].elseBod == this.asts[this.top - 0]; + }; + AstPath.prototype.isBodyOfDefaultCase = function () { + return this.isBodyOfCase(); + }; + AstPath.prototype.isSingleStatementList = function () { + return this.count() >= 1 && this.asts[this.top].nodeType === TypeScript.NodeType.List && this.asts[this.top].members.length === 1; + }; + AstPath.prototype.isArgumentListOfFunction = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.FuncDecl && this.asts[this.top - 1].arguments === this.asts[this.top - 0]; + }; + AstPath.prototype.isArgumentOfFunction = function () { + return this.count() >= 3 && this.asts[this.top - 1].nodeType === TypeScript.NodeType.List && this.asts[this.top - 2].nodeType === TypeScript.NodeType.FuncDecl && this.asts[this.top - 2].arguments === this.asts[this.top - 1]; + }; + AstPath.prototype.isArgumentListOfCall = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.Call && this.asts[this.top - 1].arguments === this.asts[this.top - 0]; + }; + AstPath.prototype.isArgumentListOfNew = function () { + return this.count() >= 2 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.List && this.asts[this.top - 1].nodeType === TypeScript.NodeType.New && this.asts[this.top - 1].arguments === this.asts[this.top - 0]; + }; + AstPath.prototype.isSynthesizedBlock = function () { + return this.count() >= 1 && this.asts[this.top - 0].nodeType === TypeScript.NodeType.Block && this.asts[this.top - 0].isStatementBlock === false; + }; + return AstPath; + })(); + TypeScript.AstPath = AstPath; + function isValidAstNode(ast) { + if (ast === null) + return false; + if (ast.minChar === -1 || ast.limChar === -1) + return false; + return true; + } + TypeScript.isValidAstNode = isValidAstNode; + var AstPathContext = (function () { + function AstPathContext() { + this.path = new TypeScript.AstPath(); + } + return AstPathContext; + })(); + TypeScript.AstPathContext = AstPathContext; + (function (GetAstPathOptions) { + GetAstPathOptions[GetAstPathOptions["Default"] = 0] = "Default"; + GetAstPathOptions[GetAstPathOptions["EdgeInclusive"] = 1] = "EdgeInclusive"; + //We need this options dealing with an AST coming from an incomplete AST. For example: + // class foo { // r + // If we ask for the AST at the position after the "r" character, we won't see we are + // inside a comment, because the "class" AST node has a limChar corresponding to the position of + // the "{" character, meaning we don't traverse the tree down to the stmt list of the class, meaning + // we don't find the "precomment" attached to the errorneous empty stmt. + //TODO: It would be nice to be able to get rid of this. + GetAstPathOptions[GetAstPathOptions["DontPruneSearchBasedOnPosition"] = 1 << 1] = "DontPruneSearchBasedOnPosition"; + })(TypeScript.GetAstPathOptions || (TypeScript.GetAstPathOptions = {})); + var GetAstPathOptions = TypeScript.GetAstPathOptions; + /// + /// Return the stack of AST nodes containing "position" + /// + function getAstPathToPosition(script, pos, options) { + if (options === void 0) { options = 0 /* Default */; } + var lookInComments = function (comments) { + if (comments && comments.length > 0) { + for (var i = 0; i < comments.length; i++) { + var minChar = comments[i].minChar; + var limChar = comments[i].limChar; + if (!comments[i].isBlockComment) { + limChar++; // For single line comments, include 1 more character (for the newline) + } + if (pos >= minChar && pos < limChar) { + ctx.path.push(comments[i]); + } + } + } + }; + var pre = function (cur, parent, walker) { + if (isValidAstNode(cur)) { + // Add "cur" to the stack if it contains our position + // For "identifier" nodes, we need a special case: A position equal to "limChar" is + // valid, since the position corresponds to a caret position (in between characters) + // For example: + // bar + // 0123 + // If "position == 3", the caret is at the "right" of the "r" character, which should be considered valid + var inclusive = hasFlag(options, 1 /* EdgeInclusive */) || cur.nodeType === TypeScript.NodeType.Name || pos === script.limChar; // Special "EOF" case + var minChar = cur.minChar; + var limChar = cur.limChar + (inclusive ? 1 : 0); + if (pos >= minChar && pos < limChar) { + // TODO: Since AST is sometimes not correct wrt to position, only add "cur" if it's better + // than top of the stack. + var previous = ctx.path.ast(); + if (previous == null || (cur.minChar >= previous.minChar && cur.limChar <= previous.limChar)) { + ctx.path.push(cur); + } + else { + } + } + // The AST walker skips comments, but we might be in one, so check the pre/post comments for this node manually + if (pos < limChar) { + lookInComments(cur.preComments); + } + if (pos >= minChar) { + lookInComments(cur.postComments); + } + if (!hasFlag(options, GetAstPathOptions.DontPruneSearchBasedOnPosition)) { + // Don't go further down the tree if pos is outside of [minChar, limChar] + walker.options.goChildren = (minChar <= pos && pos <= limChar); + } + } + return cur; + }; + var ctx = new AstPathContext(); + TypeScript.getAstWalkerFactory().walk(script, pre, null, null, ctx); + return ctx.path; + } + TypeScript.getAstPathToPosition = getAstPathToPosition; + // + // Find a source text offset that is safe for lexing tokens at the given position. + // This is used when "position" might be inside a comment or string, etc. + // + function getTokenizationOffset(script, position) { + var bestOffset = 0; + var pre = function (cur, parent, walker) { + if (TypeScript.isValidAstNode(cur)) { + // Did we find a closer offset? + if (cur.minChar <= position) { + bestOffset = max(bestOffset, cur.minChar); + } + // Stop the walk if this node is not related to "minChar" + if (cur.minChar > position || cur.limChar < bestOffset) { + walker.options.goChildren = false; + } + } + return cur; + }; + TypeScript.getAstWalkerFactory().walk(script, pre); + return bestOffset; + } + TypeScript.getTokenizationOffset = getTokenizationOffset; + /// + /// Simple function to Walk an AST using a simple callback function. + /// + function walkAST(ast, callback) { + var pre = function (cur, parent, walker) { + var path = walker.state; + path.push(cur); + callback(path, walker); + return cur; + }; + var post = function (cur, parent, walker) { + var path = walker.state; + path.pop(); + return cur; + }; + var path = new AstPath(); + TypeScript.getAstWalkerFactory().walk(ast, pre, post, null, path); + } + TypeScript.walkAST = walkAST; +})(TypeScript || (TypeScript = {})); diff --git a/tests/baselines/reference/parserRealSource2.js b/tests/baselines/reference/parserRealSource2.js new file mode 100644 index 00000000000..0dbe7dfef40 --- /dev/null +++ b/tests/baselines/reference/parserRealSource2.js @@ -0,0 +1,534 @@ +//// [parserRealSource2.ts] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. + +/// + +module TypeScript { + + export function hasFlag(val: number, flag: number) { + return (val & flag) != 0; + } + + export enum ErrorRecoverySet { + None = 0, + Comma = 1, // Comma + SColon = 1 << 1, // SColon + Asg = 1 << 2, // Asg + BinOp = 1 << 3, // Lsh, Rsh, Rs2, Le, Ge, INSTANCEOF, EQ, NE, Eqv, NEqv, LogAnd, LogOr, AsgMul, AsgDiv + // AsgMod, AsgAdd, AsgSub, AsgLsh, AsgRsh, AsgRs2, AsgAnd, AsgXor, AsgOr, QMark, Mult, Div, + // Pct, GT, LT, And, Xor, Or + RBrack = 1 << 4, // RBrack + RCurly = 1 << 5, // RCurly + RParen = 1 << 6, // RParen + Dot = 1 << 7, // Dot + Colon = 1 << 8, // Colon + PrimType = 1 << 9, // number, string, boolean + AddOp = 1 << 10, // Add, Sub + LCurly = 1 << 11, // LCurly + PreOp = 1 << 12, // Tilde, Bang, Inc, Dec + RegExp = 1 << 13, // RegExp + LParen = 1 << 14, // LParen + LBrack = 1 << 15, // LBrack + Scope = 1 << 16, // Scope + In = 1 << 17, // IN + SCase = 1 << 18, // CASE, DEFAULT + Else = 1 << 19, // ELSE + Catch = 1 << 20, // CATCH, FINALLY + Var = 1 << 21, // + Stmt = 1 << 22, // BREAK, RETURN, THROW, DEBUGGER, FOR, SWITCH, DO, IF, TRY, WITH + While = 1 << 23, // WHILE + ID = 1 << 24, // ID + Prefix = 1 << 25, // VOID, DELETE, TYPEOF, AWAIT + Literal = 1 << 26, // IntCon, FltCon, StrCon + RLit = 1 << 27, // THIS, TRUE, FALSE, NULL + Func = 1 << 28, // FUNCTION + EOF = 1 << 29, // EOF + + // REVIEW: Name this something clearer. + TypeScriptS = 1 << 30, // PROPERTY, PRIVATE, STATIC, INTERFACE, CLASS, MODULE, EXPORT, IMPORT + ExprStart = SColon | AddOp | LCurly | PreOp | RegExp | LParen | LBrack | ID | Prefix | RLit | Func | Literal, + StmtStart = ExprStart | SColon | Var | Stmt | While | TypeScriptS, + Postfix = Dot | LParen | LBrack, + } + + export enum AllowedElements { + None = 0, + ModuleDeclarations = 1 << 2, + ClassDeclarations = 1 << 3, + InterfaceDeclarations = 1 << 4, + AmbientDeclarations = 1 << 10, + Properties = 1 << 11, + + Global = ModuleDeclarations | ClassDeclarations | InterfaceDeclarations | AmbientDeclarations, + QuickParse = Global | Properties, + } + + export enum Modifiers { + None = 0, + Private = 1, + Public = 1 << 1, + Readonly = 1 << 2, + Ambient = 1 << 3, + Exported = 1 << 4, + Getter = 1 << 5, + Setter = 1 << 6, + Static = 1 << 7, + } + + export enum ASTFlags { + None = 0, + ExplicitSemicolon = 1, // statment terminated by an explicit semicolon + AutomaticSemicolon = 1 << 1, // statment terminated by an automatic semicolon + Writeable = 1 << 2, // node is lhs that can be modified + Error = 1 << 3, // node has an error + DotLHSPartial = 1 << 4, // node is the lhs of an incomplete dot expr at cursor + DotLHS = 1 << 5, // node is the lhs of a dot expr + IsStatement = 1 << 6, // node is a statement + StrictMode = 1 << 7, // node is in the strict mode environment + PossibleOptionalParameter = 1 << 8, + ClassBaseConstructorCall = 1 << 9, + OptionalName = 1 << 10, + // REVIEW: This flag is to mark lambda nodes to note that the LParen of an expression has already been matched in the lambda header. + // The flag is used to communicate this piece of information to the calling parseTerm, which intern will remove it. + // Once we have a better way to associate information with nodes, this flag should not be used. + SkipNextRParen = 1 << 11, + } + + export enum DeclFlags { + None = 0, + Exported = 1, + Private = 1 << 1, + Public = 1 << 2, + Ambient = 1 << 3, + Static = 1 << 4, + LocalStatic = 1 << 5, + GetAccessor = 1 << 6, + SetAccessor = 1 << 7, + } + + export enum ModuleFlags { + None = 0, + Exported = 1, + Private = 1 << 1, + Public = 1 << 2, + Ambient = 1 << 3, + Static = 1 << 4, + LocalStatic = 1 << 5, + GetAccessor = 1 << 6, + SetAccessor = 1 << 7, + IsEnum = 1 << 8, + ShouldEmitModuleDecl = 1 << 9, + IsWholeFile = 1 << 10, + IsDynamic = 1 << 11, + MustCaptureThis = 1 << 12, + } + + export enum SymbolFlags { + None = 0, + Exported = 1, + Private = 1 << 1, + Public = 1 << 2, + Ambient = 1 << 3, + Static = 1 << 4, + LocalStatic = 1 << 5, + GetAccessor = 1 << 6, + SetAccessor = 1 << 7, + Property = 1 << 8, + Readonly = 1 << 9, + ModuleMember = 1 << 10, + InterfaceMember = 1 << 11, + ClassMember = 1 << 12, + BuiltIn = 1 << 13, + TypeSetDuringScopeAssignment = 1 << 14, + Constant = 1 << 15, + Optional = 1 << 16, + RecursivelyReferenced = 1 << 17, + Bound = 1 << 18, + CompilerGenerated = 1 << 19, + } + + export enum VarFlags { + None = 0, + Exported = 1, + Private = 1 << 1, + Public = 1 << 2, + Ambient = 1 << 3, + Static = 1 << 4, + LocalStatic = 1 << 5, + GetAccessor = 1 << 6, + SetAccessor = 1 << 7, + AutoInit = 1 << 8, + Property = 1 << 9, + Readonly = 1 << 10, + Class = 1 << 11, + ClassProperty = 1 << 12, + ClassBodyProperty = 1 << 13, + ClassConstructorProperty = 1 << 14, + ClassSuperMustBeFirstCallInConstructor = 1 << 15, + Constant = 1 << 16, + MustCaptureThis = 1 << 17, + } + + export enum FncFlags { + None = 0, + Exported = 1, + Private = 1 << 1, + Public = 1 << 2, + Ambient = 1 << 3, + Static = 1 << 4, + LocalStatic = 1 << 5, + GetAccessor = 1 << 6, + SetAccessor = 1 << 7, + Definition = 1 << 8, + Signature = 1 << 9, + Method = 1 << 10, + HasReturnExpression = 1 << 11, + CallMember = 1 << 12, + ConstructMember = 1 << 13, + HasSelfReference = 1 << 14, + IsFatArrowFunction = 1 << 15, + IndexerMember = 1 << 16, + IsFunctionExpression = 1 << 17, + ClassMethod = 1 << 18, + ClassPropertyMethodExported = 1 << 19, + } + + export enum SignatureFlags { + None = 0, + IsIndexer = 1, + IsStringIndexer = 1 << 1, + IsNumberIndexer = 1 << 2, + } + + export function ToDeclFlags(fncFlags: FncFlags) : DeclFlags; + export function ToDeclFlags(varFlags: VarFlags) : DeclFlags; + export function ToDeclFlags(symFlags: SymbolFlags): DeclFlags; + export function ToDeclFlags(moduleFlags: ModuleFlags): DeclFlags; + export function ToDeclFlags(fncOrVarOrSymbolOrModuleFlags: any) { + return fncOrVarOrSymbolOrModuleFlags; + } + + export enum TypeFlags { + None = 0, + HasImplementation = 1, + HasSelfReference = 1 << 1, + MergeResult = 1 << 2, + IsEnum = 1 << 3, + BuildingName = 1 << 4, + HasBaseType = 1 << 5, + HasBaseTypeOfObject = 1 << 6, + IsClass = 1 << 7, + } + + export enum TypeRelationshipFlags { + SuccessfulComparison = 0, + SourceIsNullTargetIsVoidOrUndefined = 1, + RequiredPropertyIsMissing = 1 << 1, + IncompatibleSignatures = 1 << 2, + SourceSignatureHasTooManyParameters = 3, + IncompatibleReturnTypes = 1 << 4, + IncompatiblePropertyTypes = 1 << 5, + IncompatibleParameterTypes = 1 << 6, + } + + export enum CodeGenTarget { + ES3 = 0, + ES5 = 1, + } + + export enum ModuleGenTarget { + Synchronous = 0, + Asynchronous = 1, + Local = 1 << 1, + } + + // Compiler defaults to generating ES5-compliant code for + // - getters and setters + export var codeGenTarget: CodeGenTarget = CodeGenTarget.ES3; + + export var moduleGenTarget: ModuleGenTarget = ModuleGenTarget.Synchronous; + + export var optimizeModuleCodeGen = true; + + export function flagsToString(e, flags: number): string { + var builder = ""; + for (var i = 1; i < (1 << 31) ; i = i << 1) { + if ((flags & i) != 0) { + for (var k in e) { + if (e[k] == i) { + if (builder.length > 0) { + builder += "|"; + } + builder += k; + break; + } + } + } + } + return builder; + } + +} + +//// [parserRealSource2.js] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. +/// +var TypeScript; +(function (TypeScript) { + function hasFlag(val, flag) { + return (val & flag) != 0; + } + TypeScript.hasFlag = hasFlag; + (function (ErrorRecoverySet) { + ErrorRecoverySet[ErrorRecoverySet["None"] = 0] = "None"; + ErrorRecoverySet[ErrorRecoverySet["Comma"] = 1] = "Comma"; + ErrorRecoverySet[ErrorRecoverySet["SColon"] = 1 << 1] = "SColon"; + ErrorRecoverySet[ErrorRecoverySet["Asg"] = 1 << 2] = "Asg"; + ErrorRecoverySet[ErrorRecoverySet["BinOp"] = 1 << 3] = "BinOp"; + // AsgMod, AsgAdd, AsgSub, AsgLsh, AsgRsh, AsgRs2, AsgAnd, AsgXor, AsgOr, QMark, Mult, Div, + // Pct, GT, LT, And, Xor, Or + ErrorRecoverySet[ErrorRecoverySet["RBrack"] = 1 << 4] = "RBrack"; + ErrorRecoverySet[ErrorRecoverySet["RCurly"] = 1 << 5] = "RCurly"; + ErrorRecoverySet[ErrorRecoverySet["RParen"] = 1 << 6] = "RParen"; + ErrorRecoverySet[ErrorRecoverySet["Dot"] = 1 << 7] = "Dot"; + ErrorRecoverySet[ErrorRecoverySet["Colon"] = 1 << 8] = "Colon"; + ErrorRecoverySet[ErrorRecoverySet["PrimType"] = 1 << 9] = "PrimType"; + ErrorRecoverySet[ErrorRecoverySet["AddOp"] = 1 << 10] = "AddOp"; + ErrorRecoverySet[ErrorRecoverySet["LCurly"] = 1 << 11] = "LCurly"; + ErrorRecoverySet[ErrorRecoverySet["PreOp"] = 1 << 12] = "PreOp"; + ErrorRecoverySet[ErrorRecoverySet["RegExp"] = 1 << 13] = "RegExp"; + ErrorRecoverySet[ErrorRecoverySet["LParen"] = 1 << 14] = "LParen"; + ErrorRecoverySet[ErrorRecoverySet["LBrack"] = 1 << 15] = "LBrack"; + ErrorRecoverySet[ErrorRecoverySet["Scope"] = 1 << 16] = "Scope"; + ErrorRecoverySet[ErrorRecoverySet["In"] = 1 << 17] = "In"; + ErrorRecoverySet[ErrorRecoverySet["SCase"] = 1 << 18] = "SCase"; + ErrorRecoverySet[ErrorRecoverySet["Else"] = 1 << 19] = "Else"; + ErrorRecoverySet[ErrorRecoverySet["Catch"] = 1 << 20] = "Catch"; + ErrorRecoverySet[ErrorRecoverySet["Var"] = 1 << 21] = "Var"; + ErrorRecoverySet[ErrorRecoverySet["Stmt"] = 1 << 22] = "Stmt"; + ErrorRecoverySet[ErrorRecoverySet["While"] = 1 << 23] = "While"; + ErrorRecoverySet[ErrorRecoverySet["ID"] = 1 << 24] = "ID"; + ErrorRecoverySet[ErrorRecoverySet["Prefix"] = 1 << 25] = "Prefix"; + ErrorRecoverySet[ErrorRecoverySet["Literal"] = 1 << 26] = "Literal"; + ErrorRecoverySet[ErrorRecoverySet["RLit"] = 1 << 27] = "RLit"; + ErrorRecoverySet[ErrorRecoverySet["Func"] = 1 << 28] = "Func"; + ErrorRecoverySet[ErrorRecoverySet["EOF"] = 1 << 29] = "EOF"; + // REVIEW: Name this something clearer. + ErrorRecoverySet[ErrorRecoverySet["TypeScriptS"] = 1 << 30] = "TypeScriptS"; + ErrorRecoverySet[ErrorRecoverySet["ExprStart"] = ErrorRecoverySet.SColon | ErrorRecoverySet.AddOp | ErrorRecoverySet.LCurly | ErrorRecoverySet.PreOp | ErrorRecoverySet.RegExp | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack | ErrorRecoverySet.ID | ErrorRecoverySet.Prefix | ErrorRecoverySet.RLit | ErrorRecoverySet.Func | ErrorRecoverySet.Literal] = "ExprStart"; + ErrorRecoverySet[ErrorRecoverySet["StmtStart"] = ErrorRecoverySet.ExprStart | ErrorRecoverySet.SColon | ErrorRecoverySet.Var | ErrorRecoverySet.Stmt | ErrorRecoverySet.While | ErrorRecoverySet.TypeScriptS] = "StmtStart"; + ErrorRecoverySet[ErrorRecoverySet["Postfix"] = ErrorRecoverySet.Dot | ErrorRecoverySet.LParen | ErrorRecoverySet.LBrack] = "Postfix"; + })(TypeScript.ErrorRecoverySet || (TypeScript.ErrorRecoverySet = {})); + var ErrorRecoverySet = TypeScript.ErrorRecoverySet; + (function (AllowedElements) { + AllowedElements[AllowedElements["None"] = 0] = "None"; + AllowedElements[AllowedElements["ModuleDeclarations"] = 1 << 2] = "ModuleDeclarations"; + AllowedElements[AllowedElements["ClassDeclarations"] = 1 << 3] = "ClassDeclarations"; + AllowedElements[AllowedElements["InterfaceDeclarations"] = 1 << 4] = "InterfaceDeclarations"; + AllowedElements[AllowedElements["AmbientDeclarations"] = 1 << 10] = "AmbientDeclarations"; + AllowedElements[AllowedElements["Properties"] = 1 << 11] = "Properties"; + AllowedElements[AllowedElements["Global"] = AllowedElements.ModuleDeclarations | AllowedElements.ClassDeclarations | AllowedElements.InterfaceDeclarations | AllowedElements.AmbientDeclarations] = "Global"; + AllowedElements[AllowedElements["QuickParse"] = AllowedElements.Global | AllowedElements.Properties] = "QuickParse"; + })(TypeScript.AllowedElements || (TypeScript.AllowedElements = {})); + var AllowedElements = TypeScript.AllowedElements; + (function (Modifiers) { + Modifiers[Modifiers["None"] = 0] = "None"; + Modifiers[Modifiers["Private"] = 1] = "Private"; + Modifiers[Modifiers["Public"] = 1 << 1] = "Public"; + Modifiers[Modifiers["Readonly"] = 1 << 2] = "Readonly"; + Modifiers[Modifiers["Ambient"] = 1 << 3] = "Ambient"; + Modifiers[Modifiers["Exported"] = 1 << 4] = "Exported"; + Modifiers[Modifiers["Getter"] = 1 << 5] = "Getter"; + Modifiers[Modifiers["Setter"] = 1 << 6] = "Setter"; + Modifiers[Modifiers["Static"] = 1 << 7] = "Static"; + })(TypeScript.Modifiers || (TypeScript.Modifiers = {})); + var Modifiers = TypeScript.Modifiers; + (function (ASTFlags) { + ASTFlags[ASTFlags["None"] = 0] = "None"; + ASTFlags[ASTFlags["ExplicitSemicolon"] = 1] = "ExplicitSemicolon"; + ASTFlags[ASTFlags["AutomaticSemicolon"] = 1 << 1] = "AutomaticSemicolon"; + ASTFlags[ASTFlags["Writeable"] = 1 << 2] = "Writeable"; + ASTFlags[ASTFlags["Error"] = 1 << 3] = "Error"; + ASTFlags[ASTFlags["DotLHSPartial"] = 1 << 4] = "DotLHSPartial"; + ASTFlags[ASTFlags["DotLHS"] = 1 << 5] = "DotLHS"; + ASTFlags[ASTFlags["IsStatement"] = 1 << 6] = "IsStatement"; + ASTFlags[ASTFlags["StrictMode"] = 1 << 7] = "StrictMode"; + ASTFlags[ASTFlags["PossibleOptionalParameter"] = 1 << 8] = "PossibleOptionalParameter"; + ASTFlags[ASTFlags["ClassBaseConstructorCall"] = 1 << 9] = "ClassBaseConstructorCall"; + ASTFlags[ASTFlags["OptionalName"] = 1 << 10] = "OptionalName"; + // REVIEW: This flag is to mark lambda nodes to note that the LParen of an expression has already been matched in the lambda header. + // The flag is used to communicate this piece of information to the calling parseTerm, which intern will remove it. + // Once we have a better way to associate information with nodes, this flag should not be used. + ASTFlags[ASTFlags["SkipNextRParen"] = 1 << 11] = "SkipNextRParen"; + })(TypeScript.ASTFlags || (TypeScript.ASTFlags = {})); + var ASTFlags = TypeScript.ASTFlags; + (function (DeclFlags) { + DeclFlags[DeclFlags["None"] = 0] = "None"; + DeclFlags[DeclFlags["Exported"] = 1] = "Exported"; + DeclFlags[DeclFlags["Private"] = 1 << 1] = "Private"; + DeclFlags[DeclFlags["Public"] = 1 << 2] = "Public"; + DeclFlags[DeclFlags["Ambient"] = 1 << 3] = "Ambient"; + DeclFlags[DeclFlags["Static"] = 1 << 4] = "Static"; + DeclFlags[DeclFlags["LocalStatic"] = 1 << 5] = "LocalStatic"; + DeclFlags[DeclFlags["GetAccessor"] = 1 << 6] = "GetAccessor"; + DeclFlags[DeclFlags["SetAccessor"] = 1 << 7] = "SetAccessor"; + })(TypeScript.DeclFlags || (TypeScript.DeclFlags = {})); + var DeclFlags = TypeScript.DeclFlags; + (function (ModuleFlags) { + ModuleFlags[ModuleFlags["None"] = 0] = "None"; + ModuleFlags[ModuleFlags["Exported"] = 1] = "Exported"; + ModuleFlags[ModuleFlags["Private"] = 1 << 1] = "Private"; + ModuleFlags[ModuleFlags["Public"] = 1 << 2] = "Public"; + ModuleFlags[ModuleFlags["Ambient"] = 1 << 3] = "Ambient"; + ModuleFlags[ModuleFlags["Static"] = 1 << 4] = "Static"; + ModuleFlags[ModuleFlags["LocalStatic"] = 1 << 5] = "LocalStatic"; + ModuleFlags[ModuleFlags["GetAccessor"] = 1 << 6] = "GetAccessor"; + ModuleFlags[ModuleFlags["SetAccessor"] = 1 << 7] = "SetAccessor"; + ModuleFlags[ModuleFlags["IsEnum"] = 1 << 8] = "IsEnum"; + ModuleFlags[ModuleFlags["ShouldEmitModuleDecl"] = 1 << 9] = "ShouldEmitModuleDecl"; + ModuleFlags[ModuleFlags["IsWholeFile"] = 1 << 10] = "IsWholeFile"; + ModuleFlags[ModuleFlags["IsDynamic"] = 1 << 11] = "IsDynamic"; + ModuleFlags[ModuleFlags["MustCaptureThis"] = 1 << 12] = "MustCaptureThis"; + })(TypeScript.ModuleFlags || (TypeScript.ModuleFlags = {})); + var ModuleFlags = TypeScript.ModuleFlags; + (function (SymbolFlags) { + SymbolFlags[SymbolFlags["None"] = 0] = "None"; + SymbolFlags[SymbolFlags["Exported"] = 1] = "Exported"; + SymbolFlags[SymbolFlags["Private"] = 1 << 1] = "Private"; + SymbolFlags[SymbolFlags["Public"] = 1 << 2] = "Public"; + SymbolFlags[SymbolFlags["Ambient"] = 1 << 3] = "Ambient"; + SymbolFlags[SymbolFlags["Static"] = 1 << 4] = "Static"; + SymbolFlags[SymbolFlags["LocalStatic"] = 1 << 5] = "LocalStatic"; + SymbolFlags[SymbolFlags["GetAccessor"] = 1 << 6] = "GetAccessor"; + SymbolFlags[SymbolFlags["SetAccessor"] = 1 << 7] = "SetAccessor"; + SymbolFlags[SymbolFlags["Property"] = 1 << 8] = "Property"; + SymbolFlags[SymbolFlags["Readonly"] = 1 << 9] = "Readonly"; + SymbolFlags[SymbolFlags["ModuleMember"] = 1 << 10] = "ModuleMember"; + SymbolFlags[SymbolFlags["InterfaceMember"] = 1 << 11] = "InterfaceMember"; + SymbolFlags[SymbolFlags["ClassMember"] = 1 << 12] = "ClassMember"; + SymbolFlags[SymbolFlags["BuiltIn"] = 1 << 13] = "BuiltIn"; + SymbolFlags[SymbolFlags["TypeSetDuringScopeAssignment"] = 1 << 14] = "TypeSetDuringScopeAssignment"; + SymbolFlags[SymbolFlags["Constant"] = 1 << 15] = "Constant"; + SymbolFlags[SymbolFlags["Optional"] = 1 << 16] = "Optional"; + SymbolFlags[SymbolFlags["RecursivelyReferenced"] = 1 << 17] = "RecursivelyReferenced"; + SymbolFlags[SymbolFlags["Bound"] = 1 << 18] = "Bound"; + SymbolFlags[SymbolFlags["CompilerGenerated"] = 1 << 19] = "CompilerGenerated"; + })(TypeScript.SymbolFlags || (TypeScript.SymbolFlags = {})); + var SymbolFlags = TypeScript.SymbolFlags; + (function (VarFlags) { + VarFlags[VarFlags["None"] = 0] = "None"; + VarFlags[VarFlags["Exported"] = 1] = "Exported"; + VarFlags[VarFlags["Private"] = 1 << 1] = "Private"; + VarFlags[VarFlags["Public"] = 1 << 2] = "Public"; + VarFlags[VarFlags["Ambient"] = 1 << 3] = "Ambient"; + VarFlags[VarFlags["Static"] = 1 << 4] = "Static"; + VarFlags[VarFlags["LocalStatic"] = 1 << 5] = "LocalStatic"; + VarFlags[VarFlags["GetAccessor"] = 1 << 6] = "GetAccessor"; + VarFlags[VarFlags["SetAccessor"] = 1 << 7] = "SetAccessor"; + VarFlags[VarFlags["AutoInit"] = 1 << 8] = "AutoInit"; + VarFlags[VarFlags["Property"] = 1 << 9] = "Property"; + VarFlags[VarFlags["Readonly"] = 1 << 10] = "Readonly"; + VarFlags[VarFlags["Class"] = 1 << 11] = "Class"; + VarFlags[VarFlags["ClassProperty"] = 1 << 12] = "ClassProperty"; + VarFlags[VarFlags["ClassBodyProperty"] = 1 << 13] = "ClassBodyProperty"; + VarFlags[VarFlags["ClassConstructorProperty"] = 1 << 14] = "ClassConstructorProperty"; + VarFlags[VarFlags["ClassSuperMustBeFirstCallInConstructor"] = 1 << 15] = "ClassSuperMustBeFirstCallInConstructor"; + VarFlags[VarFlags["Constant"] = 1 << 16] = "Constant"; + VarFlags[VarFlags["MustCaptureThis"] = 1 << 17] = "MustCaptureThis"; + })(TypeScript.VarFlags || (TypeScript.VarFlags = {})); + var VarFlags = TypeScript.VarFlags; + (function (FncFlags) { + FncFlags[FncFlags["None"] = 0] = "None"; + FncFlags[FncFlags["Exported"] = 1] = "Exported"; + FncFlags[FncFlags["Private"] = 1 << 1] = "Private"; + FncFlags[FncFlags["Public"] = 1 << 2] = "Public"; + FncFlags[FncFlags["Ambient"] = 1 << 3] = "Ambient"; + FncFlags[FncFlags["Static"] = 1 << 4] = "Static"; + FncFlags[FncFlags["LocalStatic"] = 1 << 5] = "LocalStatic"; + FncFlags[FncFlags["GetAccessor"] = 1 << 6] = "GetAccessor"; + FncFlags[FncFlags["SetAccessor"] = 1 << 7] = "SetAccessor"; + FncFlags[FncFlags["Definition"] = 1 << 8] = "Definition"; + FncFlags[FncFlags["Signature"] = 1 << 9] = "Signature"; + FncFlags[FncFlags["Method"] = 1 << 10] = "Method"; + FncFlags[FncFlags["HasReturnExpression"] = 1 << 11] = "HasReturnExpression"; + FncFlags[FncFlags["CallMember"] = 1 << 12] = "CallMember"; + FncFlags[FncFlags["ConstructMember"] = 1 << 13] = "ConstructMember"; + FncFlags[FncFlags["HasSelfReference"] = 1 << 14] = "HasSelfReference"; + FncFlags[FncFlags["IsFatArrowFunction"] = 1 << 15] = "IsFatArrowFunction"; + FncFlags[FncFlags["IndexerMember"] = 1 << 16] = "IndexerMember"; + FncFlags[FncFlags["IsFunctionExpression"] = 1 << 17] = "IsFunctionExpression"; + FncFlags[FncFlags["ClassMethod"] = 1 << 18] = "ClassMethod"; + FncFlags[FncFlags["ClassPropertyMethodExported"] = 1 << 19] = "ClassPropertyMethodExported"; + })(TypeScript.FncFlags || (TypeScript.FncFlags = {})); + var FncFlags = TypeScript.FncFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["IsIndexer"] = 1] = "IsIndexer"; + SignatureFlags[SignatureFlags["IsStringIndexer"] = 1 << 1] = "IsStringIndexer"; + SignatureFlags[SignatureFlags["IsNumberIndexer"] = 1 << 2] = "IsNumberIndexer"; + })(TypeScript.SignatureFlags || (TypeScript.SignatureFlags = {})); + var SignatureFlags = TypeScript.SignatureFlags; + function ToDeclFlags(fncOrVarOrSymbolOrModuleFlags) { + return fncOrVarOrSymbolOrModuleFlags; + } + TypeScript.ToDeclFlags = ToDeclFlags; + (function (TypeFlags) { + TypeFlags[TypeFlags["None"] = 0] = "None"; + TypeFlags[TypeFlags["HasImplementation"] = 1] = "HasImplementation"; + TypeFlags[TypeFlags["HasSelfReference"] = 1 << 1] = "HasSelfReference"; + TypeFlags[TypeFlags["MergeResult"] = 1 << 2] = "MergeResult"; + TypeFlags[TypeFlags["IsEnum"] = 1 << 3] = "IsEnum"; + TypeFlags[TypeFlags["BuildingName"] = 1 << 4] = "BuildingName"; + TypeFlags[TypeFlags["HasBaseType"] = 1 << 5] = "HasBaseType"; + TypeFlags[TypeFlags["HasBaseTypeOfObject"] = 1 << 6] = "HasBaseTypeOfObject"; + TypeFlags[TypeFlags["IsClass"] = 1 << 7] = "IsClass"; + })(TypeScript.TypeFlags || (TypeScript.TypeFlags = {})); + var TypeFlags = TypeScript.TypeFlags; + (function (TypeRelationshipFlags) { + TypeRelationshipFlags[TypeRelationshipFlags["SuccessfulComparison"] = 0] = "SuccessfulComparison"; + TypeRelationshipFlags[TypeRelationshipFlags["SourceIsNullTargetIsVoidOrUndefined"] = 1] = "SourceIsNullTargetIsVoidOrUndefined"; + TypeRelationshipFlags[TypeRelationshipFlags["RequiredPropertyIsMissing"] = 1 << 1] = "RequiredPropertyIsMissing"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleSignatures"] = 1 << 2] = "IncompatibleSignatures"; + TypeRelationshipFlags[TypeRelationshipFlags["SourceSignatureHasTooManyParameters"] = 3] = "SourceSignatureHasTooManyParameters"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleReturnTypes"] = 1 << 4] = "IncompatibleReturnTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatiblePropertyTypes"] = 1 << 5] = "IncompatiblePropertyTypes"; + TypeRelationshipFlags[TypeRelationshipFlags["IncompatibleParameterTypes"] = 1 << 6] = "IncompatibleParameterTypes"; + })(TypeScript.TypeRelationshipFlags || (TypeScript.TypeRelationshipFlags = {})); + var TypeRelationshipFlags = TypeScript.TypeRelationshipFlags; + (function (CodeGenTarget) { + CodeGenTarget[CodeGenTarget["ES3"] = 0] = "ES3"; + CodeGenTarget[CodeGenTarget["ES5"] = 1] = "ES5"; + })(TypeScript.CodeGenTarget || (TypeScript.CodeGenTarget = {})); + var CodeGenTarget = TypeScript.CodeGenTarget; + (function (ModuleGenTarget) { + ModuleGenTarget[ModuleGenTarget["Synchronous"] = 0] = "Synchronous"; + ModuleGenTarget[ModuleGenTarget["Asynchronous"] = 1] = "Asynchronous"; + ModuleGenTarget[ModuleGenTarget["Local"] = 1 << 1] = "Local"; + })(TypeScript.ModuleGenTarget || (TypeScript.ModuleGenTarget = {})); + var ModuleGenTarget = TypeScript.ModuleGenTarget; + // Compiler defaults to generating ES5-compliant code for + // - getters and setters + TypeScript.codeGenTarget = 0 /* ES3 */; + TypeScript.moduleGenTarget = 0 /* Synchronous */; + TypeScript.optimizeModuleCodeGen = true; + function flagsToString(e, flags) { + var builder = ""; + for (var i = 1; i < (1 << 31); i = i << 1) { + if ((flags & i) != 0) { + for (var k in e) { + if (e[k] == i) { + if (builder.length > 0) { + builder += "|"; + } + builder += k; + break; + } + } + } + } + return builder; + } + TypeScript.flagsToString = flagsToString; +})(TypeScript || (TypeScript = {})); diff --git a/tests/baselines/reference/parserRealSource3.js b/tests/baselines/reference/parserRealSource3.js new file mode 100644 index 00000000000..cfe6800fcf5 --- /dev/null +++ b/tests/baselines/reference/parserRealSource3.js @@ -0,0 +1,241 @@ +//// [parserRealSource3.ts] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. + +/// + +module TypeScript { + // Note: Any addition to the NodeType should also be supported with addition to AstWalkerDetailCallback + export enum NodeType { + None, + Empty, + EmptyExpr, + True, + False, + This, + Super, + QString, + Regex, + Null, + ArrayLit, + ObjectLit, + Void, + Comma, + Pos, + Neg, + Delete, + Await, + In, + Dot, + From, + Is, + InstOf, + Typeof, + NumberLit, + Name, + TypeRef, + Index, + Call, + New, + Asg, + AsgAdd, + AsgSub, + AsgDiv, + AsgMul, + AsgMod, + AsgAnd, + AsgXor, + AsgOr, + AsgLsh, + AsgRsh, + AsgRs2, + ConditionalExpression, + LogOr, + LogAnd, + Or, + Xor, + And, + Eq, + Ne, + Eqv, + NEqv, + Lt, + Le, + Gt, + Ge, + Add, + Sub, + Mul, + Div, + Mod, + Lsh, + Rsh, + Rs2, + Not, + LogNot, + IncPre, + DecPre, + IncPost, + DecPost, + TypeAssertion, + FuncDecl, + Member, + VarDecl, + ArgDecl, + Return, + Break, + Continue, + Throw, + For, + ForIn, + If, + While, + DoWhile, + Block, + Case, + Switch, + Try, + TryCatch, + TryFinally, + Finally, + Catch, + List, + Script, + ClassDeclaration, + InterfaceDeclaration, + ModuleDeclaration, + ImportDeclaration, + With, + Label, + LabeledStatement, + EBStart, + GotoEB, + EndCode, + Error, + Comment, + Debugger, + GeneralNode = FuncDecl, + LastAsg = AsgRs2, + } +} + +//// [parserRealSource3.js] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. +/// +var TypeScript; +(function (TypeScript) { + // Note: Any addition to the NodeType should also be supported with addition to AstWalkerDetailCallback + (function (NodeType) { + NodeType[NodeType["None"] = 0] = "None"; + NodeType[NodeType["Empty"] = 1] = "Empty"; + NodeType[NodeType["EmptyExpr"] = 2] = "EmptyExpr"; + NodeType[NodeType["True"] = 3] = "True"; + NodeType[NodeType["False"] = 4] = "False"; + NodeType[NodeType["This"] = 5] = "This"; + NodeType[NodeType["Super"] = 6] = "Super"; + NodeType[NodeType["QString"] = 7] = "QString"; + NodeType[NodeType["Regex"] = 8] = "Regex"; + NodeType[NodeType["Null"] = 9] = "Null"; + NodeType[NodeType["ArrayLit"] = 10] = "ArrayLit"; + NodeType[NodeType["ObjectLit"] = 11] = "ObjectLit"; + NodeType[NodeType["Void"] = 12] = "Void"; + NodeType[NodeType["Comma"] = 13] = "Comma"; + NodeType[NodeType["Pos"] = 14] = "Pos"; + NodeType[NodeType["Neg"] = 15] = "Neg"; + NodeType[NodeType["Delete"] = 16] = "Delete"; + NodeType[NodeType["Await"] = 17] = "Await"; + NodeType[NodeType["In"] = 18] = "In"; + NodeType[NodeType["Dot"] = 19] = "Dot"; + NodeType[NodeType["From"] = 20] = "From"; + NodeType[NodeType["Is"] = 21] = "Is"; + NodeType[NodeType["InstOf"] = 22] = "InstOf"; + NodeType[NodeType["Typeof"] = 23] = "Typeof"; + NodeType[NodeType["NumberLit"] = 24] = "NumberLit"; + NodeType[NodeType["Name"] = 25] = "Name"; + NodeType[NodeType["TypeRef"] = 26] = "TypeRef"; + NodeType[NodeType["Index"] = 27] = "Index"; + NodeType[NodeType["Call"] = 28] = "Call"; + NodeType[NodeType["New"] = 29] = "New"; + NodeType[NodeType["Asg"] = 30] = "Asg"; + NodeType[NodeType["AsgAdd"] = 31] = "AsgAdd"; + NodeType[NodeType["AsgSub"] = 32] = "AsgSub"; + NodeType[NodeType["AsgDiv"] = 33] = "AsgDiv"; + NodeType[NodeType["AsgMul"] = 34] = "AsgMul"; + NodeType[NodeType["AsgMod"] = 35] = "AsgMod"; + NodeType[NodeType["AsgAnd"] = 36] = "AsgAnd"; + NodeType[NodeType["AsgXor"] = 37] = "AsgXor"; + NodeType[NodeType["AsgOr"] = 38] = "AsgOr"; + NodeType[NodeType["AsgLsh"] = 39] = "AsgLsh"; + NodeType[NodeType["AsgRsh"] = 40] = "AsgRsh"; + NodeType[NodeType["AsgRs2"] = 41] = "AsgRs2"; + NodeType[NodeType["ConditionalExpression"] = 42] = "ConditionalExpression"; + NodeType[NodeType["LogOr"] = 43] = "LogOr"; + NodeType[NodeType["LogAnd"] = 44] = "LogAnd"; + NodeType[NodeType["Or"] = 45] = "Or"; + NodeType[NodeType["Xor"] = 46] = "Xor"; + NodeType[NodeType["And"] = 47] = "And"; + NodeType[NodeType["Eq"] = 48] = "Eq"; + NodeType[NodeType["Ne"] = 49] = "Ne"; + NodeType[NodeType["Eqv"] = 50] = "Eqv"; + NodeType[NodeType["NEqv"] = 51] = "NEqv"; + NodeType[NodeType["Lt"] = 52] = "Lt"; + NodeType[NodeType["Le"] = 53] = "Le"; + NodeType[NodeType["Gt"] = 54] = "Gt"; + NodeType[NodeType["Ge"] = 55] = "Ge"; + NodeType[NodeType["Add"] = 56] = "Add"; + NodeType[NodeType["Sub"] = 57] = "Sub"; + NodeType[NodeType["Mul"] = 58] = "Mul"; + NodeType[NodeType["Div"] = 59] = "Div"; + NodeType[NodeType["Mod"] = 60] = "Mod"; + NodeType[NodeType["Lsh"] = 61] = "Lsh"; + NodeType[NodeType["Rsh"] = 62] = "Rsh"; + NodeType[NodeType["Rs2"] = 63] = "Rs2"; + NodeType[NodeType["Not"] = 64] = "Not"; + NodeType[NodeType["LogNot"] = 65] = "LogNot"; + NodeType[NodeType["IncPre"] = 66] = "IncPre"; + NodeType[NodeType["DecPre"] = 67] = "DecPre"; + NodeType[NodeType["IncPost"] = 68] = "IncPost"; + NodeType[NodeType["DecPost"] = 69] = "DecPost"; + NodeType[NodeType["TypeAssertion"] = 70] = "TypeAssertion"; + NodeType[NodeType["FuncDecl"] = 71] = "FuncDecl"; + NodeType[NodeType["Member"] = 72] = "Member"; + NodeType[NodeType["VarDecl"] = 73] = "VarDecl"; + NodeType[NodeType["ArgDecl"] = 74] = "ArgDecl"; + NodeType[NodeType["Return"] = 75] = "Return"; + NodeType[NodeType["Break"] = 76] = "Break"; + NodeType[NodeType["Continue"] = 77] = "Continue"; + NodeType[NodeType["Throw"] = 78] = "Throw"; + NodeType[NodeType["For"] = 79] = "For"; + NodeType[NodeType["ForIn"] = 80] = "ForIn"; + NodeType[NodeType["If"] = 81] = "If"; + NodeType[NodeType["While"] = 82] = "While"; + NodeType[NodeType["DoWhile"] = 83] = "DoWhile"; + NodeType[NodeType["Block"] = 84] = "Block"; + NodeType[NodeType["Case"] = 85] = "Case"; + NodeType[NodeType["Switch"] = 86] = "Switch"; + NodeType[NodeType["Try"] = 87] = "Try"; + NodeType[NodeType["TryCatch"] = 88] = "TryCatch"; + NodeType[NodeType["TryFinally"] = 89] = "TryFinally"; + NodeType[NodeType["Finally"] = 90] = "Finally"; + NodeType[NodeType["Catch"] = 91] = "Catch"; + NodeType[NodeType["List"] = 92] = "List"; + NodeType[NodeType["Script"] = 93] = "Script"; + NodeType[NodeType["ClassDeclaration"] = 94] = "ClassDeclaration"; + NodeType[NodeType["InterfaceDeclaration"] = 95] = "InterfaceDeclaration"; + NodeType[NodeType["ModuleDeclaration"] = 96] = "ModuleDeclaration"; + NodeType[NodeType["ImportDeclaration"] = 97] = "ImportDeclaration"; + NodeType[NodeType["With"] = 98] = "With"; + NodeType[NodeType["Label"] = 99] = "Label"; + NodeType[NodeType["LabeledStatement"] = 100] = "LabeledStatement"; + NodeType[NodeType["EBStart"] = 101] = "EBStart"; + NodeType[NodeType["GotoEB"] = 102] = "GotoEB"; + NodeType[NodeType["EndCode"] = 103] = "EndCode"; + NodeType[NodeType["Error"] = 104] = "Error"; + NodeType[NodeType["Comment"] = 105] = "Comment"; + NodeType[NodeType["Debugger"] = 106] = "Debugger"; + NodeType[NodeType["GeneralNode"] = NodeType.FuncDecl] = "GeneralNode"; + NodeType[NodeType["LastAsg"] = NodeType.AsgRs2] = "LastAsg"; + })(TypeScript.NodeType || (TypeScript.NodeType = {})); + var NodeType = TypeScript.NodeType; +})(TypeScript || (TypeScript = {})); diff --git a/tests/baselines/reference/parserRealSource4.js b/tests/baselines/reference/parserRealSource4.js new file mode 100644 index 00000000000..1d6ed0aaf13 --- /dev/null +++ b/tests/baselines/reference/parserRealSource4.js @@ -0,0 +1,568 @@ +//// [parserRealSource4.ts] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. + +/// + +module TypeScript { + + export class BlockIntrinsics { + public prototype = undefined; + public toString = undefined; + public toLocaleString = undefined; + public valueOf = undefined; + public hasOwnProperty = undefined; + public propertyIsEnumerable = undefined; + public isPrototypeOf = undefined; + + constructor () { + // initialize the 'constructor' field + this["constructor"] = undefined; + } + } + + export interface IHashTable { + getAllKeys(): string[]; + add(key: string, data): boolean; + addOrUpdate(key: string, data): boolean; + map(fn: (k: string, v, c) => void , context): void; + every(fn: (k: string, v, c) => boolean, context): boolean; + some(fn: (k: string, v, c) => boolean, context): boolean; + count(): number; + lookup(key: string): any; + } + + export class StringHashTable implements IHashTable { + public itemCount = 0; + public table = ( new BlockIntrinsics()); + + public getAllKeys(): string[]{ + var result: string[] = []; + for (var k in this.table) { + if (this.table[k] != undefined) { + result[result.length] = k; + } + } + return result; + } + + public add(key: string, data): boolean { + if (this.table[key] != undefined) { + return false; + } + this.table[key] = data; + this.itemCount++; + return true; + } + + public addOrUpdate(key: string, data): boolean { + if (this.table[key] != undefined) { + this.table[key] = data; + return false; + } + this.table[key] = data; + this.itemCount++; + return true; + } + + public map(fn: (k: string, v, c) => void , context) { + for (var k in this.table) { + var data = this.table[k]; + if (data != undefined) { + fn(k, this.table[k], context); + } + } + } + + public every(fn: (k: string, v, c) => boolean, context) { + for (var k in this.table) { + var data = this.table[k]; + if (data != undefined) { + if (!fn(k, this.table[k], context)) { + return false; + } + } + } + return true; + } + + public some(fn: (k: string, v, c) => boolean, context) { + for (var k in this.table) { + var data = this.table[k]; + if (data != undefined) { + if (fn(k, this.table[k], context)) { + return true; + } + } + } + return false; + } + + public count(): number { return this.itemCount; } + + public lookup(key: string) { + var data = this.table[key]; + if (data != undefined) { + return data; + } + else { + return (null); + } + } + } + + // The resident table is expected to reference the same table object, whereas the + // transientTable may reference different objects over time + // REVIEW: WARNING: For performance reasons, neither the primary nor secondary table may be null + export class DualStringHashTable implements IHashTable { + + public insertPrimary = true; + + constructor (public primaryTable: IHashTable, + public secondaryTable: IHashTable) { } + + public getAllKeys(): string[]{ + return this.primaryTable.getAllKeys().concat(this.secondaryTable.getAllKeys()); + } + + public add(key: string, data): boolean { + if (this.insertPrimary) { + return this.primaryTable.add(key, data); + } + else { + return this.secondaryTable.add(key, data); + } + } + + public addOrUpdate(key: string, data): boolean { + if (this.insertPrimary) { + return this.primaryTable.addOrUpdate(key, data); + } + else { + return this.secondaryTable.addOrUpdate(key, data); + } + } + + public map(fn: (k: string, v, c) => void , context) { + this.primaryTable.map(fn, context); + this.secondaryTable.map(fn, context); + } + + public every(fn: (k: string, v, c) => boolean, context) { + return this.primaryTable.every(fn, context) && this.secondaryTable.every(fn, context); + } + + public some(fn: (k: string, v, c) => boolean, context) { + return this.primaryTable.some(fn, context) || this.secondaryTable.some(fn, context); + } + + public count() { + return this.primaryTable.count() + this.secondaryTable.count(); + } + + public lookup(key: string) { + var data = this.primaryTable.lookup(key); + if (data != undefined) { + return data; + } + else { + return this.secondaryTable.lookup(key); + } + } + } + + export function numberHashFn(key: number): number { + var c2 = 0x27d4eb2d; // a prime or an odd constant + key = (key ^ 61) ^ (key >>> 16); + key = key + (key << 3); + key = key ^ (key >>> 4); + key = key * c2; + key = key ^ (key >>> 15); + return key; + } + + export function combineHashes(key1: number, key2: number) { + return key2 ^ ((key1 >> 5) + key1); + } + + export class HashEntry { + public next: HashEntry; + + constructor (public key, public data) { } + } + + export class HashTable { + public itemCount: number = 0; + public table = new HashEntry[]; + + constructor (public size: number, public hashFn: (key) =>number, + public equalsFn: (key1, key2) =>boolean) { + for (var i: number = 0; i < this.size; i++) { + this.table[i] = null; + } + } + + public add(key, data): boolean { + var current: HashEntry; + var entry: HashEntry = new HashEntry(key, data); + var val: number = this.hashFn(key); + val = val % this.size; + + for (current = this.table[val]; current != null ; current = current.next) { + if (this.equalsFn(key, current.key)) { + return false; + } + } + entry.next = this.table[val]; + this.table[val] = entry; + this.itemCount++; + return true; + } + + public remove(key) { + var current: HashEntry; + var val: number = this.hashFn(key); + val = val % this.size; + var result = null; + var prevEntry: HashEntry = null; + + for (current = this.table[val]; current != null ; current = current.next) { + if (this.equalsFn(key, current.key)) { + result = current.data; + this.itemCount--; + if (prevEntry) { + prevEntry.next = current.next; + } + else { + this.table[val] = current.next; + } + break; + } + prevEntry = current; + } + return result; + } + + public count(): number { return this.itemCount; } + + public lookup(key) { + var current: HashEntry; + var val: number = this.hashFn(key); + val = val % this.size; + for (current = this.table[val]; current != null ; current = current.next) { + if (this.equalsFn(key, current.key)) { + return (current.data); + } + } + return (null); + } + } + + // Simple Hash table with list of keys and values matching each other at the given index + export class SimpleHashTable { + private keys = []; + private values = []; + + public lookup(key, findValue?: boolean) { + var searchArray = this.keys; + if (findValue) { + searchArray = this.values; + } + + for (var i = 0; i < searchArray.length; i++) { + if (searchArray[i] == key) { + return { + key: this.keys[i], + data: this.values[i], + }; + } + } + return null; + } + + public add(key, data): boolean { + var lookupData = this.lookup(key); + if (lookupData) { + return false; + } + + this.keys[this.keys.length] = key; + this.values[this.values.length] = data; + + return true; + } + } + +} + +//// [parserRealSource4.js] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. +/// +var TypeScript; +(function (TypeScript) { + var BlockIntrinsics = (function () { + function BlockIntrinsics() { + this.prototype = undefined; + this.toString = undefined; + this.toLocaleString = undefined; + this.valueOf = undefined; + this.hasOwnProperty = undefined; + this.propertyIsEnumerable = undefined; + this.isPrototypeOf = undefined; + // initialize the 'constructor' field + this["constructor"] = undefined; + } + return BlockIntrinsics; + })(); + TypeScript.BlockIntrinsics = BlockIntrinsics; + var StringHashTable = (function () { + function StringHashTable() { + this.itemCount = 0; + this.table = (new BlockIntrinsics()); + } + StringHashTable.prototype.getAllKeys = function () { + var result = []; + for (var k in this.table) { + if (this.table[k] != undefined) { + result[result.length] = k; + } + } + return result; + }; + StringHashTable.prototype.add = function (key, data) { + if (this.table[key] != undefined) { + return false; + } + this.table[key] = data; + this.itemCount++; + return true; + }; + StringHashTable.prototype.addOrUpdate = function (key, data) { + if (this.table[key] != undefined) { + this.table[key] = data; + return false; + } + this.table[key] = data; + this.itemCount++; + return true; + }; + StringHashTable.prototype.map = function (fn, context) { + for (var k in this.table) { + var data = this.table[k]; + if (data != undefined) { + fn(k, this.table[k], context); + } + } + }; + StringHashTable.prototype.every = function (fn, context) { + for (var k in this.table) { + var data = this.table[k]; + if (data != undefined) { + if (!fn(k, this.table[k], context)) { + return false; + } + } + } + return true; + }; + StringHashTable.prototype.some = function (fn, context) { + for (var k in this.table) { + var data = this.table[k]; + if (data != undefined) { + if (fn(k, this.table[k], context)) { + return true; + } + } + } + return false; + }; + StringHashTable.prototype.count = function () { + return this.itemCount; + }; + StringHashTable.prototype.lookup = function (key) { + var data = this.table[key]; + if (data != undefined) { + return data; + } + else { + return (null); + } + }; + return StringHashTable; + })(); + TypeScript.StringHashTable = StringHashTable; + // The resident table is expected to reference the same table object, whereas the + // transientTable may reference different objects over time + // REVIEW: WARNING: For performance reasons, neither the primary nor secondary table may be null + var DualStringHashTable = (function () { + function DualStringHashTable(primaryTable, secondaryTable) { + this.primaryTable = primaryTable; + this.secondaryTable = secondaryTable; + this.insertPrimary = true; + } + DualStringHashTable.prototype.getAllKeys = function () { + return this.primaryTable.getAllKeys().concat(this.secondaryTable.getAllKeys()); + }; + DualStringHashTable.prototype.add = function (key, data) { + if (this.insertPrimary) { + return this.primaryTable.add(key, data); + } + else { + return this.secondaryTable.add(key, data); + } + }; + DualStringHashTable.prototype.addOrUpdate = function (key, data) { + if (this.insertPrimary) { + return this.primaryTable.addOrUpdate(key, data); + } + else { + return this.secondaryTable.addOrUpdate(key, data); + } + }; + DualStringHashTable.prototype.map = function (fn, context) { + this.primaryTable.map(fn, context); + this.secondaryTable.map(fn, context); + }; + DualStringHashTable.prototype.every = function (fn, context) { + return this.primaryTable.every(fn, context) && this.secondaryTable.every(fn, context); + }; + DualStringHashTable.prototype.some = function (fn, context) { + return this.primaryTable.some(fn, context) || this.secondaryTable.some(fn, context); + }; + DualStringHashTable.prototype.count = function () { + return this.primaryTable.count() + this.secondaryTable.count(); + }; + DualStringHashTable.prototype.lookup = function (key) { + var data = this.primaryTable.lookup(key); + if (data != undefined) { + return data; + } + else { + return this.secondaryTable.lookup(key); + } + }; + return DualStringHashTable; + })(); + TypeScript.DualStringHashTable = DualStringHashTable; + function numberHashFn(key) { + var c2 = 0x27d4eb2d; // a prime or an odd constant + key = (key ^ 61) ^ (key >>> 16); + key = key + (key << 3); + key = key ^ (key >>> 4); + key = key * c2; + key = key ^ (key >>> 15); + return key; + } + TypeScript.numberHashFn = numberHashFn; + function combineHashes(key1, key2) { + return key2 ^ ((key1 >> 5) + key1); + } + TypeScript.combineHashes = combineHashes; + var HashEntry = (function () { + function HashEntry(key, data) { + this.key = key; + this.data = data; + } + return HashEntry; + })(); + TypeScript.HashEntry = HashEntry; + var HashTable = (function () { + function HashTable(size, hashFn, equalsFn) { + this.size = size; + this.hashFn = hashFn; + this.equalsFn = equalsFn; + this.itemCount = 0; + this.table = new HashEntry[]; + for (var i = 0; i < this.size; i++) { + this.table[i] = null; + } + } + HashTable.prototype.add = function (key, data) { + var current; + var entry = new HashEntry(key, data); + var val = this.hashFn(key); + val = val % this.size; + for (current = this.table[val]; current != null; current = current.next) { + if (this.equalsFn(key, current.key)) { + return false; + } + } + entry.next = this.table[val]; + this.table[val] = entry; + this.itemCount++; + return true; + }; + HashTable.prototype.remove = function (key) { + var current; + var val = this.hashFn(key); + val = val % this.size; + var result = null; + var prevEntry = null; + for (current = this.table[val]; current != null; current = current.next) { + if (this.equalsFn(key, current.key)) { + result = current.data; + this.itemCount--; + if (prevEntry) { + prevEntry.next = current.next; + } + else { + this.table[val] = current.next; + } + break; + } + prevEntry = current; + } + return result; + }; + HashTable.prototype.count = function () { + return this.itemCount; + }; + HashTable.prototype.lookup = function (key) { + var current; + var val = this.hashFn(key); + val = val % this.size; + for (current = this.table[val]; current != null; current = current.next) { + if (this.equalsFn(key, current.key)) { + return (current.data); + } + } + return (null); + }; + return HashTable; + })(); + TypeScript.HashTable = HashTable; + // Simple Hash table with list of keys and values matching each other at the given index + var SimpleHashTable = (function () { + function SimpleHashTable() { + this.keys = []; + this.values = []; + } + SimpleHashTable.prototype.lookup = function (key, findValue) { + var searchArray = this.keys; + if (findValue) { + searchArray = this.values; + } + for (var i = 0; i < searchArray.length; i++) { + if (searchArray[i] == key) { + return { + key: this.keys[i], + data: this.values[i] + }; + } + } + return null; + }; + SimpleHashTable.prototype.add = function (key, data) { + var lookupData = this.lookup(key); + if (lookupData) { + return false; + } + this.keys[this.keys.length] = key; + this.values[this.values.length] = data; + return true; + }; + return SimpleHashTable; + })(); + TypeScript.SimpleHashTable = SimpleHashTable; +})(TypeScript || (TypeScript = {})); diff --git a/tests/baselines/reference/parserRealSource5.js b/tests/baselines/reference/parserRealSource5.js new file mode 100644 index 00000000000..9c64899fab7 --- /dev/null +++ b/tests/baselines/reference/parserRealSource5.js @@ -0,0 +1,129 @@ +//// [parserRealSource5.ts] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. + +/// + +module TypeScript { + // TODO: refactor indent logic for use in emit + export class PrintContext { + public builder = ""; + public indent1 = " "; + public indentStrings: string[] = []; + public indentAmt = 0; + + constructor (public outfile: ITextWriter, public parser: Parser) { + } + + public increaseIndent() { + this.indentAmt++; + } + + public decreaseIndent() { + this.indentAmt--; + } + + public startLine() { + if (this.builder.length > 0) { + CompilerDiagnostics.Alert(this.builder); + } + var indentString = this.indentStrings[this.indentAmt]; + if (indentString === undefined) { + indentString = ""; + for (var i = 0; i < this.indentAmt; i++) { + indentString += this.indent1; + } + this.indentStrings[this.indentAmt] = indentString; + } + this.builder += indentString; + } + + public write(s) { + this.builder += s; + } + + public writeLine(s) { + this.builder += s; + this.outfile.WriteLine(this.builder); + this.builder = ""; + } + + } + + export function prePrintAST(ast: AST, parent: AST, walker: IAstWalker) { + var pc: PrintContext = walker.state; + + ast.print(pc); + pc.increaseIndent(); + return ast; + } + + + export function postPrintAST(ast: AST, parent: AST, walker: IAstWalker) { + var pc: PrintContext = walker.state; + pc.decreaseIndent(); + return ast; + } +} + +//// [parserRealSource5.js] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. +/// +var TypeScript; +(function (TypeScript) { + // TODO: refactor indent logic for use in emit + var PrintContext = (function () { + function PrintContext(outfile, parser) { + this.outfile = outfile; + this.parser = parser; + this.builder = ""; + this.indent1 = " "; + this.indentStrings = []; + this.indentAmt = 0; + } + PrintContext.prototype.increaseIndent = function () { + this.indentAmt++; + }; + PrintContext.prototype.decreaseIndent = function () { + this.indentAmt--; + }; + PrintContext.prototype.startLine = function () { + if (this.builder.length > 0) { + CompilerDiagnostics.Alert(this.builder); + } + var indentString = this.indentStrings[this.indentAmt]; + if (indentString === undefined) { + indentString = ""; + for (var i = 0; i < this.indentAmt; i++) { + indentString += this.indent1; + } + this.indentStrings[this.indentAmt] = indentString; + } + this.builder += indentString; + }; + PrintContext.prototype.write = function (s) { + this.builder += s; + }; + PrintContext.prototype.writeLine = function (s) { + this.builder += s; + this.outfile.WriteLine(this.builder); + this.builder = ""; + }; + return PrintContext; + })(); + TypeScript.PrintContext = PrintContext; + function prePrintAST(ast, parent, walker) { + var pc = walker.state; + ast.print(pc); + pc.increaseIndent(); + return ast; + } + TypeScript.prePrintAST = prePrintAST; + function postPrintAST(ast, parent, walker) { + var pc = walker.state; + pc.decreaseIndent(); + return ast; + } + TypeScript.postPrintAST = postPrintAST; +})(TypeScript || (TypeScript = {})); diff --git a/tests/baselines/reference/parserRealSource6.js b/tests/baselines/reference/parserRealSource6.js new file mode 100644 index 00000000000..e747b95e610 --- /dev/null +++ b/tests/baselines/reference/parserRealSource6.js @@ -0,0 +1,422 @@ +//// [parserRealSource6.ts] +// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0. +// See LICENSE.txt in the project root for complete license information. + +/// + +module TypeScript { + export class TypeCollectionContext { + public script: Script = null; + + constructor (public scopeChain: ScopeChain, public checker: TypeChecker) { + } + } + + export class MemberScopeContext { + public type: Type = null; + public ast: AST = null; + public scope: SymbolScope; + public options = new AstWalkOptions(); + + constructor (public flow: TypeFlow, public pos: number, public matchFlag: ASTFlags) { + } + } + + export class EnclosingScopeContext { + + public scopeGetter: () => SymbolScope = null; + public objectLiteralScopeGetter: () => SymbolScope = null; + public scopeStartAST: AST = null; + public skipNextFuncDeclForClass = false; + public deepestModuleDecl: ModuleDeclaration = null; + public enclosingClassDecl: TypeDeclaration = null; + public enclosingObjectLit: UnaryExpression = null; + public publicsOnly = true; + public useFullAst = false; + private scriptFragment: Script; + + constructor (public logger: ILogger, + public script: Script, + public text: ISourceText, + public pos: number, + public isMemberCompletion: boolean) { + } + + public getScope(): SymbolScope { + return this.scopeGetter(); + } + + public getObjectLiteralScope(): SymbolScope { + return this.objectLiteralScopeGetter(); + } + + public getScopeAST() { + return this.scopeStartAST; + } + + public getScopePosition() { + return this.scopeStartAST.minChar; + } + + public getScriptFragmentStartAST(): AST { + return this.scopeStartAST; + } + + public getScriptFragmentPosition(): number { + return this.getScriptFragmentStartAST().minChar; + } + + public getScriptFragment(): Script { + if (this.scriptFragment == null) { + var ast = this.getScriptFragmentStartAST(); + var minChar = ast.minChar; + var limChar = (this.isMemberCompletion ? this.pos : this.pos + 1); + this.scriptFragment = TypeScript.quickParse(this.logger, ast, this.text, minChar, limChar, null/*errorCapture*/).Script; + } + return this.scriptFragment; + } + } + + export function preFindMemberScope(ast: AST, parent: AST, walker: IAstWalker) { + var memScope: MemberScopeContext = walker.state; + if (hasFlag(ast.flags, memScope.matchFlag) && ((memScope.pos < 0) || (memScope.pos == ast.limChar))) { + memScope.ast = ast; + if ((ast.type == null) && (memScope.pos >= 0)) { + memScope.flow.inScopeTypeCheck(ast, memScope.scope); + } + memScope.type = ast.type; + memScope.options.stopWalk(); + } + return ast; + } + + export function pushTypeCollectionScope(container: Symbol, + valueMembers: ScopedMembers, + ambientValueMembers: ScopedMembers, + enclosedTypes: ScopedMembers, + ambientEnclosedTypes: ScopedMembers, + context: TypeCollectionContext, + thisType: Type, + classType: Type, + moduleDecl: ModuleDeclaration) { + var builder = new SymbolScopeBuilder(valueMembers, ambientValueMembers, enclosedTypes, ambientEnclosedTypes, null, container); + var chain: ScopeChain = new ScopeChain(container, context.scopeChain, builder); + chain.thisType = thisType; + chain.classType = classType; + chain.moduleDecl = moduleDecl; + context.scopeChain = chain; + } + + export function popTypeCollectionScope(context: TypeCollectionContext) { + context.scopeChain = context.scopeChain.previous; + } + + export function preFindEnclosingScope(ast: AST, parent: AST, walker: IAstWalker) { + var context: EnclosingScopeContext = walker.state; + var minChar = ast.minChar; + var limChar = ast.limChar; + + // Account for the fact completion list may be called at the end of a file which + // is has not been fully re-parsed yet. + if (ast.nodeType == NodeType.Script && context.pos > limChar) + limChar = context.pos; + + if ((minChar <= context.pos) && + (limChar >= context.pos)) { + switch (ast.nodeType) { + case NodeType.Script: + var script =