Merge branch 'master' into sigHelp

Conflicts:
	src/compiler/checker.ts
	src/compiler/types.ts
	src/services/services.ts
This commit is contained in:
Jason Freeman 2014-09-24 10:47:41 -07:00
commit 22e989795d
88 changed files with 13259 additions and 7682 deletions

View file

@ -65,7 +65,6 @@ var harnessSources = [
"sourceMapRecorder.ts",
"harnessLanguageService.ts",
"fourslash.ts",
"external/json2.ts",
"runnerbase.ts",
"compilerRunner.ts",
"typeWriter.ts",
@ -320,7 +319,7 @@ function exec(cmd, completeHandler) {
complete();
})
try{
ex.run();
ex.run();
} catch(e) {
console.log('Exception: ' + e)
}
@ -344,7 +343,7 @@ function cleanTestDirs() {
function writeTestConfigFile(tests, testConfigFile) {
console.log('Running test(s): ' + tests);
var testConfigContents = '{\n' + '\ttest: [\'' + tests + '\']\n}';
fs.writeFileSync('test.config', testConfigContents);
fs.writeFileSync('test.config', testConfigContents);
}
function deleteTemporaryProjectOutput() {
@ -387,7 +386,7 @@ desc("Generates code coverage data via instanbul")
task("generate-code-coverage", ["tests", builtLocalDirectory], function () {
var cmd = 'istanbul cover node_modules/mocha/bin/_mocha -- -R min -t ' + testTimeout + ' ' + run;
console.log(cmd);
exec(cmd);
exec(cmd);
}, { async: true });
// Browser tests

View file

@ -47,16 +47,18 @@ npm install
Use one of the following to build and test:
```
jake local # Build the compiler into built/local
jake clean # Delete the built compiler
jake LKG # Replace the last known good with the built one.
# Bootstrapping step to be executed when the built compiler reaches a stable state.
jake tests # Build the test infrastructure using the built compiler.
jake runtests # Run tests using the built compiler and test infrastructure.
# You can override the host or specify a test for this command.
# Use host=<hostName> or tests=<testPath>.
jake baseline-accept # This replaces the baseline test results with the results obtained from jake runtests.
jake -T # List the above commands.
jake local # Build the compiler into built/local
jake clean # Delete the built compiler
jake LKG # Replace the last known good with the built one.
# Bootstrapping step to be executed when the built compiler reaches a stable state.
jake tests # Build the test infrastructure using the built compiler.
jake runtests # Run tests using the built compiler and test infrastructure.
# You can override the host or specify a test for this command.
# Use host=<hostName> or tests=<testPath>.
jake runtests-browser # Runs the tests using the built run.js file. Syntax is jake runtests. Optional
parameters 'host=', 'tests=[regex], reporter=[list|spec|json|<more>]'.
jake baseline-accept # This replaces the baseline test results with the results obtained from jake runtests.
jake -T # List the above commands.
```

View file

@ -19,67 +19,6 @@ limitations under the License.
---------------------------------------------
Third Party Code Components
--------------------------------------------
---- Mozilla Developer Code---------
The following Mozilla Developer Code is under Public Domain as updated after Aug. 20, 2012, see, https://developer.mozilla.org/en-US/docs/Project:Copyrights
1. Array filter Compatibility Method,
Available at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
Any copyright is dedicated to the Public Domain.
2. Array forEach Compatibility Method,
Available at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
Any copyright is dedicated to the Public Domain.
3. Array indexOf Compatibility Method,
Available at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
Any copyright is dedicated to the Public Domain.
4. Array map Compatibility Method,
Available at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
Any copyright is dedicated to the Public Domain.
5. Array Reduce Compatibility Method,
Available at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/Reduce
Any copyright is dedicated to the Public Domain.
6. String Trim Compatibility Method,
Available at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/Trim
Any copyright is dedicated to the Public Domain.
7. Date now Compatibility Method,
Available at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/now
Any copyright is dedicated to the Public Domain.
------------JSON2 Script------------------------
json2.js 2012-10-08
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See, http://www.JSON.org/js.html
--------------r.js----------------------
Copyright (c) 2010-2011 Dojo Foundation. All Rights Reserved.
Originally License under MIT License
-------------------------------------------------------------------------
Provided for Informational Purposes Only
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------- DefinitelyTyped --------------------
This file is based on or incorporates material from the projects listed below (collectively ?Third Party Code?). Microsoft is not the original author of the Third Party Code. The original copyright notice and the license, under which Microsoft received such Third Party Code, are set forth below. Such licenses and notices are provided for informational purposes only. Microsoft, not the third party, licenses the Third Party Code to you under the terms set forth in the EULA for the Microsoft Product. Microsoft reserves all other rights not expressly granted under this agreement, whether by implication, estoppel or otherwise.

32
bin/lib.d.ts vendored
View file

@ -1182,14 +1182,14 @@ interface Int8Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Int8Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -1240,14 +1240,14 @@ interface Uint8Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Uint8Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -1298,14 +1298,14 @@ interface Int16Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Int16Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -1356,14 +1356,14 @@ interface Uint16Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Uint16Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -1414,14 +1414,14 @@ interface Int32Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Int32Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -1472,14 +1472,14 @@ interface Uint32Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Uint32Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -1530,14 +1530,14 @@ interface Float32Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Float32Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -1588,14 +1588,14 @@ interface Float64Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Float64Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;

32
bin/lib.dom.d.ts vendored
View file

@ -79,14 +79,14 @@ interface Int8Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Int8Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -137,14 +137,14 @@ interface Uint8Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Uint8Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -195,14 +195,14 @@ interface Int16Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Int16Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -253,14 +253,14 @@ interface Uint16Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Uint16Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -311,14 +311,14 @@ interface Int32Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Int32Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -369,14 +369,14 @@ interface Uint32Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Uint32Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -427,14 +427,14 @@ interface Float32Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Float32Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -485,14 +485,14 @@ interface Float64Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Float64Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;

View file

@ -79,14 +79,14 @@ interface Int8Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Int8Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -137,14 +137,14 @@ interface Uint8Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Uint8Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -195,14 +195,14 @@ interface Int16Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Int16Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -253,14 +253,14 @@ interface Uint16Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Uint16Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -311,14 +311,14 @@ interface Int32Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Int32Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -369,14 +369,14 @@ interface Uint32Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Uint32Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -427,14 +427,14 @@ interface Float32Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Float32Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;
@ -485,14 +485,14 @@ interface Float64Array extends ArrayBufferView {
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: Float64Array, offset?: number): void;
/**
* Sets a value or an array of values.
* @param A typed or untyped array of values to set.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: number[], offset?: number): void;

4555
bin/tsc.js

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -23,6 +23,28 @@ module ts {
return undefined;
}
interface SymbolWriter {
writeKind(text: string, kind: SymbolDisplayPartKind): void;
writeSymbol(text: string, symbol: Symbol): void;
writeLine(): void;
increaseIndent(): void;
decreaseIndent(): void;
clear(): void;
// Called when the symbol writer encounters a symbol to write. Currently only used by the
// declaration emitter to help determine if it should patch up the final declaration file
// with import statements it previously saw (but chose not to emit).
trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void;
}
interface DisplayPartsSymbolWriter extends SymbolWriter {
displayParts(): SymbolDisplayPart[];
}
interface StringSymbolWriter extends SymbolWriter {
string(): string;
}
/// fullTypeCheck denotes if this instance of the typechecker will be used to get semantic diagnostics.
/// If fullTypeCheck === true, then the typechecker should do every possible check to produce all errors
/// If fullTypeCheck === false, the typechecker can take shortcuts and skip checks that only produce errors.
@ -62,12 +84,15 @@ module ts {
getTypeOfNode: getTypeOfNode,
getApparentType: getApparentType,
typeToString: typeToString,
typeToDisplayParts: typeToDisplayParts,
symbolToString: symbolToString,
symbolToDisplayParts: symbolToDisplayParts,
getAugmentedPropertiesOfApparentType: getAugmentedPropertiesOfApparentType,
getRootSymbol: getRootSymbol,
getContextualType: getContextualType,
getFullyQualifiedName: getFullyQualifiedName,
getResolvedSignature: getResolvedSignature
getResolvedSignature: getResolvedSignature,
getEnumMemberValue: getEnumMemberValue
};
var undefinedSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "undefined");
@ -896,106 +921,238 @@ module ts {
{ accessibility: SymbolAccessibility.NotAccessible, errorSymbolName: firstIdentifierName };
}
// Pool writers to avoid needing to allocate them for every symbol we write.
var displayPartWriters: DisplayPartsSymbolWriter[] = [];
var stringWriters: StringSymbolWriter[] = [];
function displayPartKind(symbol: Symbol): SymbolDisplayPartKind {
var flags = symbol.flags;
if (flags & SymbolFlags.Variable) {
return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === SyntaxKind.Parameter
? SymbolDisplayPartKind.parameterName
: SymbolDisplayPartKind.localName;
}
else if (flags & SymbolFlags.Property) { return SymbolDisplayPartKind.propertyName; }
else if (flags & SymbolFlags.EnumMember) { return SymbolDisplayPartKind.enumMemberName; }
else if (flags & SymbolFlags.Function) { return SymbolDisplayPartKind.functionName; }
else if (flags & SymbolFlags.Class) { return SymbolDisplayPartKind.className; }
else if (flags & SymbolFlags.Interface) { return SymbolDisplayPartKind.interfaceName; }
else if (flags & SymbolFlags.Enum) { return SymbolDisplayPartKind.enumName; }
else if (flags & SymbolFlags.Module) { return SymbolDisplayPartKind.moduleName; }
else if (flags & SymbolFlags.Method) { return SymbolDisplayPartKind.methodName; }
else if (flags & SymbolFlags.TypeParameter) { return SymbolDisplayPartKind.typeParameterName; }
return SymbolDisplayPartKind.text;
}
function getDisplayPartWriter(): DisplayPartsSymbolWriter {
if (displayPartWriters.length == 0) {
var displayParts: SymbolDisplayPart[] = [];
return {
displayParts: () => displayParts,
writeKind: (text, kind) => displayParts.push(new SymbolDisplayPart(text, kind, undefined)),
writeSymbol: (text, symbol) => displayParts.push(new SymbolDisplayPart(text, displayPartKind(symbol), symbol)),
// Completely ignore indentation for display part writers. And map newlines to
// a single space.
writeLine: () => displayParts.push(new SymbolDisplayPart(" ", SymbolDisplayPartKind.space, undefined)),
increaseIndent: () => { },
decreaseIndent: () => { },
clear: () => displayParts = [],
trackSymbol: () => { }
};
}
return displayPartWriters.pop();
}
function getStringWriter(): StringSymbolWriter {
if (stringWriters.length == 0) {
var str = "";
return {
string: () => str,
writeKind: text => str += text,
writeSymbol: text => str += text,
// Completely ignore indentation for string writers. And map newlines to
// a single space.
writeLine: () => str += " ",
increaseIndent: () => { },
decreaseIndent: () => { },
clear: () => str = "",
trackSymbol: () => { }
};
}
return stringWriters.pop();
}
function releaseDisplayPartWriter(writer: DisplayPartsSymbolWriter) {
writer.clear();
displayPartWriters.push(writer);
}
function releaseStringWriter(writer: StringSymbolWriter) {
writer.clear()
stringWriters.push(writer);
}
function writeKeyword(writer: SymbolWriter, kind: SyntaxKind) {
writer.writeKind(tokenToString(kind), SymbolDisplayPartKind.keyword);
}
function writePunctuation(writer: SymbolWriter, kind: SyntaxKind) {
writer.writeKind(tokenToString(kind), SymbolDisplayPartKind.punctuation);
}
function writeOperator(writer: SymbolWriter, kind: SyntaxKind) {
writer.writeKind(tokenToString(kind), SymbolDisplayPartKind.operator);
}
function writeSpace(writer: SymbolWriter) {
writer.writeKind(" ", SymbolDisplayPartKind.space);
}
function symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string {
var writer = getStringWriter();
writeSymbol(symbol, writer, enclosingDeclaration, meaning);
var result = writer.string();
releaseStringWriter(writer);
return result;
}
function symbolToDisplayParts(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): SymbolDisplayPart[] {
var writer = getDisplayPartWriter();
writeSymbol(symbol, writer, enclosingDeclaration, meaning);
var result = writer.displayParts();
releaseDisplayPartWriter(writer);
return result;
}
// 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 symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags) {
function getSymbolName(symbol: Symbol) {
function writeSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags): void {
function writeSymbolName(symbol: Symbol): void {
if (symbol.declarations && symbol.declarations.length > 0) {
var declaration = symbol.declarations[0];
if (declaration.name) {
return identifierToString(declaration.name);
writer.writeSymbol(identifierToString(declaration.name), symbol);
return;
}
}
writer.writeSymbol(symbol.name, symbol);
}
// Let the writer know we just wrote out a symbol. The declarationemitter writer uses
// this to determine if an import it has previously seen (and not writter out) needs
// to be written to the file once the walk of the tree is complete.
//
// NOTE(cyrusn): This approach feels somewhat unfortunate. A simple pass over the tree
// up front (for example, during checking) could determien if we need to emit the imports
// and we could then access that data during declaration emit.
writer.trackSymbol(symbol, enclosingDeclaration, meaning);
var needsDot = false;
function walkSymbol(symbol: Symbol, meaning: SymbolFlags): void {
if (symbol) {
var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning);
if (!accessibleSymbolChain ||
needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
// Go up and add our parent.
walkSymbol(
getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol),
getQualifiedLeftMeaning(meaning));
}
if (accessibleSymbolChain) {
for (var i = 0, n = accessibleSymbolChain.length; i < n; i++) {
if (needsDot) {
writePunctuation(writer, SyntaxKind.DotToken);
}
writeSymbolName(accessibleSymbolChain[i]);
needsDot = true;
}
}
else {
// If we didn't find accessible symbol chain for this symbol, break if this is external module
if (!needsDot && ts.forEach(symbol.declarations, declaration => hasExternalModuleSymbol(declaration))) {
return;
}
if (needsDot) {
writePunctuation(writer, SyntaxKind.DotToken);
}
writeSymbolName(symbol);
needsDot = true;
}
}
return symbol.name;
}
// Get qualified name
if (enclosingDeclaration &&
// TypeParameters do not need qualification
!(symbol.flags & SymbolFlags.TypeParameter)) {
var symbolName: string;
while (symbol) {
var isFirstName = !symbolName;
var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning);
var currentSymbolName: string;
if (accessibleSymbolChain) {
currentSymbolName = ts.map(accessibleSymbolChain, accessibleSymbol => getSymbolName(accessibleSymbol)).join(".");
}
else {
// If we didn't find accessible symbol chain for this symbol, break if this is external module
if (!isFirstName && ts.forEach(symbol.declarations, declaration => hasExternalModuleSymbol(declaration))) {
break;
}
currentSymbolName = getSymbolName(symbol);
}
symbolName = currentSymbolName + (isFirstName ? "" : ("." + symbolName));
if (accessibleSymbolChain && !needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
break;
}
symbol = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol);
meaning = getQualifiedLeftMeaning(meaning);
}
return symbolName;
walkSymbol(symbol, meaning);
return;
}
return getSymbolName(symbol);
return writeSymbolName(symbol);
}
function writeSymbolToTextWriter(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags, writer: TextWriter) {
writer.write(symbolToString(symbol, enclosingDeclaration, meaning));
}
function createSingleLineTextWriter(maxLength?: number) {
var result = "";
var overflow = false;
function write(s: string) {
if (!overflow) {
result += s;
if (result.length > maxLength) {
result = result.substr(0, maxLength - 3) + "...";
overflow = true;
}
}
}
return {
write: write,
writeSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags) {
writeSymbolToTextWriter(symbol, enclosingDeclaration, meaning, this);
},
writeLine() {
write(" ");
},
increaseIndent() { },
decreaseIndent() { },
getText() {
return result;
}
};
}
function typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string {
var writer = getStringWriter();
writeType(type, writer, enclosingDeclaration, flags);
var result = writer.string();
releaseStringWriter(writer);
var maxLength = compilerOptions.noErrorTruncation || flags & TypeFormatFlags.NoTruncation ? undefined : 100;
var stringWriter = createSingleLineTextWriter(maxLength);
// TODO(shkamat): typeToString should take enclosingDeclaration as input, once we have implemented enclosingDeclaration
writeTypeToTextWriter(type, enclosingDeclaration, flags, stringWriter);
return stringWriter.getText();
if (maxLength && result.length >= maxLength) {
result = result.substr(0, maxLength - "...".length) + "...";
}
return result;
}
function writeTypeToTextWriter(type: Type, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: TextWriter) {
function typeToDisplayParts(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): SymbolDisplayPart[] {
var writer = getDisplayPartWriter();
writeType(type, writer, enclosingDeclaration, flags);
var result = writer.displayParts();
releaseDisplayPartWriter(writer);
return result;
}
function writeType(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags) {
var typeStack: Type[];
return writeType(type, /*allowFunctionOrConstructorTypeLiteral*/ true);
function writeType(type: Type, allowFunctionOrConstructorTypeLiteral: boolean) {
if (type.flags & TypeFlags.Intrinsic) {
writer.write((<IntrinsicType>type).intrinsicName);
writer.writeKind((<IntrinsicType>type).intrinsicName, SymbolDisplayPartKind.keyword);
}
else if (type.flags & TypeFlags.Reference) {
writeTypeReference(<TypeReference>type);
}
else if (type.flags & (TypeFlags.Class | TypeFlags.Interface | TypeFlags.Enum | TypeFlags.TypeParameter)) {
writer.writeSymbol(type.symbol, enclosingDeclaration, SymbolFlags.Type);
writeSymbol(type.symbol, writer, enclosingDeclaration, SymbolFlags.Type);
}
else if (type.flags & TypeFlags.Tuple) {
writeTupleType(<TupleType>type);
@ -1004,18 +1161,24 @@ module ts {
writeAnonymousType(<ObjectType>type, allowFunctionOrConstructorTypeLiteral);
}
else if (type.flags & TypeFlags.StringLiteral) {
writer.write((<StringLiteralType>type).text);
writer.writeKind((<StringLiteralType>type).text, SymbolDisplayPartKind.stringLiteral);
}
else {
// Should never get here
writer.write("{ ... }");
// { ... }
writePunctuation(writer, SyntaxKind.OpenBraceToken);
writeSpace(writer);
writePunctuation(writer, SyntaxKind.DotDotDotToken);
writeSpace(writer);
writePunctuation(writer, SyntaxKind.CloseBraceToken);
}
}
function writeTypeList(types: Type[]) {
for (var i = 0; i < types.length; i++) {
if (i > 0) {
writer.write(", ");
writePunctuation(writer, SyntaxKind.CommaToken);
writeSpace(writer);
}
writeType(types[i], /*allowFunctionOrConstructorTypeLiteral*/ true);
}
@ -1026,20 +1189,21 @@ module ts {
// If we are writing array element type the arrow style signatures are not allowed as
// we need to surround it by curlies, e.g. { (): T; }[]; as () => T[] would mean something different
writeType(type.typeArguments[0], /*allowFunctionOrConstructorTypeLiteral*/ false);
writer.write("[]");
writePunctuation(writer, SyntaxKind.OpenBracketToken);
writePunctuation(writer, SyntaxKind.CloseBracketToken);
}
else {
writer.writeSymbol(type.target.symbol, enclosingDeclaration, SymbolFlags.Type);
writer.write("<");
writeSymbol(type.target.symbol, writer, enclosingDeclaration, SymbolFlags.Type);
writePunctuation(writer, SyntaxKind.LessThanToken);
writeTypeList(type.typeArguments);
writer.write(">");
writePunctuation(writer, SyntaxKind.GreaterThanToken);
}
}
function writeTupleType(type: TupleType) {
writer.write("[");
writePunctuation(writer, SyntaxKind.OpenBracketToken);
writeTypeList(type.elementTypes);
writer.write("]");
writePunctuation(writer, SyntaxKind.CloseBracketToken);
}
function writeAnonymousType(type: ObjectType, allowFunctionOrConstructorTypeLiteral: boolean) {
@ -1053,7 +1217,7 @@ module ts {
}
else if (typeStack && contains(typeStack, type)) {
// Recursive usage, use any
writer.write("any");
writeKeyword(writer, SyntaxKind.AnyKeyword);
}
else {
if (!typeStack) {
@ -1083,15 +1247,17 @@ module ts {
}
function writeTypeofSymbol(type: ObjectType) {
writer.write("typeof ");
writer.writeSymbol(type.symbol, enclosingDeclaration, SymbolFlags.Value);
writeKeyword(writer, SyntaxKind.TypeOfKeyword);
writeSpace(writer);
writeSymbol(type.symbol, writer, enclosingDeclaration, SymbolFlags.Value);
}
function writeLiteralType(type: ObjectType, allowFunctionOrConstructorTypeLiteral: boolean) {
var resolved = resolveObjectTypeMembers(type);
if (!resolved.properties.length && !resolved.stringIndexType && !resolved.numberIndexType) {
if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
writer.write("{}");
writePunctuation(writer, SyntaxKind.OpenBraceToken);
writePunctuation(writer, SyntaxKind.CloseBraceToken);
return;
}
@ -1101,37 +1267,56 @@ module ts {
return;
}
if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
writer.write("new ");
writeKeyword(writer, SyntaxKind.NewKeyword);
writeSpace(writer);
writeSignature(resolved.constructSignatures[0], /*arrowStyle*/ true);
return;
}
}
}
writer.write("{");
writePunctuation(writer, SyntaxKind.OpenBraceToken);
writer.writeLine();
writer.increaseIndent();
for (var i = 0; i < resolved.callSignatures.length; i++) {
writeSignature(resolved.callSignatures[i]);
writer.write(";");
writePunctuation(writer, SyntaxKind.SemicolonToken);
writer.writeLine();
}
for (var i = 0; i < resolved.constructSignatures.length; i++) {
writer.write("new ");
writeKeyword(writer, SyntaxKind.NewKeyword);
writeSpace(writer);
writeSignature(resolved.constructSignatures[i]);
writer.write(";");
writePunctuation(writer, SyntaxKind.SemicolonToken);
writer.writeLine();
}
if (resolved.stringIndexType) {
writer.write("[x: string]: ");
// [x: string]:
writePunctuation(writer, SyntaxKind.OpenBracketToken);
writer.writeKind("x", SymbolDisplayPartKind.parameterName);
writePunctuation(writer, SyntaxKind.ColonToken);
writeSpace(writer);
writeKeyword(writer, SyntaxKind.StringKeyword);
writePunctuation(writer, SyntaxKind.CloseBracketToken);
writePunctuation(writer, SyntaxKind.ColonToken);
writeSpace(writer);
writeType(resolved.stringIndexType, /*allowFunctionOrConstructorTypeLiteral*/ true);
writer.write(";");
writePunctuation(writer, SyntaxKind.SemicolonToken);
writer.writeLine();
}
if (resolved.numberIndexType) {
writer.write("[x: number]: ");
// [x: number]:
writePunctuation(writer, SyntaxKind.OpenBracketToken);
writer.writeKind("x", SymbolDisplayPartKind.parameterName);
writePunctuation(writer, SyntaxKind.ColonToken);
writeSpace(writer);
writeKeyword(writer, SyntaxKind.NumberKeyword);
writePunctuation(writer, SyntaxKind.CloseBracketToken);
writePunctuation(writer, SyntaxKind.ColonToken);
writeSpace(writer);
writeType(resolved.numberIndexType, /*allowFunctionOrConstructorTypeLiteral*/ true);
writer.write(";");
writePunctuation(writer, SyntaxKind.SemicolonToken);
writer.writeLine();
}
for (var i = 0; i < resolved.properties.length; i++) {
@ -1140,64 +1325,81 @@ module ts {
if (p.flags & (SymbolFlags.Function | SymbolFlags.Method) && !getPropertiesOfType(t).length) {
var signatures = getSignaturesOfType(t, SignatureKind.Call);
for (var j = 0; j < signatures.length; j++) {
writer.writeSymbol(p);
writeSymbol(p, writer);
if (isOptionalProperty(p)) {
writer.write("?");
writePunctuation(writer, SyntaxKind.QuestionToken);
}
writeSignature(signatures[j]);
writer.write(";");
writePunctuation(writer, SyntaxKind.SemicolonToken);
writer.writeLine();
}
}
else {
writer.writeSymbol(p);
writeSymbol(p, writer);
if (isOptionalProperty(p)) {
writer.write("?");
writePunctuation(writer, SyntaxKind.QuestionToken);
}
writer.write(": ");
writePunctuation(writer, SyntaxKind.ColonToken);
writeSpace(writer);
writeType(t, /*allowFunctionOrConstructorTypeLiteral*/ true);
writer.write(";");
writePunctuation(writer, SyntaxKind.SemicolonToken);
writer.writeLine();
}
}
writer.decreaseIndent();
writer.write("}");
writePunctuation(writer, SyntaxKind.CloseBraceToken);
}
function writeSignature(signature: Signature, arrowStyle?: boolean) {
if (signature.typeParameters) {
writer.write("<");
writePunctuation(writer, SyntaxKind.LessThanToken);
for (var i = 0; i < signature.typeParameters.length; i++) {
if (i > 0) {
writer.write(", ");
writePunctuation(writer, SyntaxKind.CommaToken);
writeSpace(writer);
}
var tp = signature.typeParameters[i];
writer.writeSymbol(tp.symbol);
writeSymbol(tp.symbol, writer);
var constraint = getConstraintOfTypeParameter(tp);
if (constraint) {
writer.write(" extends ");
writeSpace(writer);
writeKeyword(writer, SyntaxKind.ExtendsKeyword);
writeSpace(writer);
writeType(constraint, /*allowFunctionOrConstructorTypeLiteral*/ true);
}
}
writer.write(">");
writePunctuation(writer, SyntaxKind.GreaterThanToken);
}
writer.write("(");
writePunctuation(writer, SyntaxKind.OpenParenToken);
for (var i = 0; i < signature.parameters.length; i++) {
if (i > 0) {
writer.write(", ");
writePunctuation(writer, SyntaxKind.CommaToken);
writeSpace(writer);
}
var p = signature.parameters[i];
if (getDeclarationFlagsFromSymbol(p) & NodeFlags.Rest) {
writer.write("...");
writePunctuation(writer, SyntaxKind.DotDotDotToken);
}
writer.writeSymbol(p);
writeSymbol(p, writer);
if (p.valueDeclaration.flags & NodeFlags.QuestionMark || (<VariableDeclaration>p.valueDeclaration).initializer) {
writer.write("?");
writePunctuation(writer, SyntaxKind.QuestionToken);
}
writer.write(": ");
writePunctuation(writer, SyntaxKind.ColonToken);
writeSpace(writer);
writeType(getTypeOfSymbol(p), /*allowFunctionOrConstructorTypeLiteral*/ true);
}
writer.write(arrowStyle ? ") => " : "): ");
writePunctuation(writer, SyntaxKind.CloseParenToken);
if (arrowStyle) {
writeSpace(writer);
writePunctuation(writer, SyntaxKind.EqualsGreaterThanToken);
}
else {
writePunctuation(writer, SyntaxKind.ColonToken);
}
writeSpace(writer);
writeType(getReturnTypeOfSignature(signature), /*allowFunctionOrConstructorTypeLiteral*/ true);
}
}
@ -6356,7 +6558,7 @@ module ts {
}
}
function getConstantValue(node: Expression): number {
function getConstantValueForExpression(node: Expression): number {
var isNegative = false;
if (node.kind === SyntaxKind.PrefixOperator) {
var unaryExpression = <UnaryExpression>node;
@ -6373,38 +6575,51 @@ module ts {
return undefined;
}
function computeEnumMemberValues(node: EnumDeclaration) {
var nodeLinks = getNodeLinks(node);
if (!(nodeLinks.flags & NodeCheckFlags.EnumValuesComputed)) {
var enumSymbol = getSymbolOfNode(node);
var enumType = getDeclaredTypeOfSymbol(enumSymbol);
var autoValue = 0;
var ambient = isInAmbientContext(node);
forEach(node.members, member => {
var initializer = member.initializer;
if (initializer) {
autoValue = getConstantValueForExpression(initializer);
if (autoValue === undefined && !ambient) {
// Only here do we need to check that the initializer is assignable to the enum type.
// If it is a constant value (not undefined), it is syntactically constrained to be a number.
// Also, we do not need to check this for ambients because there is already
// a syntax error if it is not a constant.
checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*chainedMessage*/ undefined, /*terminalMessage*/ undefined);
}
}
else if (ambient) {
autoValue = undefined;
}
if (autoValue !== undefined) {
getNodeLinks(member).enumMemberValue = autoValue++;
}
});
nodeLinks.flags |= NodeCheckFlags.EnumValuesComputed;
}
}
function checkEnumDeclaration(node: EnumDeclaration) {
if (!fullTypeCheck) {
return;
}
checkTypeNameIsReserved(node.name, Diagnostics.Enum_name_cannot_be_0);
checkCollisionWithCapturedThisVariable(node, node.name);
checkCollistionWithRequireExportsInGeneratedCode(node, node.name);
checkExportsOnMergedDeclarations(node);
var enumSymbol = getSymbolOfNode(node);
var enumType = getDeclaredTypeOfSymbol(enumSymbol);
var autoValue = 0;
var ambient = isInAmbientContext(node);
forEach(node.members, member => {
var initializer = member.initializer;
if (initializer) {
autoValue = getConstantValue(initializer);
if (autoValue === undefined && !ambient) {
// Only here do we need to check that the initializer is assignable to the enum type.
// If it is a constant value (not undefined), it is syntactically constrained to be a number.
// Also, we do not need to check this for ambients because there is already
// a syntax error if it is not a constant.
checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*chainedMessage*/ undefined, /*terminalMessage*/ undefined);
}
}
else if (ambient) {
autoValue = undefined;
}
if (autoValue !== undefined) {
getNodeLinks(member).enumMemberValue = autoValue++;
}
});
computeEnumMemberValues(node);
// Spec 2014 - Section 9.3:
// It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
@ -6412,6 +6627,7 @@ module ts {
// for the first member.
//
// Only perform this check once per symbol
var enumSymbol = getSymbolOfNode(node);
var firstDeclaration = getDeclarationOfKind(enumSymbol, node.kind);
if (node === firstDeclaration) {
var seenEnumMissingInitialInitializer = false;
@ -7311,17 +7527,6 @@ module ts {
}
}
function getPropertyAccessSubstitution(node: PropertyAccess): string {
var symbol = getNodeLinks(node).resolvedSymbol;
if (symbol && (symbol.flags & SymbolFlags.EnumMember)) {
var declaration = symbol.valueDeclaration;
var constantValue: number;
if (declaration.kind === SyntaxKind.EnumMember && (constantValue = getNodeLinks(declaration).enumMemberValue) !== undefined) {
return constantValue.toString() + " /* " + identifierToString(declaration.name) + " */";
}
}
}
function getExportAssignmentName(node: SourceFile): string {
var symbol = getExportAssignmentSymbol(getSymbolOfNode(node));
return symbol && symbolIsValue(symbol) ? symbolToString(symbol): undefined;
@ -7384,20 +7589,51 @@ module ts {
}
function getEnumMemberValue(node: EnumMember): number {
computeEnumMemberValues(<EnumDeclaration>node.parent);
return getNodeLinks(node).enumMemberValue;
}
function getConstantValue(node: PropertyAccess): number {
var symbol = getNodeLinks(node).resolvedSymbol;
if (symbol && (symbol.flags & SymbolFlags.EnumMember)) {
var declaration = symbol.valueDeclaration;
var constantValue: number;
if (declaration.kind === SyntaxKind.EnumMember && (constantValue = getNodeLinks(declaration).enumMemberValue) !== undefined) {
return constantValue;
}
}
return undefined;
}
// Create a single instance that we can wrap the underlying emitter TextWriter with. That
// way we don't have to allocate a new wrapper every time writeTypeAtLocation and
// writeReturnTypeOfSignatureDeclaration are called.
var emitSymbolWriter = {
writer: <TextWriter>undefined,
writeKind: function (text: string) { this.writer.write(text) },
writeSymbol: function (text: string) { this.writer.write(text) },
writeLine: function () { this.writer.writeLine() },
increaseIndent: function () { this.writer.increaseIndent() },
decreaseIndent: function () { this.writer.decreaseIndent() },
clear: function () { },
trackSymbol: function (symbol: Symbol, declaration: Node, meaning: SymbolFlags) { this.writer.trackSymbol(symbol, declaration, meaning) }
};
function writeTypeAtLocation(location: Node, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: TextWriter) {
// Get type of the symbol if this is the valid symbol otherwise get type at location
var symbol = getSymbolOfNode(location);
var type = symbol && !(symbol.flags & SymbolFlags.TypeLiteral) ? getTypeOfSymbol(symbol) : getTypeFromTypeNode(location);
writeTypeToTextWriter(type, enclosingDeclaration, flags, writer);
emitSymbolWriter.writer = writer;
writeType(type, emitSymbolWriter, enclosingDeclaration, flags);
}
function writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: TextWriter) {
var signature = getSignatureFromDeclaration(signatureDeclaration);
writeTypeToTextWriter(getReturnTypeOfSignature(signature), enclosingDeclaration, flags , writer);
emitSymbolWriter.writer = writer;
writeType(getReturnTypeOfSignature(signature), emitSymbolWriter, enclosingDeclaration, flags);
}
function invokeEmitter(targetSourceFile?: SourceFile) {
@ -7405,7 +7641,6 @@ module ts {
getProgram: () => program,
getLocalNameOfContainer: getLocalNameOfContainer,
getExpressionNamePrefix: getExpressionNamePrefix,
getPropertyAccessSubstitution: getPropertyAccessSubstitution,
getExportAssignmentName: getExportAssignmentName,
isReferencedImportDeclaration: isReferencedImportDeclaration,
getNodeCheckFlags: getNodeCheckFlags,
@ -7416,9 +7651,9 @@ module ts {
isImplementationOfOverload: isImplementationOfOverload,
writeTypeAtLocation: writeTypeAtLocation,
writeReturnTypeOfSignatureDeclaration: writeReturnTypeOfSignatureDeclaration,
writeSymbol: writeSymbolToTextWriter,
isSymbolAccessible: isSymbolAccessible,
isImportDeclarationEntityNameReferenceDeclarationVisibile: isImportDeclarationEntityNameReferenceDeclarationVisibile
isImportDeclarationEntityNameReferenceDeclarationVisibile: isImportDeclarationEntityNameReferenceDeclarationVisibile,
getConstantValue: getConstantValue,
};
checkProgram();
return emitFiles(resolver, targetSourceFile);

View file

@ -101,7 +101,7 @@ module ts {
};
}
function createTextWriter(writeSymbol: (symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags)=> void): EmitTextWriter {
function createTextWriter(trackSymbol: (symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags)=> void): EmitTextWriter {
var output = "";
var indent = 0;
var lineStart = true;
@ -149,7 +149,7 @@ module ts {
return {
write: write,
writeSymbol: writeSymbol,
trackSymbol: trackSymbol,
rawWrite: rawWrite,
writeLiteral: writeLiteral,
writeLine: writeLine,
@ -182,7 +182,7 @@ module ts {
});
}
function emitComments(comments: Comment[], trailingSeparator: boolean, writer: EmitTextWriter, writeComment: (comment: Comment, writer: EmitTextWriter) => void) {
function emitComments(comments: CommentRange[], trailingSeparator: boolean, writer: EmitTextWriter, writeComment: (comment: CommentRange, writer: EmitTextWriter) => void) {
var emitLeadingSpace = !trailingSeparator;
forEach(comments, comment => {
if (emitLeadingSpace) {
@ -203,7 +203,7 @@ module ts {
});
}
function emitNewLineBeforeLeadingComments(node: TextRange, leadingComments: Comment[], writer: EmitTextWriter) {
function emitNewLineBeforeLeadingComments(node: TextRange, leadingComments: CommentRange[], writer: EmitTextWriter) {
// If the leading comments start on different line than the start of node, write new line
if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos &&
getLineOfLocalPosition(node.pos) !== getLineOfLocalPosition(leadingComments[0].pos)) {
@ -211,7 +211,7 @@ module ts {
}
}
function writeCommentRange(comment: Comment, writer: EmitTextWriter) {
function writeCommentRange(comment: CommentRange, writer: EmitTextWriter) {
if (currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk) {
var firstCommentLineAndCharacter = currentSourceFile.getLineAndCharacterFromPosition(comment.pos);
var firstCommentLineIndent: number;
@ -307,7 +307,7 @@ module ts {
}
function emitJavaScript(jsFilePath: string, root?: SourceFile) {
var writer = createTextWriter(writeSymbol);
var writer = createTextWriter(trackSymbol);
var write = writer.write;
var writeLine = writer.writeLine;
var increaseIndent = writer.increaseIndent;
@ -363,7 +363,7 @@ module ts {
/** Sourcemap data that will get encoded */
var sourceMapData: SourceMapData;
function writeSymbol(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags) { }
function trackSymbol(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags) { }
function initializeEmitterWithSourceMaps() {
var sourceMapDir: string; // The directory in which sourcemap will be
@ -585,23 +585,71 @@ module ts {
sourceMapNameIndices.pop();
};
function writeCommentRangeWithMap(comment: Comment, writer: EmitTextWriter) {
function writeCommentRangeWithMap(comment: CommentRange, writer: EmitTextWriter) {
recordSourceMapSpan(comment.pos);
writeCommentRange(comment, writer);
recordSourceMapSpan(comment.end);
}
var escapedCharsRegExp = /[\t\v\f\b\0\r\n\"\u2028\u2029\u0085]/g;
var escapedCharsMap: Map<string> = {
"\t": "\\t",
"\v": "\\v",
"\f": "\\f",
"\b": "\\b",
"\0": "\\0",
"\r": "\\r",
"\n": "\\n",
"\"": "\\\"",
"\u2028": "\\u2028", // lineSeparator
"\u2029": "\\u2029", // paragraphSeparator
"\u0085": "\\u0085" // nextLine
};
function serializeSourceMapContents(version: number, file: string, sourceRoot: string, sources: string[], names: string[], mappings: string) {
if (typeof JSON !== "undefined") {
return JSON.stringify({
version: version,
file: file,
sourceRoot: sourceRoot,
sources: sources,
names: names,
mappings: mappings
});
}
return "{\"version\":" + version + ",\"file\":\"" + escapeString(file) + "\",\"sourceRoot\":\"" + escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + escapeString(mappings) + "\"}";
/** This does not support the full escape characters, it only supports the subset that can be used in file names
* or string literals. If the information encoded in the map changes, this needs to be revisited. */
function escapeString(s: string): string {
return escapedCharsRegExp.test(s) ? s.replace(escapedCharsRegExp, c => {
return escapedCharsMap[c] || c;
}) : s;
}
function serializeStringArray(list: string[]): string {
var output = "";
for (var i = 0, n = list.length; i < n; i++) {
if (i) {
output += ",";
}
output += "\"" + escapeString(list[i]) + "\"";
}
return output;
}
}
function writeJavaScriptAndSourceMapFile(emitOutput: string, writeByteOrderMark: boolean) {
// Write source map file
encodeLastRecordedSourceMapSpan();
writeFile(sourceMapData.sourceMapFilePath, JSON.stringify({
version: 3,
file: sourceMapData.sourceMapFile,
sourceRoot: sourceMapData.sourceMapSourceRoot,
sources: sourceMapData.sourceMapSources,
names: sourceMapData.sourceMapNames,
mappings: sourceMapData.sourceMapMappings
}), /*writeByteOrderMark*/ false);
writeFile(sourceMapData.sourceMapFilePath, serializeSourceMapContents(
3,
sourceMapData.sourceMapFile,
sourceMapData.sourceMapSourceRoot,
sourceMapData.sourceMapSources,
sourceMapData.sourceMapNames,
sourceMapData.sourceMapMappings), /*writeByteOrderMark*/ false);
sourceMapDataList.push(sourceMapData);
// Write sourcemap url to the js file and write the js file
@ -891,14 +939,15 @@ module ts {
}
function emitPropertyAccess(node: PropertyAccess) {
var text = resolver.getPropertyAccessSubstitution(node);
if (text) {
write(text);
return;
var constantValue = resolver.getConstantValue(node);
if (constantValue !== undefined) {
write(constantValue.toString() + " /* " + identifierToString(node.right) + " */");
}
else {
emit(node.left);
write(".");
emit(node.right);
}
emit(node.left);
write(".");
emit(node.right);
}
function emitIndexedAccess(node: IndexedAccess) {
@ -2130,7 +2179,7 @@ module ts {
function getLeadingCommentsWithoutDetachedComments() {
// get the leading comments from detachedPos
var leadingComments = getLeadingComments(currentSourceFile.text, detachedCommentsInfo[detachedCommentsInfo.length - 1].detachedCommentEndPos);
var leadingComments = getLeadingCommentRanges(currentSourceFile.text, detachedCommentsInfo[detachedCommentsInfo.length - 1].detachedCommentEndPos);
if (detachedCommentsInfo.length - 1) {
detachedCommentsInfo.pop();
}
@ -2144,14 +2193,14 @@ module ts {
function getLeadingCommentsToEmit(node: Node) {
// Emit the leading comments only if the parent's pos doesn't match because parent should take care of emitting these comments
if (node.parent.kind === SyntaxKind.SourceFile || node.pos !== node.parent.pos) {
var leadingComments: Comment[];
var leadingComments: CommentRange[];
if (hasDetachedComments(node.pos)) {
// get comments without detached comments
leadingComments = getLeadingCommentsWithoutDetachedComments();
}
else {
// get the leading comments from the node
leadingComments = getLeadingCommentsOfNode(node, currentSourceFile);
leadingComments = getLeadingCommentRangesOfNode(node, currentSourceFile);
}
return leadingComments;
}
@ -2167,21 +2216,21 @@ module ts {
function emitTrailingDeclarationComments(node: Node) {
// Emit the trailing comments only if the parent's end doesn't match
if (node.parent.kind === SyntaxKind.SourceFile || node.end !== node.parent.end) {
var trailingComments = getTrailingComments(currentSourceFile.text, node.end);
var trailingComments = getTrailingCommentRanges(currentSourceFile.text, node.end);
// trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/
emitComments(trailingComments, /*trailingSeparator*/ false, writer, writeComment);
}
}
function emitLeadingCommentsOfLocalPosition(pos: number) {
var leadingComments: Comment[];
var leadingComments: CommentRange[];
if (hasDetachedComments(pos)) {
// get comments without detached comments
leadingComments = getLeadingCommentsWithoutDetachedComments();
}
else {
// get the leading comments from the node
leadingComments = getLeadingComments(currentSourceFile.text, pos);
leadingComments = getLeadingCommentRanges(currentSourceFile.text, pos);
}
emitNewLineBeforeLeadingComments({ pos: pos, end: pos }, leadingComments, writer);
// Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
@ -2189,10 +2238,10 @@ module ts {
}
function emitDetachedCommentsAtPosition(node: TextRange) {
var leadingComments = getLeadingComments(currentSourceFile.text, node.pos);
var leadingComments = getLeadingCommentRanges(currentSourceFile.text, node.pos);
if (leadingComments) {
var detachedComments: Comment[] = [];
var lastComment: Comment;
var detachedComments: CommentRange[] = [];
var lastComment: CommentRange;
forEach(leadingComments, comment => {
if (lastComment) {
@ -2236,7 +2285,7 @@ module ts {
function emitPinnedOrTripleSlashCommentsOfNode(node: Node) {
var pinnedComments = ts.filter(getLeadingCommentsToEmit(node), isPinnedOrTripleSlashComment);
function isPinnedOrTripleSlashComment(comment: Comment) {
function isPinnedOrTripleSlashComment(comment: CommentRange) {
if (currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk) {
return currentSourceFile.text.charCodeAt(comment.pos + 2) === CharacterCodes.exclamation;
}
@ -2275,7 +2324,7 @@ module ts {
}
function emitDeclarations(jsFilePath: string, root?: SourceFile) {
var writer = createTextWriter(writeSymbol);
var writer = createTextWriter(trackSymbol);
var write = writer.write;
var writeLine = writer.writeLine;
var increaseIndent = writer.increaseIndent;
@ -2303,7 +2352,7 @@ module ts {
var oldWriter = writer;
forEach(importDeclarations, aliasToWrite => {
var aliasEmitInfo = forEach(aliasDeclarationEmitInfo, declEmitInfo => declEmitInfo.declaration === aliasToWrite ? declEmitInfo : undefined);
writer = createTextWriter(writeSymbol);
writer = createTextWriter(trackSymbol);
for (var declarationIndent = aliasEmitInfo.indent; declarationIndent; declarationIndent--) {
writer.increaseIndent();
}
@ -2314,10 +2363,9 @@ module ts {
writer = oldWriter;
}
function writeSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags) {
function trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags) {
var symbolAccesibilityResult = resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning);
if (symbolAccesibilityResult.accessibility === SymbolAccessibility.Accessible) {
resolver.writeSymbol(symbol, enclosingDeclaration, meaning, writer);
// write the aliases
if (symbolAccesibilityResult && symbolAccesibilityResult.aliasesToMakeVisible) {

View file

@ -138,25 +138,27 @@ module ts {
return (<Identifier>(<ExpressionStatement>node).expression).text === "use strict";
}
export function getLeadingCommentsOfNode(node: Node, sourceFileOfNode: SourceFile) {
export function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode?: SourceFile) {
sourceFileOfNode = sourceFileOfNode || getSourceFileOfNode(node);
// If parameter/type parameter, the prev token trailing comments are part of this node too
if (node.kind === SyntaxKind.Parameter || node.kind === SyntaxKind.TypeParameter) {
// e.g. (/** blah */ a, /** blah */ b);
return concatenate(getTrailingComments(sourceFileOfNode.text, node.pos),
return concatenate(getTrailingCommentRanges(sourceFileOfNode.text, node.pos),
// e.g.: (
// /** blah */ a,
// /** blah */ b);
getLeadingComments(sourceFileOfNode.text, node.pos));
getLeadingCommentRanges(sourceFileOfNode.text, node.pos));
}
else {
return getLeadingComments(sourceFileOfNode.text, node.pos);
return getLeadingCommentRanges(sourceFileOfNode.text, node.pos);
}
}
export function getJsDocComments(node: Declaration, sourceFileOfNode: SourceFile) {
return filter(getLeadingCommentsOfNode(node, sourceFileOfNode), comment => isJsDocComment(comment));
return filter(getLeadingCommentRangesOfNode(node, sourceFileOfNode), comment => isJsDocComment(comment));
function isJsDocComment(comment: Comment) {
function isJsDocComment(comment: CommentRange) {
// True if the comment starts with '/**' but not if it is '/**/'
return sourceFileOfNode.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk &&
sourceFileOfNode.text.charCodeAt(comment.pos + 2) === CharacterCodes.asterisk &&
@ -813,7 +815,7 @@ module ts {
// applying some stricter checks on that node.
function grammarErrorOnNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): void {
var span = getErrorSpanForNode(node);
var start = skipTrivia(file.text, span.pos);
var start = span.end > span.pos ? skipTrivia(file.text, span.pos) : span.pos;
var length = span.end - start;
file.syntacticErrors.push(createFileDiagnostic(file, start, length, message, arg0, arg1, arg2));

View file

@ -371,8 +371,8 @@ module ts {
// between the given position and the next line break are returned. The return value is an array containing a TextRange for each
// comment. Single-line comment ranges include the beginning '//' characters but not the ending line break. Multi-line comment
// ranges include the beginning '/* and ending '*/' characters. The return value is undefined if no comments were found.
function getCommentRanges(text: string, pos: number, trailing: boolean): Comment[] {
var result: Comment[];
function getCommentRanges(text: string, pos: number, trailing: boolean): CommentRange[] {
var result: CommentRange[];
var collecting = trailing || pos === 0;
while (true) {
var ch = text.charCodeAt(pos);
@ -440,11 +440,11 @@ module ts {
}
}
export function getLeadingComments(text: string, pos: number): Comment[] {
export function getLeadingCommentRanges(text: string, pos: number): CommentRange[] {
return getCommentRanges(text, pos, /*trailing*/ false);
}
export function getTrailingComments(text: string, pos: number): Comment[] {
export function getTrailingCommentRanges(text: string, pos: number): CommentRange[] {
return getCommentRanges(text, pos, /*trailing*/ true);
}

View file

@ -202,6 +202,11 @@ module ts {
var compilerOptions = commandLine.options;
if (compilerOptions.locale) {
if (typeof JSON === "undefined") {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--locale"));
return sys.exit(1);
}
validateLocaleAndSetLanguage(commandLine.options.locale, commandLine.errors);
}

View file

@ -228,7 +228,9 @@ module ts {
FirstPunctuation = OpenBraceToken,
LastPunctuation = CaretEqualsToken,
FirstToken = EndOfFileToken,
LastToken = StringKeyword
LastToken = StringKeyword,
FirstTriviaToken = SingleLineCommentTrivia,
LastTriviaToken = WhitespaceTrivia
}
export enum NodeFlags {
@ -531,7 +533,7 @@ module ts {
filename: string;
}
export interface Comment extends TextRange {
export interface CommentRange extends TextRange {
hasTrailingNewLine?: boolean;
}
@ -642,16 +644,22 @@ module ts {
getApparentType(type: Type): ApparentType;
typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string;
symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string;
typeToDisplayParts(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): SymbolDisplayPart[];
symbolToDisplayParts(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): SymbolDisplayPart[];
getFullyQualifiedName(symbol: Symbol): string;
getAugmentedPropertiesOfApparentType(type: Type): Symbol[];
getRootSymbol(symbol: Symbol): Symbol;
getContextualType(node: Node): Type;
getResolvedSignature(node: CallExpression, candidatesOutArray?: Signature[]): Signature;
// Returns the constant value of this enum member, or 'undefined' if the enum member has a
// computed value.
getEnumMemberValue(node: EnumMember): number;
}
export interface TextWriter {
write(s: string): void;
writeSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void;
trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void;
writeLine(): void;
increaseIndent(): void;
decreaseIndent(): void;
@ -682,7 +690,6 @@ module ts {
getProgram(): Program;
getLocalNameOfContainer(container: Declaration): string;
getExpressionNamePrefix(node: Identifier): string;
getPropertyAccessSubstitution(node: PropertyAccess): string;
getExportAssignmentName(node: SourceFile): string;
isReferencedImportDeclaration(node: ImportDeclaration): boolean;
isTopLevelValueImportedViaEntityName(node: ImportDeclaration): boolean;
@ -693,9 +700,12 @@ module ts {
isImplementationOfOverload(node: FunctionDeclaration): boolean;
writeTypeAtLocation(location: Node, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: TextWriter): void;
writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: TextWriter): void;
writeSymbol(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags, writer: TextWriter): void;
isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessiblityResult;
isImportDeclarationEntityNameReferenceDeclarationVisibile(entityName: EntityName): SymbolAccessiblityResult;
// Returns the constant value this property access resolves to, or 'undefined' if it does
// resolve to a constant.
getConstantValue(node: PropertyAccess): number;
}
export enum SymbolFlags {
@ -797,13 +807,16 @@ module ts {
}
export enum NodeCheckFlags {
TypeChecked = 0x00000001, // Node has been type checked
LexicalThis = 0x00000002, // Lexical 'this' reference
CaptureThis = 0x00000004, // Lexical 'this' used in body
EmitExtends = 0x00000008, // Emit __extends
SuperInstance = 0x00000010, // Instance 'super' reference
SuperStatic = 0x00000020, // Static 'super' reference
ContextChecked = 0x00000040, // Contextual types have been assigned
TypeChecked = 0x00000001, // Node has been type checked
LexicalThis = 0x00000002, // Lexical 'this' reference
CaptureThis = 0x00000004, // Lexical 'this' used in body
EmitExtends = 0x00000008, // Emit __extends
SuperInstance = 0x00000010, // Instance 'super' reference
SuperStatic = 0x00000020, // Static 'super' reference
ContextChecked = 0x00000040, // Contextual types have been assigned
// Values for enum members have been computed, and any errors have been reported for them.
EnumValuesComputed = 0x00000080,
}
export interface NodeLinks {
@ -1174,6 +1187,48 @@ module ts {
verticalTab = 0x0B, // \v
}
export class SymbolDisplayPart {
constructor(public text: string,
public kind: SymbolDisplayPartKind,
public symbol: Symbol) {
}
public toJSON() {
return {
text: this.text,
kind: SymbolDisplayPartKind[this.kind]
};
}
}
export enum SymbolDisplayPartKind {
aliasName,
className,
enumName,
fieldName,
interfaceName,
keyword,
labelName,
lineBreak,
numericLiteral,
stringLiteral,
localName,
methodName,
moduleName,
namespaceName,
operator,
parameterName,
propertyName,
punctuation,
space,
anonymousTypeIndicator,
text,
typeParameterName,
enumMemberName,
functionName,
regularExpressionLiteral,
}
export interface CancellationToken {
isCancellationRequested(): boolean;
}

View file

@ -1,225 +0,0 @@
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement, fromIndex) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) {
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (fun, thisp) {
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = [];
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
if (!Array.prototype.map) {
Array.prototype.map = function (callback, thisArg) {
var T = undefined, A, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
// 1. Let O be the result of calling ToObject passing the |this| value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
if ({}.toString.call(callback) != "[object Function]") {
throw new TypeError(callback + " is not a function");
}
if (thisArg) {
T = thisArg;
}
// 6. Let A be a new array created as if by the expression new Array(len) where Array is
// the standard built-in constructor with that name and len is the value of len.
A = new Array(len);
// 7. Let k be 0
k = 0;
while (k < len) {
var kValue, mappedValue;
if (k in O) {
// i. Let kValue be the result of calling the Get internal method of O with argument Pk.
kValue = O[k];
// ii. Let mappedValue be the result of calling the Call internal method of callback
// with T as the this value and argument list containing kValue, k, and O.
mappedValue = callback.call(T, kValue, k, O);
// iii. Call the DefineOwnProperty internal method of A with arguments
// Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
// and false.
// In browsers that support Object.defineProperty, use the following:
// Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
// For best browser support, use the following:
A[k] = mappedValue;
}
// d. Increase k by 1.
k++;
}
// 9. return A
return A;
};
}
if (!Array.prototype.reduce) {
Array.prototype.reduce = function reduce(accumulator) {
if (this === null || this === undefined)
throw new TypeError("Object is null or undefined");
var i = 0, l = this.length >> 0, curr;
if (typeof accumulator !== "function")
throw new TypeError("First argument is not callable");
if (arguments.length < 2) {
if (l === 0)
throw new TypeError("Array length is 0 and no second argument");
curr = this[0];
i = 1;
} else
curr = arguments[1];
while (i < l) {
if (i in this)
curr = accumulator.call(undefined, curr, this[i], i, this);
++i;
}
return curr;
};
}
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
// 1. Let O be the result of calling ToObject passing the |this| value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
if ({}.toString.call(callback) != "[object Function]") {
throw new TypeError(callback + " is not a function");
}
if (thisArg) {
T = thisArg;
} else {
T = undefined;
}
// 6. Let k be 0
k = 0;
while (k < len) {
var kValue;
if (k in O) {
// i. Let kValue be the result of calling the Get internal method of O with argument Pk.
kValue = O[k];
// ii. Call the Call internal method of callback with T as the this value and
// argument list containing kValue, k, and O.
callback.call(T, kValue, k, O);
}
// d. Increase k by 1.
k++;
}
// 8. return undefined
};
}
if (!Date.now) {
Date.now = function () {
return (new Date()).getTime();
};
}
if (!Array.prototype.some) {
Array.prototype.some = function (fun/*, thisp */ ) {
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
var idx = i.toString();
if (idx in t && fun.call(thisp, t[i], i, t))
return true;
}
return false;
};
}

View file

@ -1,354 +0,0 @@
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/*----------------- ThirdPartyNotices -------------------------------------------------------
This file is based on or incorporates material from the projects listed below
(collectively "Third Party Code"). Microsoft is not the original author of the
Third Party Code. The original copyright notice and the license, under which
Microsoft received such Third Party Code, are set forth below. Such license and
notices are provided for informational purposes only. Microsoft licenses the Third
Party Code to you under the terms of the Apache 2.0 License.
--
Array filter Compatibility Method,
Available at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
Array forEach Compatibility Method,
Available at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
Array indexOf Compatibility Method,
Available at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
Array map Compatibility Method,
Available at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
Array Reduce Compatibility Method,
Available at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/Reduce
Array some Compatibility Method,
Available at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/some
String Trim Compatibility Method,
Available at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/Trim
Date now Compatibility Method,
Available at https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/now
Copyright (c) 2007 - 2012 Mozilla Developer Network and individual contributors
Licensed by Microsoft under the Apache License, Version 2.0 (the "License"); you
may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR
CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions and
limitations under the License.
--
Original License provided for Informational Purposes Only
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------- End of ThirdPartyNotices --------------------------------------------------- */
// Compatibility with non ES5 compliant engines
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
// Compatibility with non ES5 compliant engines
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement: any, fromIndex?: any) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len: any = t.length >>> 0;
if (len === 0) {
return -1;
}
var n: any = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
}
else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || <any>-1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k: any = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun: any, thisp?: any)
{
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res: any[] = [];
for (var i = 0; i < len; i++)
{
if (<any>i in t)
{
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.com/#x15.4.4.19
if (!Array.prototype.map) {
Array.prototype.map = function(callback: any, thisArg?: any) {
var T: any = undefined, A: any, k: any;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
// 1. Let O be the result of calling ToObject passing the |this| value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If IsCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if ({}.toString.call(callback) != "[object Function]") {
throw new TypeError(callback + " is not a function");
}
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (thisArg) {
T = thisArg;
}
// 6. Let A be a new array created as if by the expression new Array(len) where Array is
// the standard built-in constructor with that name and len is the value of len.
A = new Array(len);
// 7. Let k be 0
k = 0;
// 8. Repeat, while k < len
while(k < len) {
var kValue: any, mappedValue: any;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal method of O with argument Pk.
kValue = O[ k ];
// ii. Let mappedValue be the result of calling the Call internal method of callback
// with T as the this value and argument list containing kValue, k, and O.
mappedValue = callback.call(T, kValue, k, O);
// iii. Call the DefineOwnProperty internal method of A with arguments
// Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
// and false.
// In browsers that support Object.defineProperty, use the following:
// Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
// For best browser support, use the following:
A[ k ] = mappedValue;
}
// d. Increase k by 1.
k++;
}
// 9. return A
return A;
};
}
if (!Array.prototype.reduce) {
Array.prototype.reduce = function reduce(accumulator: any){
if (this===null || this===undefined) throw new TypeError("Object is null or undefined");
var i = 0, l = this.length >> 0, curr: any;
if(typeof accumulator !== "function") // ES5 : "If IsCallable(callbackfn) is false, throw a TypeError exception."
throw new TypeError("First argument is not callable");
if(arguments.length < 2) {
if (l === 0) throw new TypeError("Array length is 0 and no second argument");
curr = this[0];
i = 1; // start accumulating at the second element
}
else
curr = arguments[1];
while (i < l) {
if(<any>i in this) curr = accumulator.call(undefined, curr, this[i], i, this);
++i;
}
return curr;
};
}
// Compatibility with non ES5 compliant engines
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.com/#x15.4.4.18
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(callback: any, thisArg?: any) {
var T: any, k: any;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
// 1. Let O be the result of calling ToObject passing the |this| value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // Hack to convert O.length to a UInt32
// 4. If IsCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if ({ }.toString.call(callback) != "[object Function]") {
throw new TypeError(callback + " is not a function");
}
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (thisArg) {
T = thisArg;
}
else {
T = undefined; // added to stop definite assignment error
}
// 6. Let k be 0
k = 0;
// 7. Repeat, while k < len
while (k < len) {
var kValue: any;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal method of O with argument Pk.
kValue = O[k];
// ii. Call the Call internal method of callback with T as the this value and
// argument list containing kValue, k, and O.
callback.call(T, kValue, k, O);
}
// d. Increase k by 1.
k++;
}
// 8. return undefined
};
}
// Compatibility with non ES5 compliant engines
if (!Date.now) {
Date.now = function() {
return (new Date()).getTime();
};
}
// Compatibility with non ES5 compliant engines
// Production steps of ECMA-262, Edition 5.1, 15.4.4.17
if (!Array.prototype.some)
{
Array.prototype.some = function(fun: any /*, thisp */)
{
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
var idx = i.toString(); // REVIEW: this line is not from the Mozilla page, necessary to avoid our compile time checks against non-string/any types in an in expression
if (idx in t && fun.call(thisp, t[i], i, t))
return true;
}
return false;
};
}

View file

@ -1,486 +0,0 @@
/*
json2.js
2013-05-26
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or '&nbsp;'),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON !== 'object') {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function () {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function () {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());

View file

@ -1,486 +0,0 @@
/*
json2.js
2013-05-26
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or '&nbsp;'),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON !== 'object') {
JSON = <any>{};
}
(function () {
'use strict';
function f(n: any) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function () {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
(<any>String.prototype).toJSON =
(<any>Number.prototype).toJSON =
(<any>Boolean.prototype).toJSON = function () {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap: any,
indent: any,
meta = <any>{ // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep: any;
function quote(string: string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key: any, holder: any) {
// Produce a string from holder[key].
var i: any, // The loop counter.
k: any, // The member key.
v: any, // The member value.
length: number,
mind = gap,
partial: any,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = <any>function (value: any, replacer: any, space: any) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i: any;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j: any;
function walk(holder: any, key: any) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k: any, v: any, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());

View file

@ -1660,9 +1660,9 @@ module FourSlash {
}
var actualMatchPosition = -1;
if (bracePosition >= actual[0].start() && bracePosition <= actual[0].end()) {
if (bracePosition === actual[0].start()) {
actualMatchPosition = actual[1].start();
} else if (bracePosition >= actual[1].start() && bracePosition <= actual[1].end()) {
} else if (bracePosition === actual[1].start()) {
actualMatchPosition = actual[0].start();
} else {
throw new Error('verifyMatchingBracePosition failed - could not find the brace position: ' + bracePosition + ' in the returned list: (' + actual[0].start() + ',' + actual[0].end() + ') and (' + actual[1].start() + ',' + actual[1].end() + ')');

View file

@ -1,73 +0,0 @@
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///<reference path='references.ts' />
module TypeScript.Services {
export class BraceMatcher {
// Given a script name and position in the script, return a pair of text range if the
// position corresponds to a "brace matchin" characters (e.g. "{" or "(", etc.)
// If the position is not on any range, return an empty set.
public static getMatchSpans(syntaxTree: TypeScript.SyntaxTree, position: number): TypeScript.TextSpan[] {
var result: TypeScript.TextSpan[] = [];
var token = findToken(syntaxTree.sourceUnit(), position);
if (start(token) === position) {
var matchKind = BraceMatcher.getMatchingTokenKind(token);
if (matchKind !== null) {
var parentElement = token.parent;
for (var i = 0, n = childCount(parentElement); i < n; i++) {
var current = childAt(parentElement, i);
if (current !== null && fullWidth(current) > 0) {
if (current.kind() === matchKind) {
var range1 = new TypeScript.TextSpan(start(token), width(token));
var range2 = new TypeScript.TextSpan(start(current), width(current));
if (range1.start() < range2.start()) {
result.push(range1, range2);
}
else {
result.push(range2, range1);
}
break;
}
}
}
}
}
return result;
}
private static getMatchingTokenKind(token: TypeScript.ISyntaxToken): TypeScript.SyntaxKind {
switch (token.kind()) {
case TypeScript.SyntaxKind.OpenBraceToken: return TypeScript.SyntaxKind.CloseBraceToken
case TypeScript.SyntaxKind.OpenParenToken: return TypeScript.SyntaxKind.CloseParenToken;
case TypeScript.SyntaxKind.OpenBracketToken: return TypeScript.SyntaxKind.CloseBracketToken;
case TypeScript.SyntaxKind.LessThanToken: return TypeScript.SyntaxKind.GreaterThanToken;
case TypeScript.SyntaxKind.CloseBraceToken: return TypeScript.SyntaxKind.OpenBraceToken
case TypeScript.SyntaxKind.CloseParenToken: return TypeScript.SyntaxKind.OpenParenToken;
case TypeScript.SyntaxKind.CloseBracketToken: return TypeScript.SyntaxKind.OpenBracketToken;
case TypeScript.SyntaxKind.GreaterThanToken: return TypeScript.SyntaxKind.LessThanToken;
}
return null;
}
}
}

View file

@ -7,7 +7,6 @@
/// <reference path='syntax\incrementalParser.ts' />
/// <reference path='outliningElementsCollector.ts' />
/// <reference path='getScriptLexicalStructureWalker.ts' />
/// <reference path='braceMatcher.ts' />
/// <reference path='breakpoints.ts' />
/// <reference path='indentation.ts' />
/// <reference path='signatureHelp.ts' />
@ -48,6 +47,7 @@ module ts {
getFlags(): SymbolFlags;
getName(): string;
getDeclarations(): Declaration[];
getDocumentationComment(): string;
}
export interface Type {
@ -99,9 +99,7 @@ module ts {
private _children: Node[];
public getSourceFile(): SourceFile {
var node: Node = this;
while (node.kind !== SyntaxKind.SourceFile) node = node.parent;
return <SourceFile>node;
return getSourceFileOfNode(this);
}
public getStart(sourceFile?: SourceFile): number {
@ -227,19 +225,176 @@ module ts {
flags: SymbolFlags;
name: string;
declarations: Declaration[];
// Undefined is used to indicate the value has not been computed. If, after computing, the
// symbol has no doc comment, then the empty string will be returned.
documentationComment: string;
constructor(flags: SymbolFlags, name: string) {
this.flags = flags;
this.name = name;
}
getFlags(): SymbolFlags {
return this.flags;
}
getName(): string {
return this.name;
}
getDeclarations(): Declaration[] {
return this.declarations;
}
getDocumentationComment(): string {
if (this.documentationComment === undefined) {
var lines: string[] = [];
// Get the doc comments from all the declarations of this symbol, and merge them
// into one single doc comment.
var declarations = this.getDeclarations();
if (declarations) {
for (var i = 0, n = declarations.length; i < n; i++) {
this.processDocumentationCommentDeclaration(lines, declarations[0]);
}
}
// TODO: get the newline info from the host.
this.documentationComment = lines.join("\r\n");
}
return this.documentationComment;
}
private processDocumentationCommentDeclaration(lines: string[], declaration: Node) {
var commentRanges = getLeadingCommentRangesOfNode(declaration);
if (commentRanges) {
var sourceFile = declaration.getSourceFile();
for (var i = 0, n = commentRanges.length; i < n; i++) {
this.processDocumentationCommentRange(
lines, sourceFile, commentRanges[0]);
}
}
}
private processDocumentationCommentRange(lines: string[], sourceFile: SourceFile, commentRange: CommentRange) {
// We only care about well-formed /** */ comments
if (commentRange.end - commentRange.pos > "/**/".length &&
sourceFile.text.substr(commentRange.pos, "/**".length) === "/**" &&
sourceFile.text.substr(commentRange.end - "*/".length, "*/".length) === "*/") {
// Put a newline between each converted comment we join together.
if (lines.length) {
lines.push("");
}
var startLineAndChar = sourceFile.getLineAndCharacterFromPosition(commentRange.pos);
var endLineAndChar = sourceFile.getLineAndCharacterFromPosition(commentRange.end);
if (startLineAndChar.line === endLineAndChar.line) {
// A single line doc comment. Just extract the text between the
// comment markers and add that to the doc comment we're building
// up.
lines.push(sourceFile.text.substring(commentRange.pos + "/**".length, commentRange.end - "*/".length).trim());
}
else {
this.processMultiLineDocumentationCommentRange(sourceFile, commentRange, startLineAndChar, endLineAndChar, lines);
}
}
}
private processMultiLineDocumentationCommentRange(
sourceFile: SourceFile, commentRange: CommentRange,
startLineAndChar: { line: number; character: number },
endLineAndChar: { line: number; character: number },
lines: string[]) {
// Comment spanned multiple lines. Find the leftmost character
// position in each line, and use that to determine what we should
// trim off, and what part of the line to keep.
// i.e. if the comment looks like:
//
// /** Foo
// * Bar
// * Baz
// */
//
// Then we'll want to add:
// Foo
// Bar
// Baz
var trimLength: number = undefined;
for (var iLine = startLineAndChar.line + 1; iLine <= endLineAndChar.line; iLine++) {
var lineStart = sourceFile.getPositionFromLineAndCharacter(iLine, /*character:*/ 1);
var lineEnd = iLine === endLineAndChar.line
? commentRange.end - "*/".length
: sourceFile.getPositionFromLineAndCharacter(iLine + 1, 1);
var docCommentTriviaLength = this.skipDocumentationCommentTrivia(sourceFile.text, lineStart, lineEnd);
if (trimLength === undefined || (docCommentTriviaLength && docCommentTriviaLength < trimLength)) {
trimLength = docCommentTriviaLength;
}
}
// Add the first line in.
var firstLine = sourceFile.text.substring(
commentRange.pos + "/**".length,
sourceFile.getPositionFromLineAndCharacter(startLineAndChar.line + 1, /*character:*/ 1)).trim();
if (firstLine !== "") {
lines.push(firstLine);
}
// For all the lines up to the last (but not including the last), add the contents
// of the line (with the length up to the
for (var iLine = startLineAndChar.line + 1; iLine < endLineAndChar.line; iLine++) {
var line = this.trimRight(sourceFile.text.substring(
sourceFile.getPositionFromLineAndCharacter(iLine, /*character*/ 1),
sourceFile.getPositionFromLineAndCharacter(iLine + 1, /*character*/ 1))).substr(trimLength);
lines.push(line);
}
// Add the last line if there is any actual text before the */
var lastLine = this.trimRight(sourceFile.text.substring(
sourceFile.getPositionFromLineAndCharacter(endLineAndChar.line, /*character:*/ 1),
commentRange.end - "*/".length)).substr(trimLength);
if (lastLine !== "") {
lines.push(lastLine);
}
}
private trimRight(val: string) {
return val.replace(/(\n|\r|\s)+$/, '');
}
private skipDocumentationCommentTrivia(text: string, lineStart: number, lineEnd: number): number {
var seenAsterisk = false;
var lineLength = lineEnd - lineStart;
for (var i = 0; i < lineLength; i++) {
var char = text.charCodeAt(i + lineStart);
if (char === CharacterCodes.asterisk && !seenAsterisk) {
// Ignore the first asterisk we see. We want to trim out the line of *'s
// commonly seen at the start of a doc comment.
seenAsterisk = true;
continue;
}
else if (isLineBreak(char)) {
// This was a blank line. Just ignore it wrt computing the leading whitespace to
// trim.
break;
}
else if (!isWhiteSpace(char)) {
// Found a real doc comment character. Keep track of it so we can determine how
// much of the doc comment leading trivia to trim off.
return i;
}
}
return undefined;
}
}
class TypeObject implements Type {
@ -497,6 +652,7 @@ module ts {
getCompletionEntryDetails(fileName: string, position: number, entryName: string): CompletionEntryDetails;
getTypeAtPosition(fileName: string, position: number): TypeInfo;
getQuickInfoAtPosition(fileName: string, position: number): QuickInfo;
getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TypeScript.TextSpan;
@ -654,6 +810,15 @@ module ts {
text: string;
}
export class QuickInfo {
constructor(public kind: string,
public kindModifiers: string,
public textSpan: TypeScript.TextSpan,
public displayParts: SymbolDisplayPart[],
public documentation: SymbolDisplayPart[]) {
}
}
export class TypeInfo {
constructor(
public memberName: TypeScript.MemberName,
@ -1470,11 +1635,14 @@ module ts {
var formattingRulesProvider: TypeScript.Services.Formatting.RulesProvider;
var hostCache: HostCache; // A cache of all the information about the files on the host side.
var program: Program;
// this checker is used to answer all LS questions except errors
var typeInfoResolver: TypeChecker;
// the sole purpose of this checker is to return semantic diagnostics
// creation is deferred - use getFullTypeCheckChecker to get instance
var fullTypeCheckChecker_doNotAccessDirectly: TypeChecker;
var useCaseSensitivefilenames = false;
var sourceFilesByName: Map<SourceFile> = {};
var documentRegistry = documentRegistry;
@ -1715,11 +1883,10 @@ module ts {
return undefined;
}
var declarations = symbol.getDeclarations();
return {
name: displayName,
kind: getSymbolKind(symbol),
kindModifiers: declarations ? getNodeModifiers(declarations[0]) : ScriptElementKindModifier.none
kindModifiers: getSymbolModifiers(symbol)
};
}
@ -2166,6 +2333,12 @@ module ts {
}
}
function getSymbolModifiers(symbol: Symbol): string {
return symbol && symbol.declarations && symbol.declarations.length > 0
? getNodeModifiers(symbol.declarations[0])
: ScriptElementKindModifier.none;
}
function getNodeModifiers(node: Node): string {
var flags = node.flags;
var result: string[] = [];
@ -2179,7 +2352,114 @@ module ts {
return result.length > 0 ? result.join(',') : ScriptElementKindModifier.none;
}
/// QuickInfo
function getQuickInfoAtPosition(fileName: string, position: number): QuickInfo {
synchronizeHostData();
fileName = TypeScript.switchToForwardSlashes(fileName);
var sourceFile = getSourceFile(fileName);
var node = getNodeAtPosition(sourceFile, position);
if (!node) {
return undefined;
}
var symbol = typeInfoResolver.getSymbolInfo(node);
if (!symbol) {
return undefined;
}
var documentation = symbol.getDocumentationComment();
var documentationParts = documentation === "" ? [] : [new SymbolDisplayPart(documentation, SymbolDisplayPartKind.text, /*symbol:*/ null)];
// Having all this logic here is pretty unclean. Consider moving to the roslyn model
// where all symbol display logic is encapsulated into visitors and options.
var totalParts: SymbolDisplayPart[] = [];
if (symbol.flags & SymbolFlags.Class) {
totalParts.push(new SymbolDisplayPart("class", SymbolDisplayPartKind.keyword, undefined));
totalParts.push(new SymbolDisplayPart(" ", SymbolDisplayPartKind.space, undefined));
totalParts.push.apply(totalParts, typeInfoResolver.symbolToDisplayParts(symbol, sourceFile));
}
else if (symbol.flags & SymbolFlags.Interface) {
totalParts.push(new SymbolDisplayPart("interface", SymbolDisplayPartKind.keyword, undefined));
totalParts.push(new SymbolDisplayPart(" ", SymbolDisplayPartKind.space, undefined));
totalParts.push.apply(totalParts, typeInfoResolver.symbolToDisplayParts(symbol, sourceFile));
}
else if (symbol.flags & SymbolFlags.Enum) {
totalParts.push(new SymbolDisplayPart("enum", SymbolDisplayPartKind.keyword, undefined));
totalParts.push(new SymbolDisplayPart(" ", SymbolDisplayPartKind.space, undefined));
totalParts.push.apply(totalParts, typeInfoResolver.symbolToDisplayParts(symbol, sourceFile));
}
else if (symbol.flags & SymbolFlags.Module) {
totalParts.push(new SymbolDisplayPart("module", SymbolDisplayPartKind.keyword, undefined));
totalParts.push(new SymbolDisplayPart(" ", SymbolDisplayPartKind.space, undefined));
totalParts.push.apply(totalParts, typeInfoResolver.symbolToDisplayParts(symbol, sourceFile));
}
else if (symbol.flags & SymbolFlags.TypeParameter) {
totalParts.push(new SymbolDisplayPart("(", SymbolDisplayPartKind.punctuation, undefined));
totalParts.push(new SymbolDisplayPart("type parameter", SymbolDisplayPartKind.text, undefined));
totalParts.push(new SymbolDisplayPart(")", SymbolDisplayPartKind.punctuation, undefined));
totalParts.push(new SymbolDisplayPart(" ", SymbolDisplayPartKind.space, undefined));
totalParts.push.apply(totalParts, typeInfoResolver.symbolToDisplayParts(symbol));
}
else {
totalParts.push(new SymbolDisplayPart("(", SymbolDisplayPartKind.punctuation, undefined));
var text: string;
if (symbol.flags & SymbolFlags.Property) { text = "property" }
else if (symbol.flags & SymbolFlags.EnumMember) { text = "enum member" }
else if (symbol.flags & SymbolFlags.Function) { text = "function" }
else if (symbol.flags & SymbolFlags.Variable) { text = "variable" }
else if (symbol.flags & SymbolFlags.Method) { text = "method" }
if (!text) {
return undefined;
}
totalParts.push(new SymbolDisplayPart(text, SymbolDisplayPartKind.text, undefined));
totalParts.push(new SymbolDisplayPart(")", SymbolDisplayPartKind.punctuation, undefined));
totalParts.push(new SymbolDisplayPart(" ", SymbolDisplayPartKind.space, undefined));
totalParts.push.apply(totalParts, typeInfoResolver.symbolToDisplayParts(symbol, getContainerNode(node)));
var type = typeInfoResolver.getTypeOfSymbol(symbol);
if (symbol.flags & SymbolFlags.Property ||
symbol.flags & SymbolFlags.Variable) {
if (type) {
totalParts.push(new SymbolDisplayPart(":", SymbolDisplayPartKind.punctuation, undefined));
totalParts.push(new SymbolDisplayPart(" ", SymbolDisplayPartKind.space, undefined));
totalParts.push.apply(totalParts, typeInfoResolver.typeToDisplayParts(type, getContainerNode(node)));
}
}
else if (symbol.flags & SymbolFlags.Function ||
symbol.flags & SymbolFlags.Method) {
if (type) {
totalParts.push.apply(totalParts, typeInfoResolver.typeToDisplayParts(type, getContainerNode(node)));
}
}
else if (symbol.flags & SymbolFlags.EnumMember) {
var declaration = symbol.declarations[0];
if (declaration.kind === SyntaxKind.EnumMember) {
var constantValue = typeInfoResolver.getEnumMemberValue(<EnumMember>declaration);
if (constantValue !== undefined) {
totalParts.push(new SymbolDisplayPart(" ", SymbolDisplayPartKind.space, undefined));
totalParts.push(new SymbolDisplayPart("=", SymbolDisplayPartKind.operator, undefined));
totalParts.push(new SymbolDisplayPart(" ", SymbolDisplayPartKind.space, undefined));
totalParts.push(new SymbolDisplayPart(constantValue.toString(), SymbolDisplayPartKind.numericLiteral, undefined));
}
}
}
}
return new QuickInfo(
getSymbolKind(symbol),
getSymbolModifiers(symbol),
new TypeScript.TextSpan(node.getStart(), node.getWidth()),
totalParts,
documentationParts);
}
function getTypeAtPosition(fileName: string, position: number): TypeInfo {
synchronizeHostData();
@ -3750,14 +4030,61 @@ module ts {
}
function getBraceMatchingAtPosition(filename: string, position: number) {
filename = TypeScript.switchToForwardSlashes(filename);
var syntaxTree = getSyntaxTree(filename);
return TypeScript.Services.BraceMatcher.getMatchSpans(syntaxTree, position);
var sourceFile = getCurrentSourceFile(filename);
var result: TypeScript.TextSpan[] = [];
var token = getTokenAtPosition(sourceFile, position);
if (token.getStart(sourceFile) === position) {
var matchKind = getMatchingTokenKind(token);
// Ensure that there is a corresponding token to match ours.
if (matchKind) {
var parentElement = token.parent;
var childNodes = parentElement.getChildren(sourceFile);
for (var i = 0, n = childNodes.length; i < n; i++) {
var current = childNodes[i];
if (current.kind === matchKind) {
var range1 = new TypeScript.TextSpan(token.getStart(sourceFile), token.getWidth(sourceFile));
var range2 = new TypeScript.TextSpan(current.getStart(sourceFile), current.getWidth(sourceFile));
// We want to order the braces when we return the result.
if (range1.start() < range2.start()) {
result.push(range1, range2);
}
else {
result.push(range2, range1);
}
break;
}
}
}
}
return result;
function getMatchingTokenKind(token: Node): ts.SyntaxKind {
switch (token.kind) {
case ts.SyntaxKind.OpenBraceToken: return ts.SyntaxKind.CloseBraceToken
case ts.SyntaxKind.OpenParenToken: return ts.SyntaxKind.CloseParenToken;
case ts.SyntaxKind.OpenBracketToken: return ts.SyntaxKind.CloseBracketToken;
case ts.SyntaxKind.LessThanToken: return ts.SyntaxKind.GreaterThanToken;
case ts.SyntaxKind.CloseBraceToken: return ts.SyntaxKind.OpenBraceToken
case ts.SyntaxKind.CloseParenToken: return ts.SyntaxKind.OpenParenToken;
case ts.SyntaxKind.CloseBracketToken: return ts.SyntaxKind.OpenBracketToken;
case ts.SyntaxKind.GreaterThanToken: return ts.SyntaxKind.LessThanToken;
}
return undefined;
}
}
function getIndentationAtPosition(filename: string, position: number, editorOptions: EditorOptions) {
filename = TypeScript.switchToForwardSlashes(filename);
var sourceFile = getCurrentSourceFile(filename);
var options = new TypeScript.FormattingOptions(!editorOptions.ConvertTabsToSpaces, editorOptions.TabSize, editorOptions.IndentSize, editorOptions.NewLineCharacter)
@ -3871,8 +4198,8 @@ module ts {
}
// Looks to be within the trivia. See if we can find the comment containing it.
if (!getContainingComment(getTrailingComments(fileContents, token.getFullStart()), matchPosition) &&
!getContainingComment(getLeadingComments(fileContents, token.getFullStart()), matchPosition)) {
if (!getContainingComment(getTrailingCommentRanges(fileContents, token.getFullStart()), matchPosition) &&
!getContainingComment(getLeadingCommentRanges(fileContents, token.getFullStart()), matchPosition)) {
continue;
}
@ -3959,7 +4286,7 @@ module ts {
return new RegExp(regExpString, "gim");
}
function getContainingComment(comments: Comment[], position: number): Comment {
function getContainingComment(comments: CommentRange[], position: number): CommentRange {
if (comments) {
for (var i = 0, n = comments.length; i < n; i++) {
var comment = comments[i];
@ -3997,7 +4324,7 @@ module ts {
var kind = getSymbolKind(symbol);
if (kind) {
return RenameInfo.Create(symbol.name, typeInfoResolver.getFullyQualifiedName(symbol), kind,
getNodeModifiers(symbol.getDeclarations()[0]),
getSymbolModifiers(symbol),
new TypeScript.TextSpan(node.getStart(), node.getWidth()));
}
}
@ -4019,6 +4346,7 @@ module ts {
getTypeAtPosition: getTypeAtPosition,
getSignatureHelpItems: getSignatureHelpItems,
getSignatureHelpCurrentArgumentState: getSignatureHelpCurrentArgumentState,
getQuickInfoAtPosition: getQuickInfoAtPosition,
getDefinitionAtPosition: getDefinitionAtPosition,
getReferencesAtPosition: getReferencesAtPosition,
getOccurrencesAtPosition: getOccurrencesAtPosition,
@ -4041,13 +4369,13 @@ module ts {
/// Classifier
export function createClassifier(host: Logger): Classifier {
var scanner: Scanner;
var noRegexTable: boolean[];
var scanner = createScanner(ScriptTarget.ES5, /*skipTrivia*/ false);
/// We do not have a full parser support to know when we should parse a regex or not
/// If we consider every slash token to be a regex, we could be missing cases like "1/2/3", where
/// we have a series of divide operator. this list allows us to be more accurate by ruling out
/// locations where a regexp cannot exist.
var noRegexTable: boolean[];
if (!noRegexTable) {
noRegexTable = [];
noRegexTable[SyntaxKind.Identifier] = true;
@ -4067,8 +4395,7 @@ module ts {
function getClassificationsForLine(text: string, lexState: EndOfLineState): ClassificationResult {
var offset = 0;
var lastTokenOrCommentEnd = 0;
var lastToken = SyntaxKind.Unknown;
var inUnterminatedMultiLineComment = false;
var lastNonTriviaToken = SyntaxKind.Unknown;
// If we're in a string literal, then prepend: "\
// (and a newline). That way when we lex we'll think we're still in a string literal.
@ -4090,27 +4417,31 @@ module ts {
break;
}
scanner.setText(text);
var result: ClassificationResult = {
finalLexState: EndOfLineState.Start,
entries: []
};
scanner = createScanner(ScriptTarget.ES5, /*skipTrivia*/ true, text, onError, processComment);
var token = SyntaxKind.Unknown;
do {
token = scanner.scan();
if ((token === SyntaxKind.SlashToken || token === SyntaxKind.SlashEqualsToken) && !noRegexTable[lastToken]) {
if ((token === SyntaxKind.SlashToken || token === SyntaxKind.SlashEqualsToken) && !noRegexTable[lastNonTriviaToken]) {
if (scanner.reScanSlashToken() === SyntaxKind.RegularExpressionLiteral) {
token = SyntaxKind.RegularExpressionLiteral;
}
}
else if (lastToken === SyntaxKind.DotToken) {
else if (lastNonTriviaToken === SyntaxKind.DotToken) {
token = SyntaxKind.Identifier;
}
lastToken = token;
// Only recall the token if it was *not* trivia.
if (!(SyntaxKind.FirstTriviaToken <= token && token <= SyntaxKind.LastTriviaToken)) {
lastNonTriviaToken = token;
}
processToken();
}
@ -4118,35 +4449,17 @@ module ts {
return result;
function onError(message: DiagnosticMessage): void {
inUnterminatedMultiLineComment = message.key === Diagnostics.Asterisk_Slash_expected.key;
}
function processComment(start: number, end: number) {
// add Leading white spaces
addLeadingWhiteSpace(start, end);
// add the comment
addResult(end - start, TokenClass.Comment);
}
function processToken(): void {
var start = scanner.getTokenPos();
var end = scanner.getTextPos();
// add Leading white spaces
addLeadingWhiteSpace(start, end);
// add the token
addResult(end - start, classFromKind(token));
if (end >= text.length) {
// We're at the end.
if (inUnterminatedMultiLineComment) {
result.finalLexState = EndOfLineState.InMultiLineCommentTrivia;
}
else if (token === SyntaxKind.StringLiteral) {
if (token === SyntaxKind.StringLiteral) {
// Check to see if we finished up on a multiline string literal.
var tokenText = scanner.getTokenText();
if (tokenText.length > 0 && tokenText.charCodeAt(tokenText.length - 1) === CharacterCodes.backslash) {
var quoteChar = tokenText.charCodeAt(0);
@ -4155,18 +4468,18 @@ module ts {
: EndOfLineState.InSingleQuoteStringLiteral;
}
}
else if (token === SyntaxKind.MultiLineCommentTrivia) {
// Check to see if the multiline comment was unclosed.
var tokenText = scanner.getTokenText()
if (!(tokenText.length > 3 && // need to avoid catching '/*/'
tokenText.charCodeAt(tokenText.length - 2) === CharacterCodes.asterisk &&
tokenText.charCodeAt(tokenText.length - 1) === CharacterCodes.slash)) {
result.finalLexState = EndOfLineState.InMultiLineCommentTrivia;
}
}
}
}
function addLeadingWhiteSpace(start: number, end: number): void {
if (start > lastTokenOrCommentEnd) {
addResult(start - lastTokenOrCommentEnd, TokenClass.Whitespace);
}
// Remember the end of the last token
lastTokenOrCommentEnd = end;
}
function addResult(length: number, classification: TokenClass): void {
if (length > 0) {
// If this is the first classification we're adding to the list, then remove any
@ -4259,6 +4572,11 @@ module ts {
return TokenClass.StringLiteral;
case SyntaxKind.RegularExpressionLiteral:
return TokenClass.RegExpLiteral;
case SyntaxKind.MultiLineCommentTrivia:
case SyntaxKind.SingleLineCommentTrivia:
return TokenClass.Comment;
case SyntaxKind.WhitespaceTrivia:
return TokenClass.Whitespace;
case SyntaxKind.Identifier:
default:
return TokenClass.Identifier;

View file

@ -87,7 +87,9 @@ module ts {
getCompletionsAtPosition(fileName: string, position: number, isMemberCompletion: boolean): string;
getCompletionEntryDetails(fileName: string, position: number, entryName: string): string;
getQuickInfoAtPosition(fileName: string, position: number): string;
getTypeAtPosition(fileName: string, position: number): string;
getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): string;
getBreakpointStatementAtPosition(fileName: string, position: number): string;
@ -540,6 +542,16 @@ module ts {
/// QUICKINFO
/// Computes a string representation of the type at the requested position
/// in the active file.
public getQuickInfoAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getQuickInfoAtPosition('" + fileName + "', " + position + ")",
() => {
var quickInfo = this.languageService.getQuickInfoAtPosition(fileName, position);
return quickInfo;
});
}
public getTypeAtPosition(fileName: string, position: number): string {
return this.forwardJSONCall(
"getTypeAtPosition('" + fileName + "', " + position + ")",

View file

@ -0,0 +1,99 @@
tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts(22,12): error TS1029: 'private' modifier must precede 'static' modifier.
tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts(23,12): error TS1029: 'private' modifier must precede 'static' modifier.
tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts(24,12): error TS1029: 'private' modifier must precede 'static' modifier.
tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts(25,12): error TS1029: 'private' modifier must precede 'static' modifier.
tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts(27,12): error TS1029: 'protected' modifier must precede 'static' modifier.
tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts(28,12): error TS1029: 'protected' modifier must precede 'static' modifier.
tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts(29,12): error TS1029: 'protected' modifier must precede 'static' modifier.
tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts(30,12): error TS1029: 'protected' modifier must precede 'static' modifier.
tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts(32,12): error TS1029: 'public' modifier must precede 'static' modifier.
tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts(33,12): error TS1029: 'public' modifier must precede 'static' modifier.
tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts(34,12): error TS1029: 'public' modifier must precede 'static' modifier.
tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts(35,12): error TS1029: 'public' modifier must precede 'static' modifier.
tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts(40,13): error TS1028: Accessibility modifier already seen.
tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts(40,20): error TS1028: Accessibility modifier already seen.
tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts(41,12): error TS1028: Accessibility modifier already seen.
tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts(42,13): error TS1028: Accessibility modifier already seen.
tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts(43,12): error TS1028: Accessibility modifier already seen.
==== tests/cases/conformance/classes/propertyMemberDeclarations/accessibilityModifiers.ts (17 errors) ====
// 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;
~~~~~~~
!!! error TS1029: 'private' modifier must precede 'static' modifier.
static private privateMethod() { }
~~~~~~~
!!! error TS1029: 'private' modifier must precede 'static' modifier.
static private get privateGetter() { return 0; }
~~~~~~~
!!! error TS1029: 'private' modifier must precede 'static' modifier.
static private set privateSetter(a: number) { }
~~~~~~~
!!! error TS1029: 'private' modifier must precede 'static' modifier.
static protected protectedProperty;
~~~~~~~~~
!!! error TS1029: 'protected' modifier must precede 'static' modifier.
static protected protectedMethod() { }
~~~~~~~~~
!!! error TS1029: 'protected' modifier must precede 'static' modifier.
static protected get protectedGetter() { return 0; }
~~~~~~~~~
!!! error TS1029: 'protected' modifier must precede 'static' modifier.
static protected set protectedSetter(a: number) { }
~~~~~~~~~
!!! error TS1029: 'protected' modifier must precede 'static' modifier.
static public publicProperty;
~~~~~~
!!! error TS1029: 'public' modifier must precede 'static' modifier.
static public publicMethod() { }
~~~~~~
!!! error TS1029: 'public' modifier must precede 'static' modifier.
static public get publicGetter() { return 0; }
~~~~~~
!!! error TS1029: 'public' modifier must precede 'static' modifier.
static public set publicSetter(a: number) { }
~~~~~~
!!! error TS1029: 'public' modifier must precede 'static' modifier.
}
// Errors, multiple accessibility modifier
class E {
private public protected property;
~~~~~~
!!! error TS1028: Accessibility modifier already seen.
~~~~~~~~~
!!! error TS1028: Accessibility modifier already seen.
public protected method() { }
~~~~~~~~~
!!! error TS1028: Accessibility modifier already seen.
private protected get getter() { return 0; }
~~~~~~~~~
!!! error TS1028: Accessibility modifier already seen.
public public set setter(a: number) { }
~~~~~~
!!! error TS1028: Accessibility modifier already seen.
}

View file

@ -0,0 +1,59 @@
tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts(3,9): error TS2379: Getter and setter accessors do not agree in visibility.
tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts(6,17): error TS2379: Getter and setter accessors do not agree in visibility.
tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts(11,19): error TS2379: Getter and setter accessors do not agree in visibility.
tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts(14,17): error TS2379: Getter and setter accessors do not agree in visibility.
tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts(19,19): error TS2379: Getter and setter accessors do not agree in visibility.
tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts(21,9): error TS2379: Getter and setter accessors do not agree in visibility.
tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts(27,26): error TS2379: Getter and setter accessors do not agree in visibility.
tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts(29,16): error TS2379: Getter and setter accessors do not agree in visibility.
==== tests/cases/conformance/classes/propertyMemberDeclarations/memberAccessorDeclarations/accessorWithMismatchedAccessibilityModifiers.ts (8 errors) ====
class C {
get x() {
~
!!! error TS2379: Getter and setter accessors do not agree in visibility.
return 1;
}
private set x(v) {
~
!!! error TS2379: Getter and setter accessors do not agree in visibility.
}
}
class D {
protected get x() {
~
!!! error TS2379: Getter and setter accessors do not agree in visibility.
return 1;
}
private set x(v) {
~
!!! error TS2379: Getter and setter accessors do not agree in visibility.
}
}
class E {
protected set x(v) {
~
!!! error TS2379: Getter and setter accessors do not agree in visibility.
}
get x() {
~
!!! error TS2379: Getter and setter accessors do not agree in visibility.
return 1;
}
}
class F {
protected static set x(v) {
~
!!! error TS2379: Getter and setter accessors do not agree in visibility.
}
static get x() {
~
!!! error TS2379: Getter and setter accessors do not agree in visibility.
return 1;
}
}

View file

@ -0,0 +1,91 @@
//// [accessorWithMismatchedAccessibilityModifiers.ts]
class C {
get x() {
return 1;
}
private set x(v) {
}
}
class D {
protected get x() {
return 1;
}
private set x(v) {
}
}
class E {
protected set x(v) {
}
get x() {
return 1;
}
}
class F {
protected static set x(v) {
}
static get x() {
return 1;
}
}
//// [accessorWithMismatchedAccessibilityModifiers.js]
var C = (function () {
function C() {
}
Object.defineProperty(C.prototype, "x", {
get: function () {
return 1;
},
set: function (v) {
},
enumerable: true,
configurable: true
});
return C;
})();
var D = (function () {
function D() {
}
Object.defineProperty(D.prototype, "x", {
get: function () {
return 1;
},
set: function (v) {
},
enumerable: true,
configurable: true
});
return D;
})();
var E = (function () {
function E() {
}
Object.defineProperty(E.prototype, "x", {
get: function () {
return 1;
},
set: function (v) {
},
enumerable: true,
configurable: true
});
return E;
})();
var F = (function () {
function F() {
}
Object.defineProperty(F, "x", {
get: function () {
return 1;
},
set: function (v) {
},
enumerable: true,
configurable: true
});
return F;
})();

View file

@ -0,0 +1,35 @@
tests/cases/conformance/classes/constructorDeclarations/classConstructorParametersAccessibility.ts(12,1): error TS2341: Property 'p' is private and only accessible within class 'C2'.
tests/cases/conformance/classes/constructorDeclarations/classConstructorParametersAccessibility.ts(19,1): error TS2445: Property 'p' is protected and only accessible within class 'C3' and its subclasses.
==== tests/cases/conformance/classes/constructorDeclarations/classConstructorParametersAccessibility.ts (2 errors) ====
class C1 {
constructor(public x: number) { }
}
var c1: C1;
c1.x // OK
class C2 {
constructor(private p: number) { }
}
var c2: C2;
c2.p // private, error
~~~~
!!! error TS2341: Property 'p' is private and only accessible within class 'C2'.
class C3 {
constructor(protected p: number) { }
}
var c3: C3;
c3.p // protected, error
~~~~
!!! error TS2445: Property 'p' is protected and only accessible within class 'C3' and its subclasses.
class Derived extends C3 {
constructor(p: number) {
super(p);
this.p; // OK
}
}

View file

@ -0,0 +1,67 @@
//// [classConstructorParametersAccessibility.ts]
class C1 {
constructor(public x: number) { }
}
var c1: C1;
c1.x // OK
class C2 {
constructor(private p: number) { }
}
var c2: C2;
c2.p // private, error
class C3 {
constructor(protected p: number) { }
}
var c3: C3;
c3.p // protected, error
class Derived extends C3 {
constructor(p: number) {
super(p);
this.p; // OK
}
}
//// [classConstructorParametersAccessibility.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(x) {
this.x = x;
}
return C1;
})();
var c1;
c1.x; // OK
var C2 = (function () {
function C2(p) {
this.p = p;
}
return C2;
})();
var c2;
c2.p; // private, error
var C3 = (function () {
function C3(p) {
this.p = p;
}
return C3;
})();
var c3;
c3.p; // protected, error
var Derived = (function (_super) {
__extends(Derived, _super);
function Derived(p) {
_super.call(this, p);
this.p; // OK
}
return Derived;
})(C3);

View file

@ -0,0 +1,35 @@
tests/cases/conformance/classes/constructorDeclarations/classConstructorParametersAccessibility2.ts(12,1): error TS2341: Property 'p' is private and only accessible within class 'C2'.
tests/cases/conformance/classes/constructorDeclarations/classConstructorParametersAccessibility2.ts(19,1): error TS2445: Property 'p' is protected and only accessible within class 'C3' and its subclasses.
==== tests/cases/conformance/classes/constructorDeclarations/classConstructorParametersAccessibility2.ts (2 errors) ====
class C1 {
constructor(public x?: number) { }
}
var c1: C1;
c1.x // OK
class C2 {
constructor(private p?: number) { }
}
var c2: C2;
c2.p // private, error
~~~~
!!! error TS2341: Property 'p' is private and only accessible within class 'C2'.
class C3 {
constructor(protected p?: number) { }
}
var c3: C3;
c3.p // protected, error
~~~~
!!! error TS2445: Property 'p' is protected and only accessible within class 'C3' and its subclasses.
class Derived extends C3 {
constructor(p: number) {
super(p);
this.p; // OK
}
}

View file

@ -0,0 +1,67 @@
//// [classConstructorParametersAccessibility2.ts]
class C1 {
constructor(public x?: number) { }
}
var c1: C1;
c1.x // OK
class C2 {
constructor(private p?: number) { }
}
var c2: C2;
c2.p // private, error
class C3 {
constructor(protected p?: number) { }
}
var c3: C3;
c3.p // protected, error
class Derived extends C3 {
constructor(p: number) {
super(p);
this.p; // OK
}
}
//// [classConstructorParametersAccessibility2.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(x) {
this.x = x;
}
return C1;
})();
var c1;
c1.x; // OK
var C2 = (function () {
function C2(p) {
this.p = p;
}
return C2;
})();
var c2;
c2.p; // private, error
var C3 = (function () {
function C3(p) {
this.p = p;
}
return C3;
})();
var c3;
c3.p; // protected, error
var Derived = (function (_super) {
__extends(Derived, _super);
function Derived(p) {
_super.call(this, p);
this.p; // OK
}
return Derived;
})(C3);

View file

@ -0,0 +1,39 @@
//// [classConstructorParametersAccessibility3.ts]
class Base {
constructor(protected p: number) { }
}
class Derived extends Base {
constructor(public p: number) {
super(p);
this.p; // OK
}
}
var d: Derived;
d.p; // public, OK
//// [classConstructorParametersAccessibility3.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(p) {
this.p = p;
}
return Base;
})();
var Derived = (function (_super) {
__extends(Derived, _super);
function Derived(p) {
_super.call(this, p);
this.p = p;
this.p; // OK
}
return Derived;
})(Base);
var d;
d.p; // public, OK

View file

@ -0,0 +1,36 @@
=== tests/cases/conformance/classes/constructorDeclarations/classConstructorParametersAccessibility3.ts ===
class Base {
>Base : Base
constructor(protected p: number) { }
>p : number
}
class Derived extends Base {
>Derived : Derived
>Base : Base
constructor(public p: number) {
>p : number
super(p);
>super(p) : void
>super : typeof Base
>p : number
this.p; // OK
>this.p : number
>this : Derived
>p : number
}
}
var d: Derived;
>d : Derived
>Derived : Derived
d.p; // public, OK
>d.p : number
>d : Derived
>p : number

View file

@ -0,0 +1,71 @@
//// [classWithProtectedProperty.ts]
// accessing any protected outside the class is an error
class C {
protected x;
protected a = '';
protected b: string = '';
protected c() { return '' }
protected d = () => '';
protected static e;
protected static f() { return '' }
protected static g = () => '';
}
class D extends C {
method() {
// No errors
var d = new D();
var r1: string = d.x;
var r2: string = d.a;
var r3: string = d.b;
var r4: string = d.c();
var r5: string = d.d();
var r6: string = C.e;
var r7: string = C.f();
var r8: string = C.g();
}
}
//// [classWithProtectedProperty.js]
// accessing any protected outside the class is 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 C = (function () {
function C() {
this.a = '';
this.b = '';
this.d = function () { return ''; };
}
C.prototype.c = function () {
return '';
};
C.f = function () {
return '';
};
C.g = function () { return ''; };
return C;
})();
var D = (function (_super) {
__extends(D, _super);
function D() {
_super.apply(this, arguments);
}
D.prototype.method = function () {
// No errors
var d = new D();
var r1 = d.x;
var r2 = d.a;
var r3 = d.b;
var r4 = d.c();
var r5 = d.d();
var r6 = C.e;
var r7 = C.f();
var r8 = C.g();
};
return D;
})(C);

View file

@ -0,0 +1,99 @@
=== tests/cases/conformance/types/members/classWithProtectedProperty.ts ===
// accessing any protected outside the class is an error
class C {
>C : C
protected x;
>x : any
protected a = '';
>a : string
protected b: string = '';
>b : string
protected c() { return '' }
>c : () => string
protected d = () => '';
>d : () => string
>() => '' : () => string
protected static e;
>e : any
protected static f() { return '' }
>f : () => string
protected static g = () => '';
>g : () => string
>() => '' : () => string
}
class D extends C {
>D : D
>C : C
method() {
>method : () => void
// No errors
var d = new D();
>d : D
>new D() : D
>D : typeof D
var r1: string = d.x;
>r1 : string
>d.x : any
>d : D
>x : any
var r2: string = d.a;
>r2 : string
>d.a : string
>d : D
>a : string
var r3: string = d.b;
>r3 : string
>d.b : string
>d : D
>b : string
var r4: string = d.c();
>r4 : string
>d.c() : string
>d.c : () => string
>d : D
>c : () => string
var r5: string = d.d();
>r5 : string
>d.d() : string
>d.d : () => string
>d : D
>d : () => string
var r6: string = C.e;
>r6 : string
>C.e : any
>C : typeof C
>e : any
var r7: string = C.f();
>r7 : string
>C.f() : string
>C.f : () => string
>C : typeof C
>f : () => string
var r8: string = C.g();
>r8 : string
>C.g() : string
>C.g : () => string
>C : typeof C
>g : () => string
}
}

View file

@ -0,0 +1,579 @@
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,19): error TS1005: ';' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(22,35): error TS1005: ')' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(24,28): error TS1005: ':' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(24,29): error TS1005: ',' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(27,18): error TS1129: Statement expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(28,30): error TS1005: ',' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(28,33): error TS1138: Parameter declaration expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(28,34): error TS1005: ';' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(28,36): error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(30,21): error TS1108: A 'return' statement can only be used within a function body.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(31,18): error TS1129: Statement expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(38,17): error TS1109: Expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(40,41): error TS1005: ';' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(40,45): error TS1002: Unterminated string literal.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(43,21): error TS1108: A 'return' statement can only be used within a function body.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(46,13): error TS1005: 'try' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(55,13): error TS1108: A 'return' statement can only be used within a function body.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(58,5): error TS1128: Declaration or statement expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(69,13): error TS1109: Expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(72,37): error TS1127: Invalid character.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(81,13): error TS1109: Expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(90,13): error TS1109: Expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(105,29): error TS1109: Expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(106,13): error TS1109: Expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(138,13): error TS1109: Expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(141,32): error TS1005: '{' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(143,13): error TS1005: 'try' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(159,24): error TS1109: Expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(159,30): error TS1005: '(' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(205,28): error TS1109: Expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(218,10): error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(218,36): error TS1005: ';' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(219,20): error TS1056: Accessors are only available when targeting ECMAScript 5 and higher.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(227,13): error TS1109: Expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(234,14): error TS1005: '{' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,9): error TS1128: Declaration or statement expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,27): error TS1005: ',' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,36): error TS1005: ';' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(236,13): error TS1108: A 'return' statement can only be used within a function body.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(238,9): error TS1128: Declaration or statement expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(238,26): error TS1005: ';' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(239,13): error TS1108: A 'return' statement can only be used within a function body.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(241,5): error TS1128: Declaration or statement expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,67): error TS1093: Type annotation cannot appear on a constructor declaration.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,69): error TS1110: Type expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,9): error TS1128: Declaration or statement expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,31): error TS1005: ',' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,9): error TS1128: Declaration or statement expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,27): error TS1135: Argument expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,33): error TS1005: '(' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,43): error TS1109: Expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,59): error TS1109: Expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,60): error TS1005: ';' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,65): error TS1129: Statement expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,9): error TS1129: Statement expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,35): error TS1109: Expression expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,55): error TS1005: ';' expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS1128: Declaration or statement expected.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,1): error TS2304: Cannot find name 'module'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(22,39): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(27,26): error TS2304: Cannot find name 'bfs'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(28,17): error TS2391: Function implementation is missing or not immediately following the declaration.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(34,17): error TS2304: Cannot find name 'retValue'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(34,28): error TS2304: Cannot find name 'bfs'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(35,21): error TS2304: Cannot find name 'retValue'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(40,17): error TS2304: Cannot find name 'retValue'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(40,28): error TS2304: Cannot find name 'bfs'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(41,21): error TS2304: Cannot find name 'retValue'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(47,17): error TS2304: Cannot find name 'console'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(53,13): error TS2304: Cannot find name 'console'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(76,26): error TS2358: The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(76,44): error TS2359: The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(89,23): error TS2364: Invalid left-hand side of assignment expression.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(108,24): error TS2365: Operator '+' cannot be applied to types 'number' and 'boolean'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(159,31): error TS2304: Cannot find name 'Property'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(166,13): error TS2365: Operator '+=' cannot be applied to types 'number' and 'void'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(180,40): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(180,47): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(213,16): error TS2304: Cannot find name 'bool'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(218,29): error TS2304: Cannot find name 'yield'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(223,23): error TS2304: Cannot find name 'bool'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,16): error TS2304: Cannot find name 'method1'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,24): error TS2304: Cannot find name 'val'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(235,28): error TS2304: Cannot find name 'number'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(238,16): error TS2304: Cannot find name 'method2'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(246,25): error TS2339: Property 'method1' does not exist on type 'B'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,9): error TS2390: Constructor implementation is missing.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,21): error TS2369: A parameter property is only allowed in a constructor implementation.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(254,44): error TS2369: A parameter property is only allowed in a constructor implementation.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,16): error TS2304: Cannot find name 'Overloads'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,26): error TS2304: Cannot find name 'value'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(256,33): error TS2304: Cannot find name 'string'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,16): error TS2304: Cannot find name 'Overloads'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,35): error TS2304: Cannot find name 'string'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(257,52): error TS2304: Cannot find name 'string'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,16): error TS2304: Cannot find name 'DefaultValue'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,29): error TS2304: Cannot find name 'value'.
tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,37): error TS2304: Cannot find name 'string'.
==== tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts (98 errors) ====
declare module "fs" {
export class File {
constructor(filename: string);
public ReadAllText(): string;
}
export interface IFile {
[index: number]: string;
}
}
import fs = module("fs");
~
!!! error TS1005: ';' expected.
~~~~~~~~~~~~~~~~~~
!!! error TS2304: Cannot find name 'module'.
module TypeScriptAllInOne {
export class Program {
static Main(...args: string[]) {
try {
var bfs = new BasicFeatures();
var retValue: number = 0;
retValue = bfs.VARIABLES();
if (retValue != 0 ^= {
~~
!!! error TS1005: ')' expected.
~
return 1;
~
!!! error TS1005: ':' expected.
~
!!! error TS1005: ',' expected.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
~~~~~~~~~~~~~~~~~
!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
case = bfs.STATEMENTS(4);
~~~~
!!! error TS1129: Statement expected.
~~~
!!! error TS2304: Cannot find name 'bfs'.
if (retValue != 0) {
~~
!!! error TS1005: ',' expected.
~
!!! error TS1138: Parameter declaration expected.
~
!!! error TS1005: ';' expected.
~
!!! error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
~~
!!! error TS2391: Function implementation is missing or not immediately following the declaration.
return 1;
~~~~~~
!!! error TS1108: A 'return' statement can only be used within a function body.
^
~
!!! error TS1129: Statement expected.
retValue = bfs.TYPES();
~~~~~~~~
!!! error TS2304: Cannot find name 'retValue'.
~~~
!!! error TS2304: Cannot find name 'bfs'.
if (retValue != 0) {
~~~~~~~~
!!! error TS2304: Cannot find name 'retValue'.
return 1 &&
}
~
!!! error TS1109: Expression expected.
retValue = bfs.OPERATOR ' );
~~~~
!!! error TS1005: ';' expected.
!!! error TS1002: Unterminated string literal.
~~~~~~~~
!!! error TS2304: Cannot find name 'retValue'.
~~~
!!! error TS2304: Cannot find name 'bfs'.
if (retValue != 0) {
~~~~~~~~
!!! error TS2304: Cannot find name 'retValue'.
return 1;
~~~~~~
!!! error TS1108: A 'return' statement can only be used within a function body.
}
}
catch (e) {
~~~~~
!!! error TS1005: 'try' expected.
console.log(e);
~~~~~~~
!!! error TS2304: Cannot find name 'console'.
}
finally {
}
console.log('Done');
~~~~~~~
!!! error TS2304: Cannot find name 'console'.
return 0;
~~~~~~
!!! error TS1108: A 'return' statement can only be used within a function body.
}
}
~
!!! error TS1128: Declaration or statement expected.
class BasicFeatures {
/// <summary>
/// Test various of variables. Including nullable,key world as variable,special format
/// </summary>
/// <returns></returns>
public VARIABLES(): number {
var local = Number.MAX_VALUE;
var min = Number.MIN_VALUE;
var inf = Number.NEGATIVE_INFINITY -
var nan = Number.NaN;
~~~
!!! error TS1109: Expression expected.
var undef = undefined;
var _\uD4A5\u7204\uC316\uE59F = local;
!!! error TS1127: Invalid character.
var мир = local;
var local5 = <fs.File>null;
var local6 = local5 instanceof fs.File;
~~~~~~
!!! error TS2358: The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter.
~~~~~~~
!!! error TS2359: The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.
var hex = 0xBADC0DE, Hex = 0XDEADBEEF;
var float = 6.02e23, float2 = 6.02E-23
var char = 'c', \u0066 = '\u0066', hexchar = '\x42' !=
var quoted = '"', quoted2 = "'";
~~~
!!! error TS1109: Expression expected.
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 ^=
~
!!! error TS2364: Invalid left-hand side of assignment expression.
var bool = 0;
~~~
!!! error TS1109: Expression expected.
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 />
~
!!! error TS1109: Expression expected.
var yield = 0;
~~~
!!! error TS1109: Expression expected.
var sum3 = any + bool + declare + constructor + get + implements + interface + let + module + number + package + private + protected + public + set + static + string + yield;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2365: Operator '+' cannot be applied to types 'number' and 'boolean'.
return 0;
}
/// <summary>
/// Test different statements. Including if-else,swith,foreach,(un)checked,lock,using,try-catch-finally
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
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 {
~~~
!!! error TS1109: Expression expected.
throw null;
}
catch (Exception) ?
~
!!! error TS1005: '{' expected.
}
finally {
~~~~~~~
!!! error TS1005: 'try' expected.
try { }
catch (Exception) { }
}
return retVal;
}
/// <summary>
/// Test types in ts language. Including class,struct,interface,delegate,anonymous type
/// </summary>
/// <returns></returns>
public TYPES(): number {
var retVal = 0;
var c = new CLASS();
var xx: IF = c;
retVal += catch .Property;
~~~~~
!!! error TS1109: Expression expected.
~
!!! error TS1005: '(' expected.
~~~~~~~~
!!! error TS2304: Cannot find name 'Property'.
retVal += c.Member();
retVal += xx.Foo() ? 0 : 1;
//anonymous type
var anony = { a: new CLASS() };
retVal += anony.a.d();
~~~~~~~~~~~~~~~~~~~~~
!!! error TS2365: Operator '+=' cannot be applied to types 'number' and 'void'.
return retVal;
}
///// <summary>
///// Test different operators
///// </summary>
///// <returns></returns>
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;/*& | ^*/
~~~~
!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
~~~~~
!!! error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.
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 += <number>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)
~~
!!! error TS1109: Expression expected.
return 0;
else return 1;
}
}
interface IF {
Foo(): bool;
~~~~
!!! error TS2304: Cannot find name 'bool'.
}
class CLASS implements IF {
case d = () => { yield 0; };
~~~~
!!! error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
~
!!! error TS1005: ';' expected.
~~~~~
!!! error TS2304: Cannot find name 'yield'.
public get Property() { return 0; }
~~~~~~~~
!!! error TS1056: Accessors are only available when targeting ECMAScript 5 and higher.
public Member() {
return 0;
}
public Foo(): bool {
~~~~
!!! error TS2304: Cannot find name 'bool'.
var myEvent = () => { return 1; };
if (myEvent() == 1)
return true ?
else
~~~~
!!! error TS1109: Expression expected.
return false;
}
}
// todo: use these
class A .
~
!!! error TS1005: '{' expected.
public method1(val:number) {
~~~~~~
!!! error TS1128: Declaration or statement expected.
~
!!! error TS1005: ',' expected.
~
!!! error TS1005: ';' expected.
~~~~~~~
!!! error TS2304: Cannot find name 'method1'.
~~~
!!! error TS2304: Cannot find name 'val'.
~~~~~~
!!! error TS2304: Cannot find name 'number'.
return val;
~~~~~~
!!! error TS1108: A 'return' statement can only be used within a function body.
}
public method2() {
~~~~~~
!!! error TS1128: Declaration or statement expected.
~
!!! error TS1005: ';' expected.
~~~~~~~
!!! error TS2304: Cannot find name 'method2'.
return 2 * this.method1(2);
~~~~~~
!!! error TS1108: A 'return' statement can only be used within a function body.
}
}
~
!!! error TS1128: Declaration or statement expected.
class B extends A {
public method2() {
return this.method1(2);
~~~~~~~
!!! error TS2339: Property 'method1' does not exist on type 'B'.
}
}
class Overloading {
private otherValue = 42;
constructor(private value: number, public name: string) : }
!!! error TS1093: Type annotation cannot appear on a constructor declaration.
~
!!! error TS1110: Type expected.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2390: Constructor implementation is missing.
~~~~~~~~~~~~~~~~~~~~~
!!! error TS2369: A parameter property is only allowed in a constructor implementation.
~~~~~~~~~~~~~~~~~~~
!!! error TS2369: A parameter property is only allowed in a constructor implementation.
public Overloads(value: string);
~~~~~~
!!! error TS1128: Declaration or statement expected.
~
!!! error TS1005: ',' expected.
~~~~~~~~~
!!! error TS2304: Cannot find name 'Overloads'.
~~~~~
!!! error TS2304: Cannot find name 'value'.
~~~~~~
!!! error TS2304: Cannot find name 'string'.
public Overloads( while : string, ...rest: string[]) { &
~~~~~~
!!! error TS1128: Declaration or statement expected.
~~~~~
!!! error TS1135: Argument expression expected.
~
!!! error TS1005: '(' expected.
~~~
!!! error TS1109: Expression expected.
~
!!! error TS1109: Expression expected.
~
!!! error TS1005: ';' expected.
~
!!! error TS1129: Statement expected.
~~~~~~~~~
!!! error TS2304: Cannot find name 'Overloads'.
~~~~~~
!!! error TS2304: Cannot find name 'string'.
~~~~~~
!!! error TS2304: Cannot find name 'string'.
public DefaultValue(value?: string = "Hello") { }
~~~~~~
!!! error TS1129: Statement expected.
~
!!! error TS1109: Expression expected.
~
!!! error TS1005: ';' expected.
~~~~~~~~~~~~
!!! error TS2304: Cannot find name 'DefaultValue'.
~~~~~
!!! error TS2304: Cannot find name 'value'.
~~~~~~
!!! error TS2304: Cannot find name 'string'.
}
}
~
!!! error TS1128: Declaration or statement expected.
enum Weekdays {
Monday,
Tuesday,
Weekend,
}
enum Fruit {
Apple,
Pear
}
interface IDisposable {
Dispose(): void;
}
TypeScriptAllInOne.Program.Main();

View file

@ -0,0 +1,164 @@
//// [declarationEmit_protectedMembers.ts]
// Class with protected members
class C1 {
protected x: number;
protected f() {
return this.x;
}
protected set accessor(a: number) { }
protected get accessor() { return 0; }
protected static sx: number;
protected static sf() {
return this.sx;
}
protected static set staticSetter(a: number) { }
protected static get staticGetter() { return 0; }
}
// Derived class overriding protected members
class C2 extends C1 {
protected f() {
return super.f() + this.x;
}
protected static sf() {
return super.sf() + this.sx;
}
}
// Derived class making protected members public
class C3 extends C2 {
x: number;
static sx: number;
f() {
return super.f();
}
static sf() {
return super.sf();
}
static get staticGetter() { return 1; }
}
// Protected properties in constructors
class C4 {
constructor(protected a: number, protected b) { }
}
//// [declarationEmit_protectedMembers.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 __();
};
// Class with protected members
var C1 = (function () {
function C1() {
}
C1.prototype.f = function () {
return this.x;
};
Object.defineProperty(C1.prototype, "accessor", {
get: function () {
return 0;
},
set: function (a) {
},
enumerable: true,
configurable: true
});
C1.sf = function () {
return this.sx;
};
Object.defineProperty(C1, "staticSetter", {
set: function (a) {
},
enumerable: true,
configurable: true
});
Object.defineProperty(C1, "staticGetter", {
get: function () {
return 0;
},
enumerable: true,
configurable: true
});
return C1;
})();
// Derived class overriding protected members
var C2 = (function (_super) {
__extends(C2, _super);
function C2() {
_super.apply(this, arguments);
}
C2.prototype.f = function () {
return _super.prototype.f.call(this) + this.x;
};
C2.sf = function () {
return _super.sf.call(this) + this.sx;
};
return C2;
})(C1);
// Derived class making protected members public
var C3 = (function (_super) {
__extends(C3, _super);
function C3() {
_super.apply(this, arguments);
}
C3.prototype.f = function () {
return _super.prototype.f.call(this);
};
C3.sf = function () {
return _super.sf.call(this);
};
Object.defineProperty(C3, "staticGetter", {
get: function () {
return 1;
},
enumerable: true,
configurable: true
});
return C3;
})(C2);
// Protected properties in constructors
var C4 = (function () {
function C4(a, b) {
this.a = a;
this.b = b;
}
return C4;
})();
//// [declarationEmit_protectedMembers.d.ts]
declare class C1 {
protected x: number;
protected f(): number;
protected accessor: number;
protected static sx: number;
protected static sf(): number;
protected static staticSetter: number;
protected static staticGetter: number;
}
declare class C2 extends C1 {
protected f(): number;
protected static sf(): number;
}
declare class C3 extends C2 {
x: number;
static sx: number;
f(): number;
static sf(): number;
static staticGetter: number;
}
declare class C4 {
protected a: number;
protected b: any;
constructor(a: number, b: any);
}

View file

@ -0,0 +1,120 @@
=== tests/cases/compiler/declarationEmit_protectedMembers.ts ===
// Class with protected members
class C1 {
>C1 : C1
protected x: number;
>x : number
protected f() {
>f : () => number
return this.x;
>this.x : number
>this : C1
>x : number
}
protected set accessor(a: number) { }
>accessor : number
>a : number
protected get accessor() { return 0; }
>accessor : number
protected static sx: number;
>sx : number
protected static sf() {
>sf : () => number
return this.sx;
>this.sx : number
>this : typeof C1
>sx : number
}
protected static set staticSetter(a: number) { }
>staticSetter : number
>a : number
protected static get staticGetter() { return 0; }
>staticGetter : number
}
// Derived class overriding protected members
class C2 extends C1 {
>C2 : C2
>C1 : C1
protected f() {
>f : () => number
return super.f() + this.x;
>super.f() + this.x : number
>super.f() : number
>super.f : () => number
>super : C1
>f : () => number
>this.x : number
>this : C2
>x : number
}
protected static sf() {
>sf : () => number
return super.sf() + this.sx;
>super.sf() + this.sx : number
>super.sf() : number
>super.sf : () => number
>super : typeof C1
>sf : () => number
>this.sx : number
>this : typeof C2
>sx : number
}
}
// Derived class making protected members public
class C3 extends C2 {
>C3 : C3
>C2 : C2
x: number;
>x : number
static sx: number;
>sx : number
f() {
>f : () => number
return super.f();
>super.f() : number
>super.f : () => number
>super : C2
>f : () => number
}
static sf() {
>sf : () => number
return super.sf();
>super.sf() : number
>super.sf : () => number
>super : typeof C2
>sf : () => number
}
static get staticGetter() { return 1; }
>staticGetter : number
}
// Protected properties in constructors
class C4 {
>C4 : C4
constructor(protected a: number, protected b) { }
>a : number
>b : any
}

View file

@ -0,0 +1,103 @@
//// [derivedClassOverridesProtectedMembers.ts]
var x: { foo: string; }
var y: { foo: string; bar: string; }
class Base {
protected a: typeof x;
protected b(a: typeof x) { }
protected get c() { return x; }
protected set c(v: typeof x) { }
protected d: (a: typeof x) => void;
protected static r: typeof x;
protected static s(a: typeof x) { }
protected static get t() { return x; }
protected static set t(v: typeof x) { }
protected static u: (a: typeof x) => void;
constructor(a: typeof x) { }
}
class Derived extends Base {
protected a: typeof y;
protected b(a: typeof y) { }
protected get c() { return y; }
protected set c(v: typeof y) { }
protected d: (a: typeof y) => void;
protected static r: typeof y;
protected static s(a: typeof y) { }
protected static get t() { return y; }
protected static set t(a: typeof y) { }
protected static u: (a: typeof y) => void;
constructor(a: typeof y) { super(x) }
}
//// [derivedClassOverridesProtectedMembers.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);

View file

@ -0,0 +1,123 @@
=== tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassOverridesProtectedMembers.ts ===
var x: { foo: string; }
>x : { foo: string; }
>foo : string
var y: { foo: string; bar: string; }
>y : { foo: string; bar: string; }
>foo : string
>bar : string
class Base {
>Base : Base
protected a: typeof x;
>a : { foo: string; }
>x : { foo: string; }
protected b(a: typeof x) { }
>b : (a: { foo: string; }) => void
>a : { foo: string; }
>x : { foo: string; }
protected get c() { return x; }
>c : { foo: string; }
>x : { foo: string; }
protected set c(v: typeof x) { }
>c : { foo: string; }
>v : { foo: string; }
>x : { foo: string; }
protected d: (a: typeof x) => void;
>d : (a: { foo: string; }) => void
>a : { foo: string; }
>x : { foo: string; }
protected static r: typeof x;
>r : { foo: string; }
>x : { foo: string; }
protected static s(a: typeof x) { }
>s : (a: { foo: string; }) => void
>a : { foo: string; }
>x : { foo: string; }
protected static get t() { return x; }
>t : { foo: string; }
>x : { foo: string; }
protected static set t(v: typeof x) { }
>t : { foo: string; }
>v : { foo: string; }
>x : { foo: string; }
protected static u: (a: typeof x) => void;
>u : (a: { foo: string; }) => void
>a : { foo: string; }
>x : { foo: string; }
constructor(a: typeof x) { }
>a : { foo: string; }
>x : { foo: string; }
}
class Derived extends Base {
>Derived : Derived
>Base : Base
protected a: typeof y;
>a : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
protected b(a: typeof y) { }
>b : (a: { foo: string; bar: string; }) => void
>a : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
protected get c() { return y; }
>c : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
protected set c(v: typeof y) { }
>c : { foo: string; bar: string; }
>v : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
protected d: (a: typeof y) => void;
>d : (a: { foo: string; bar: string; }) => void
>a : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
protected static r: typeof y;
>r : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
protected static s(a: typeof y) { }
>s : (a: { foo: string; bar: string; }) => void
>a : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
protected static get t() { return y; }
>t : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
protected static set t(a: typeof y) { }
>t : { foo: string; bar: string; }
>a : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
protected static u: (a: typeof y) => void;
>u : (a: { foo: string; bar: string; }) => void
>a : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
constructor(a: typeof y) { super(x) }
>a : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
>super(x) : void
>super : typeof Base
>x : { foo: string; }
}

View file

@ -0,0 +1,157 @@
//// [derivedClassOverridesProtectedMembers2.ts]
var x: { foo: string; }
var y: { foo: string; bar: string; }
class Base {
protected a: typeof x;
protected b(a: typeof x) { }
protected get c() { return x; }
protected set c(v: typeof x) { }
protected d: (a: typeof x) => void ;
protected static r: typeof x;
protected static s(a: typeof x) { }
protected static get t() { return x; }
protected static set t(v: typeof x) { }
protected static u: (a: typeof x) => void ;
constructor(a: typeof x) { }
}
// Increase visibility of all protected members to public
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(a); }
}
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];
//// [derivedClassOverridesProtectedMembers2.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;
})();
// Increase visibility of all protected members to public
var Derived = (function (_super) {
__extends(Derived, _super);
function Derived(a) {
_super.call(this, a);
}
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];

View file

@ -0,0 +1,236 @@
=== tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassOverridesProtectedMembers2.ts ===
var x: { foo: string; }
>x : { foo: string; }
>foo : string
var y: { foo: string; bar: string; }
>y : { foo: string; bar: string; }
>foo : string
>bar : string
class Base {
>Base : Base
protected a: typeof x;
>a : { foo: string; }
>x : { foo: string; }
protected b(a: typeof x) { }
>b : (a: { foo: string; }) => void
>a : { foo: string; }
>x : { foo: string; }
protected get c() { return x; }
>c : { foo: string; }
>x : { foo: string; }
protected set c(v: typeof x) { }
>c : { foo: string; }
>v : { foo: string; }
>x : { foo: string; }
protected d: (a: typeof x) => void ;
>d : (a: { foo: string; }) => void
>a : { foo: string; }
>x : { foo: string; }
protected static r: typeof x;
>r : { foo: string; }
>x : { foo: string; }
protected static s(a: typeof x) { }
>s : (a: { foo: string; }) => void
>a : { foo: string; }
>x : { foo: string; }
protected static get t() { return x; }
>t : { foo: string; }
>x : { foo: string; }
protected static set t(v: typeof x) { }
>t : { foo: string; }
>v : { foo: string; }
>x : { foo: string; }
protected static u: (a: typeof x) => void ;
>u : (a: { foo: string; }) => void
>a : { foo: string; }
>x : { foo: string; }
constructor(a: typeof x) { }
>a : { foo: string; }
>x : { foo: string; }
}
// Increase visibility of all protected members to public
class Derived extends Base {
>Derived : Derived
>Base : Base
a: typeof y;
>a : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
b(a: typeof y) { }
>b : (a: { foo: string; bar: string; }) => void
>a : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
get c() { return y; }
>c : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
set c(v: typeof y) { }
>c : { foo: string; bar: string; }
>v : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
d: (a: typeof y) => void;
>d : (a: { foo: string; bar: string; }) => void
>a : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
static r: typeof y;
>r : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
static s(a: typeof y) { }
>s : (a: { foo: string; bar: string; }) => void
>a : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
static get t() { return y; }
>t : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
static set t(a: typeof y) { }
>t : { foo: string; bar: string; }
>a : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
static u: (a: typeof y) => void;
>u : (a: { foo: string; bar: string; }) => void
>a : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
constructor(a: typeof y) { super(a); }
>a : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
>super(a) : void
>super : typeof Base
>a : { foo: string; bar: string; }
}
var d: Derived = new Derived(y);
>d : Derived
>Derived : Derived
>new Derived(y) : Derived
>Derived : typeof Derived
>y : { foo: string; bar: string; }
var r1 = d.a;
>r1 : { foo: string; bar: string; }
>d.a : { foo: string; bar: string; }
>d : Derived
>a : { foo: string; bar: string; }
var r2 = d.b(y);
>r2 : void
>d.b(y) : void
>d.b : (a: { foo: string; bar: string; }) => void
>d : Derived
>b : (a: { foo: string; bar: string; }) => void
>y : { foo: string; bar: string; }
var r3 = d.c;
>r3 : { foo: string; bar: string; }
>d.c : { foo: string; bar: string; }
>d : Derived
>c : { foo: string; bar: string; }
var r3a = d.d;
>r3a : (a: { foo: string; bar: string; }) => void
>d.d : (a: { foo: string; bar: string; }) => void
>d : Derived
>d : (a: { foo: string; bar: string; }) => void
d.c = y;
>d.c = y : { foo: string; bar: string; }
>d.c : { foo: string; bar: string; }
>d : Derived
>c : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
var r4 = Derived.r;
>r4 : { foo: string; bar: string; }
>Derived.r : { foo: string; bar: string; }
>Derived : typeof Derived
>r : { foo: string; bar: string; }
var r5 = Derived.s(y);
>r5 : void
>Derived.s(y) : void
>Derived.s : (a: { foo: string; bar: string; }) => void
>Derived : typeof Derived
>s : (a: { foo: string; bar: string; }) => void
>y : { foo: string; bar: string; }
var r6 = Derived.t;
>r6 : { foo: string; bar: string; }
>Derived.t : { foo: string; bar: string; }
>Derived : typeof Derived
>t : { foo: string; bar: string; }
var r6a = Derived.u;
>r6a : (a: { foo: string; bar: string; }) => void
>Derived.u : (a: { foo: string; bar: string; }) => void
>Derived : typeof Derived
>u : (a: { foo: string; bar: string; }) => void
Derived.t = y;
>Derived.t = y : { foo: string; bar: string; }
>Derived.t : { foo: string; bar: string; }
>Derived : typeof Derived
>t : { foo: string; bar: string; }
>y : { foo: string; bar: string; }
class Base2 {
>Base2 : Base2
[i: string]: Object;
>i : string
>Object : Object
[i: number]: typeof x;
>i : number
>x : { foo: string; }
}
class Derived2 extends Base2 {
>Derived2 : Derived2
>Base2 : Base2
[i: string]: typeof x;
>i : string
>x : { foo: string; }
[i: number]: typeof y;
>i : number
>y : { foo: string; bar: string; }
}
var d2: Derived2;
>d2 : Derived2
>Derived2 : Derived2
var r7 = d2[''];
>r7 : { foo: string; }
>d2[''] : { foo: string; }
>d2 : Derived2
var r8 = d2[1];
>r8 : { foo: string; bar: string; }
>d2[1] : { foo: string; bar: string; }
>d2 : Derived2

View file

@ -0,0 +1,124 @@
tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassOverridesProtectedMembers3.ts(23,7): error TS2416: Class 'Derived1' incorrectly extends base class 'Base':
Property 'a' is protected in type 'Derived1' but public in type 'Base'.
tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassOverridesProtectedMembers3.ts(28,7): error TS2416: Class 'Derived2' incorrectly extends base class 'Base':
Property 'b' is protected in type 'Derived2' but public in type 'Base'.
tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassOverridesProtectedMembers3.ts(33,7): error TS2416: Class 'Derived3' incorrectly extends base class 'Base':
Property 'c' is protected in type 'Derived3' but public in type 'Base'.
tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassOverridesProtectedMembers3.ts(38,7): error TS2416: Class 'Derived4' incorrectly extends base class 'Base':
Property 'c' is protected in type 'Derived4' but public in type 'Base'.
tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassOverridesProtectedMembers3.ts(43,7): error TS2416: Class 'Derived5' incorrectly extends base class 'Base':
Property 'd' is protected in type 'Derived5' but public in type 'Base'.
tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassOverridesProtectedMembers3.ts(48,7): error TS2418: Class static side 'typeof Derived6' incorrectly extends base class static side 'typeof Base':
Property 'r' is protected in type 'typeof Derived6' but public in type 'typeof Base'.
tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassOverridesProtectedMembers3.ts(53,7): error TS2418: Class static side 'typeof Derived7' incorrectly extends base class static side 'typeof Base':
Property 's' is protected in type 'typeof Derived7' but public in type 'typeof Base'.
tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassOverridesProtectedMembers3.ts(58,7): error TS2418: Class static side 'typeof Derived8' incorrectly extends base class static side 'typeof Base':
Property 't' is protected in type 'typeof Derived8' but public in type 'typeof Base'.
tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassOverridesProtectedMembers3.ts(63,7): error TS2418: Class static side 'typeof Derived9' incorrectly extends base class static side 'typeof Base':
Property 't' is protected in type 'typeof Derived9' but public in type 'typeof Base'.
tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassOverridesProtectedMembers3.ts(68,7): error TS2418: Class static side 'typeof Derived10' incorrectly extends base class static side 'typeof Base':
Property 'u' is protected in type 'typeof Derived10' but public in type 'typeof Base'.
==== tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassOverridesProtectedMembers3.ts (10 errors) ====
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) {}
}
// Errors
// decrease visibility of all public members to protected
class Derived1 extends Base {
~~~~~~~~
!!! error TS2416: Class 'Derived1' incorrectly extends base class 'Base':
!!! error TS2416: Property 'a' is protected in type 'Derived1' but public in type 'Base'.
protected a: typeof x;
constructor(a: typeof x) { super(a); }
}
class Derived2 extends Base {
~~~~~~~~
!!! error TS2416: Class 'Derived2' incorrectly extends base class 'Base':
!!! error TS2416: Property 'b' is protected in type 'Derived2' but public in type 'Base'.
protected b(a: typeof x) { }
constructor(a: typeof x) { super(a); }
}
class Derived3 extends Base {
~~~~~~~~
!!! error TS2416: Class 'Derived3' incorrectly extends base class 'Base':
!!! error TS2416: Property 'c' is protected in type 'Derived3' but public in type 'Base'.
protected get c() { return x; }
constructor(a: typeof x) { super(a); }
}
class Derived4 extends Base {
~~~~~~~~
!!! error TS2416: Class 'Derived4' incorrectly extends base class 'Base':
!!! error TS2416: Property 'c' is protected in type 'Derived4' but public in type 'Base'.
protected set c(v: typeof x) { }
constructor(a: typeof x) { super(a); }
}
class Derived5 extends Base {
~~~~~~~~
!!! error TS2416: Class 'Derived5' incorrectly extends base class 'Base':
!!! error TS2416: Property 'd' is protected in type 'Derived5' but public in type 'Base'.
protected d: (a: typeof x) => void ;
constructor(a: typeof x) { super(a); }
}
class Derived6 extends Base {
~~~~~~~~
!!! error TS2418: Class static side 'typeof Derived6' incorrectly extends base class static side 'typeof Base':
!!! error TS2418: Property 'r' is protected in type 'typeof Derived6' but public in type 'typeof Base'.
protected static r: typeof x;
constructor(a: typeof x) { super(a); }
}
class Derived7 extends Base {
~~~~~~~~
!!! error TS2418: Class static side 'typeof Derived7' incorrectly extends base class static side 'typeof Base':
!!! error TS2418: Property 's' is protected in type 'typeof Derived7' but public in type 'typeof Base'.
protected static s(a: typeof x) { }
constructor(a: typeof x) { super(a); }
}
class Derived8 extends Base {
~~~~~~~~
!!! error TS2418: Class static side 'typeof Derived8' incorrectly extends base class static side 'typeof Base':
!!! error TS2418: Property 't' is protected in type 'typeof Derived8' but public in type 'typeof Base'.
protected static get t() { return x; }
constructor(a: typeof x) { super(a); }
}
class Derived9 extends Base {
~~~~~~~~
!!! error TS2418: Class static side 'typeof Derived9' incorrectly extends base class static side 'typeof Base':
!!! error TS2418: Property 't' is protected in type 'typeof Derived9' but public in type 'typeof Base'.
protected static set t(v: typeof x) { }
constructor(a: typeof x) { super(a); }
}
class Derived10 extends Base {
~~~~~~~~~
!!! error TS2418: Class static side 'typeof Derived10' incorrectly extends base class static side 'typeof Base':
!!! error TS2418: Property 'u' is protected in type 'typeof Derived10' but public in type 'typeof Base'.
protected static u: (a: typeof x) => void ;
constructor(a: typeof x) { super(a); }
}

View file

@ -0,0 +1,211 @@
//// [derivedClassOverridesProtectedMembers3.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) {}
}
// Errors
// decrease visibility of all public members to protected
class Derived1 extends Base {
protected a: typeof x;
constructor(a: typeof x) { super(a); }
}
class Derived2 extends Base {
protected b(a: typeof x) { }
constructor(a: typeof x) { super(a); }
}
class Derived3 extends Base {
protected get c() { return x; }
constructor(a: typeof x) { super(a); }
}
class Derived4 extends Base {
protected set c(v: typeof x) { }
constructor(a: typeof x) { super(a); }
}
class Derived5 extends Base {
protected d: (a: typeof x) => void ;
constructor(a: typeof x) { super(a); }
}
class Derived6 extends Base {
protected static r: typeof x;
constructor(a: typeof x) { super(a); }
}
class Derived7 extends Base {
protected static s(a: typeof x) { }
constructor(a: typeof x) { super(a); }
}
class Derived8 extends Base {
protected static get t() { return x; }
constructor(a: typeof x) { super(a); }
}
class Derived9 extends Base {
protected static set t(v: typeof x) { }
constructor(a: typeof x) { super(a); }
}
class Derived10 extends Base {
protected static u: (a: typeof x) => void ;
constructor(a: typeof x) { super(a); }
}
//// [derivedClassOverridesProtectedMembers3.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;
})();
// Errors
// decrease visibility of all public members to protected
var Derived1 = (function (_super) {
__extends(Derived1, _super);
function Derived1(a) {
_super.call(this, a);
}
return Derived1;
})(Base);
var Derived2 = (function (_super) {
__extends(Derived2, _super);
function Derived2(a) {
_super.call(this, a);
}
Derived2.prototype.b = function (a) {
};
return Derived2;
})(Base);
var Derived3 = (function (_super) {
__extends(Derived3, _super);
function Derived3(a) {
_super.call(this, a);
}
Object.defineProperty(Derived3.prototype, "c", {
get: function () {
return x;
},
enumerable: true,
configurable: true
});
return Derived3;
})(Base);
var Derived4 = (function (_super) {
__extends(Derived4, _super);
function Derived4(a) {
_super.call(this, a);
}
Object.defineProperty(Derived4.prototype, "c", {
set: function (v) {
},
enumerable: true,
configurable: true
});
return Derived4;
})(Base);
var Derived5 = (function (_super) {
__extends(Derived5, _super);
function Derived5(a) {
_super.call(this, a);
}
return Derived5;
})(Base);
var Derived6 = (function (_super) {
__extends(Derived6, _super);
function Derived6(a) {
_super.call(this, a);
}
return Derived6;
})(Base);
var Derived7 = (function (_super) {
__extends(Derived7, _super);
function Derived7(a) {
_super.call(this, a);
}
Derived7.s = function (a) {
};
return Derived7;
})(Base);
var Derived8 = (function (_super) {
__extends(Derived8, _super);
function Derived8(a) {
_super.call(this, a);
}
Object.defineProperty(Derived8, "t", {
get: function () {
return x;
},
enumerable: true,
configurable: true
});
return Derived8;
})(Base);
var Derived9 = (function (_super) {
__extends(Derived9, _super);
function Derived9(a) {
_super.call(this, a);
}
Object.defineProperty(Derived9, "t", {
set: function (v) {
},
enumerable: true,
configurable: true
});
return Derived9;
})(Base);
var Derived10 = (function (_super) {
__extends(Derived10, _super);
function Derived10(a) {
_super.call(this, a);
}
return Derived10;
})(Base);

View file

@ -0,0 +1,22 @@
tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassOverridesProtectedMembers4.ts(12,7): error TS2416: Class 'Derived2' incorrectly extends base class 'Derived1':
Property 'a' is protected in type 'Derived2' but public in type 'Derived1'.
==== tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassOverridesProtectedMembers4.ts (1 errors) ====
var x: { foo: string; }
var y: { foo: string; bar: string; }
class Base {
protected a: typeof x;
}
class Derived1 extends Base {
public a: typeof x;
}
class Derived2 extends Derived1 {
~~~~~~~~
!!! error TS2416: Class 'Derived2' incorrectly extends base class 'Derived1':
!!! error TS2416: Property 'a' is protected in type 'Derived2' but public in type 'Derived1'.
protected a: typeof x; // Error, parent was public
}

View file

@ -0,0 +1,44 @@
//// [derivedClassOverridesProtectedMembers4.ts]
var x: { foo: string; }
var y: { foo: string; bar: string; }
class Base {
protected a: typeof x;
}
class Derived1 extends Base {
public a: typeof x;
}
class Derived2 extends Derived1 {
protected a: typeof x; // Error, parent was public
}
//// [derivedClassOverridesProtectedMembers4.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() {
}
return Base;
})();
var Derived1 = (function (_super) {
__extends(Derived1, _super);
function Derived1() {
_super.apply(this, arguments);
}
return Derived1;
})(Base);
var Derived2 = (function (_super) {
__extends(Derived2, _super);
function Derived2() {
_super.apply(this, arguments);
}
return Derived2;
})(Derived1);

View file

@ -0,0 +1,37 @@
tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassTransitivity4.ts(18,1): error TS2322: Type 'E' is not assignable to type 'C':
Types of property 'foo' are incompatible:
Type '(x?: string) => void' is not assignable to type '(x: number) => void':
Types of parameters 'x' and 'x' are incompatible:
Type 'string' is not assignable to type 'number'.
tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassTransitivity4.ts(19,9): error TS2445: Property 'foo' is protected and only accessible within class 'C' and its subclasses.
==== tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassTransitivity4.ts (2 errors) ====
// subclassing is not transitive when you can remove required parameters and add optional parameters on protected members
class C {
protected foo(x: number) { }
}
class D extends C {
protected foo() { } // ok to drop parameters
}
class E extends D {
public foo(x?: string) { } // ok to add optional parameters
}
var c: C;
var d: D;
var e: E;
c = e;
~
!!! error TS2322: Type 'E' is not assignable to type 'C':
!!! error TS2322: Types of property 'foo' are incompatible:
!!! error TS2322: Type '(x?: string) => void' is not assignable to type '(x: number) => void':
!!! error TS2322: Types of parameters 'x' and 'x' are incompatible:
!!! error TS2322: Type 'string' is not assignable to type 'number'.
var r = c.foo(1);
~~~~~
!!! error TS2445: Property 'foo' is protected and only accessible within class 'C' and its subclasses.
var r2 = e.foo('');

View file

@ -0,0 +1,61 @@
//// [derivedClassTransitivity4.ts]
// subclassing is not transitive when you can remove required parameters and add optional parameters on protected members
class C {
protected foo(x: number) { }
}
class D extends C {
protected foo() { } // ok to drop parameters
}
class E extends D {
public foo(x?: string) { } // ok to add optional parameters
}
var c: C;
var d: D;
var e: E;
c = e;
var r = c.foo(1);
var r2 = e.foo('');
//// [derivedClassTransitivity4.js]
// subclassing is not transitive when you can remove required parameters and add optional parameters on protected members
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() {
}
C.prototype.foo = function (x) {
};
return C;
})();
var D = (function (_super) {
__extends(D, _super);
function D() {
_super.apply(this, arguments);
}
D.prototype.foo = function () {
}; // ok to drop parameters
return D;
})(C);
var E = (function (_super) {
__extends(E, _super);
function E() {
_super.apply(this, arguments);
}
E.prototype.foo = function (x) {
}; // ok to add optional parameters
return E;
})(D);
var c;
var d;
var e;
c = e;
var r = c.foo(1);
var r2 = e.foo('');

View file

@ -0,0 +1,30 @@
tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassWithPrivateInstanceShadowingProtectedInstance.ts(13,7): error TS2416: Class 'Derived' incorrectly extends base class 'Base':
Property 'x' is private in type 'Derived' but not in type 'Base'.
==== tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassWithPrivateInstanceShadowingProtectedInstance.ts (1 errors) ====
class Base {
protected x: string;
protected fn(): string {
return '';
}
protected get a() { return 1; }
protected set a(v) { }
}
// error, not a subtype
class Derived extends Base {
~~~~~~~
!!! error TS2416: Class 'Derived' incorrectly extends base class 'Base':
!!! error TS2416: Property 'x' is private in type 'Derived' but not in type 'Base'.
private x: string;
private fn(): string {
return '';
}
private get a() { return 1; }
private set a(v) { }
}

View file

@ -0,0 +1,68 @@
//// [derivedClassWithPrivateInstanceShadowingProtectedInstance.ts]
class Base {
protected x: string;
protected fn(): string {
return '';
}
protected get a() { return 1; }
protected 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) { }
}
//// [derivedClassWithPrivateInstanceShadowingProtectedInstance.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);

View file

@ -0,0 +1,29 @@
tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassWithPrivateStaticShadowingProtectedStatic.ts(13,7): error TS2418: Class static side 'typeof Derived' incorrectly extends base class static side 'typeof Base':
Property 'x' is private in type 'typeof Derived' but not in type 'typeof Base'.
==== tests/cases/conformance/classes/members/inheritanceAndOverriding/derivedClassWithPrivateStaticShadowingProtectedStatic.ts (1 errors) ====
class Base {
protected static x: string;
protected static fn(): string {
return '';
}
protected static get a() { return 1; }
protected static set a(v) { }
}
// should be error
class Derived extends Base {
~~~~~~~
!!! error TS2418: Class static side 'typeof Derived' incorrectly extends base class static side 'typeof Base':
!!! error TS2418: Property 'x' is private in type 'typeof Derived' but not in type 'typeof Base'.
private static x: string;
private static fn(): string {
return '';
}
private static get a() { return 1; }
private static set a(v) { }
}

View file

@ -0,0 +1,67 @@
//// [derivedClassWithPrivateStaticShadowingProtectedStatic.ts]
class Base {
protected static x: string;
protected static fn(): string {
return '';
}
protected static get a() { return 1; }
protected static set a(v) { }
}
// 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) { }
}
//// [derivedClassWithPrivateStaticShadowingProtectedStatic.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;
})();
// 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);

View file

@ -0,0 +1,18 @@
tests/cases/conformance/interfaces/interfaceDeclarations/interfaceWithAccessibilityModifiers.ts(3,5): error TS1131: Property or signature expected.
tests/cases/conformance/interfaces/interfaceDeclarations/interfaceWithAccessibilityModifiers.ts(4,5): error TS1131: Property or signature expected.
tests/cases/conformance/interfaces/interfaceDeclarations/interfaceWithAccessibilityModifiers.ts(5,5): error TS1131: Property or signature expected.
==== tests/cases/conformance/interfaces/interfaceDeclarations/interfaceWithAccessibilityModifiers.ts (3 errors) ====
// Errors
interface Foo {
public a: any;
~~~~~~
!!! error TS1131: Property or signature expected.
private b: any;
~~~~~~~
!!! error TS1131: Property or signature expected.
protected c: any;
~~~~~~~~~
!!! error TS1131: Property or signature expected.
}

View file

@ -1,16 +1,21 @@
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(3,12): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(7,12): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(12,19): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(16,19): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(23,12): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(27,12): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(32,19): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(36,19): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(42,9): error TS2341: Property 'foo' is private and only accessible within class 'C'.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(45,10): error TS2341: Property 'foo' is private and only accessible within class 'D<T>'.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(15,15): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(16,15): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(20,19): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(25,19): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(32,12): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(36,12): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(41,15): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(45,19): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(49,19): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(53,19): error TS2385: Overload signatures must all be public, private or protected.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(59,9): error TS2341: Property 'foo' is private and only accessible within class 'C'.
tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts(62,10): error TS2341: Property 'foo' is private and only accessible within class 'D<T>'.
==== tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts (10 errors) ====
==== tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclarations/memberFunctionsWithPublicPrivateOverloads.ts (15 errors) ====
class C {
private foo(x: number);
public foo(x: number, y: string); // error
@ -31,12 +36,27 @@ tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclara
!!! error TS2385: Overload signatures must all be public, private or protected.
private static foo(x: any, y?: any) { }
protected baz(x: string); // error
~~~
!!! error TS2385: Overload signatures must all be public, private or protected.
protected baz(x: number, y: string); // error
~~~
!!! error TS2385: Overload signatures must all be public, private or protected.
private baz(x: any, y?: any) { }
private static bar(x: 'hi');
public static bar(x: string); // error
~~~
!!! error TS2385: Overload signatures must all be public, private or protected.
private static bar(x: number, y: string);
private static bar(x: any, y?: any) { }
protected static baz(x: 'hi');
public static baz(x: string); // error
~~~
!!! error TS2385: Overload signatures must all be public, private or protected.
protected static baz(x: number, y: string);
protected static baz(x: any, y?: any) { }
}
class D<T> {
@ -53,6 +73,12 @@ tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclara
private bar(x: T, y: T);
private bar(x: any, y?: any) { }
private baz(x: string);
protected baz(x: number, y: string); // error
~~~
!!! error TS2385: Overload signatures must all be public, private or protected.
private baz(x: any, y?: any) { }
private static foo(x: number);
public static foo(x: number, y: string); // error
~~~
@ -65,6 +91,12 @@ tests/cases/conformance/classes/propertyMemberDeclarations/memberFunctionDeclara
!!! error TS2385: Overload signatures must all be public, private or protected.
private static bar(x: number, y: string);
private static bar(x: any, y?: any) { }
public static baz(x: string); // error
~~~
!!! error TS2385: Overload signatures must all be public, private or protected.
protected static baz(x: number, y: string);
protected static baz(x: any, y?: any) { }
}
var c: C;

View file

@ -13,10 +13,19 @@ class C {
public static foo(x: number, y: string); // error
private static foo(x: any, y?: any) { }
protected baz(x: string); // error
protected baz(x: number, y: string); // error
private baz(x: any, y?: any) { }
private static bar(x: 'hi');
public static bar(x: string); // error
private static bar(x: number, y: string);
private static bar(x: any, y?: any) { }
protected static baz(x: 'hi');
public static baz(x: string); // error
protected static baz(x: number, y: string);
protected static baz(x: any, y?: any) { }
}
class D<T> {
@ -29,6 +38,10 @@ class D<T> {
private bar(x: T, y: T);
private bar(x: any, y?: any) { }
private baz(x: string);
protected baz(x: number, y: string); // error
private baz(x: any, y?: any) { }
private static foo(x: number);
public static foo(x: number, y: string); // error
private static foo(x: any, y?: any) { }
@ -37,6 +50,10 @@ class D<T> {
public static bar(x: string); // error
private static bar(x: number, y: string);
private static bar(x: any, y?: any) { }
public static baz(x: string); // error
protected static baz(x: number, y: string);
protected static baz(x: any, y?: any) { }
}
var c: C;
@ -55,8 +72,12 @@ var C = (function () {
};
C.foo = function (x, y) {
};
C.prototype.baz = function (x, y) {
};
C.bar = function (x, y) {
};
C.baz = function (x, y) {
};
return C;
})();
var D = (function () {
@ -66,10 +87,14 @@ var D = (function () {
};
D.prototype.bar = function (x, y) {
};
D.prototype.baz = function (x, y) {
};
D.foo = function (x, y) {
};
D.bar = function (x, y) {
};
D.baz = function (x, y) {
};
return D;
})();
var c;

View file

@ -0,0 +1,160 @@
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(13,9): error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(26,9): error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived1'.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(28,9): error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived1'.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(29,9): error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(30,9): error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived1'.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(42,9): error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived2'.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(43,9): error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived2'.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(45,9): error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(59,9): error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived3'.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(60,9): error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived3'.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(61,9): error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived3'.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(63,9): error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived3'.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(75,9): error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived4'.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(76,9): error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived4'.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(77,9): error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived4'.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(78,9): error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(90,1): error TS2445: Property 'x' is protected and only accessible within class 'Base' and its subclasses.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(91,1): error TS2445: Property 'x' is protected and only accessible within class 'Base' and its subclasses.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(92,1): error TS2445: Property 'x' is protected and only accessible within class 'Base' and its subclasses.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(93,1): error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts(94,1): error TS2445: Property 'x' is protected and only accessible within class 'Base' and its subclasses.
==== tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass2.ts (21 errors) ====
class Base {
protected x: string;
method() {
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // OK, accessed within their declaring class
d1.x; // OK, accessed within their declaring class
d2.x; // OK, accessed within their declaring class
d3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
~~~~
!!! error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.
d4.x; // OK, accessed within their declaring class
}
}
class Derived1 extends Base {
method1() {
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // Error, isn't accessed through an instance of the enclosing class
~~~
!!! error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived1'.
d1.x; // OK, accessed within a class derived from their declaring class, and through an instance of the enclosing class
d2.x; // Error, isn't accessed through an instance of the enclosing class
~~~~
!!! error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived1'.
d3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
~~~~
!!! error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.
d4.x; // Error, isn't accessed through an instance of the enclosing class
~~~~
!!! error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived1'.
}
}
class Derived2 extends Base {
method2() {
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // Error, isn't accessed through an instance of the enclosing class
~~~
!!! error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived2'.
d1.x; // Error, isn't accessed through an instance of the enclosing class
~~~~
!!! error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived2'.
d2.x; // OK, accessed within a class derived from their declaring class, and through an instance of the enclosing class
d3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
~~~~
!!! error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.
d4.x; // OK, accessed within a class derived from their declaring class, and through an instance of the enclosing class or one of its subclasses
}
}
class Derived3 extends Derived1 {
protected x: string;
method3() {
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // Error, isn't accessed through an instance of the enclosing class
~~~
!!! error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived3'.
d1.x; // Error, isn't accessed through an instance of the enclosing class
~~~~
!!! error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived3'.
d2.x; // Error, isn't accessed through an instance of the enclosing class
~~~~
!!! error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived3'.
d3.x; // OK, accessed within their declaring class
d4.x; // Error, isn't accessed through an instance of the enclosing class
~~~~
!!! error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived3'.
}
}
class Derived4 extends Derived2 {
method4() {
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // Error, isn't accessed through an instance of the enclosing class
~~~
!!! error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived4'.
d1.x; // Error, isn't accessed through an instance of the enclosing class
~~~~
!!! error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived4'.
d2.x; // Error, isn't accessed through an instance of the enclosing class
~~~~
!!! error TS2446: Property 'x' is protected and only accessible through an instance of class 'Derived4'.
d3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
~~~~
!!! error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.
d4.x; // OK, accessed within a class derived from their declaring class, and through an instance of the enclosing class
}
}
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // Error, neither within their declaring class nor classes derived from their declaring class
~~~
!!! error TS2445: Property 'x' is protected and only accessible within class 'Base' and its subclasses.
d1.x; // Error, neither within their declaring class nor classes derived from their declaring class
~~~~
!!! error TS2445: Property 'x' is protected and only accessible within class 'Base' and its subclasses.
d2.x; // Error, neither within their declaring class nor classes derived from their declaring class
~~~~
!!! error TS2445: Property 'x' is protected and only accessible within class 'Base' and its subclasses.
d3.x; // Error, neither within their declaring class nor classes derived from their declaring class
~~~~
!!! error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.
d4.x; // Error, neither within their declaring class nor classes derived from their declaring class
~~~~
!!! error TS2445: Property 'x' is protected and only accessible within class 'Base' and its subclasses.

View file

@ -0,0 +1,206 @@
//// [protectedClassPropertyAccessibleWithinSubclass2.ts]
class Base {
protected x: string;
method() {
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // OK, accessed within their declaring class
d1.x; // OK, accessed within their declaring class
d2.x; // OK, accessed within their declaring class
d3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
d4.x; // OK, accessed within their declaring class
}
}
class Derived1 extends Base {
method1() {
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // Error, isn't accessed through an instance of the enclosing class
d1.x; // OK, accessed within a class derived from their declaring class, and through an instance of the enclosing class
d2.x; // Error, isn't accessed through an instance of the enclosing class
d3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
d4.x; // Error, isn't accessed through an instance of the enclosing class
}
}
class Derived2 extends Base {
method2() {
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // Error, isn't accessed through an instance of the enclosing class
d1.x; // Error, isn't accessed through an instance of the enclosing class
d2.x; // OK, accessed within a class derived from their declaring class, and through an instance of the enclosing class
d3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
d4.x; // OK, accessed within a class derived from their declaring class, and through an instance of the enclosing class or one of its subclasses
}
}
class Derived3 extends Derived1 {
protected x: string;
method3() {
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // Error, isn't accessed through an instance of the enclosing class
d1.x; // Error, isn't accessed through an instance of the enclosing class
d2.x; // Error, isn't accessed through an instance of the enclosing class
d3.x; // OK, accessed within their declaring class
d4.x; // Error, isn't accessed through an instance of the enclosing class
}
}
class Derived4 extends Derived2 {
method4() {
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // Error, isn't accessed through an instance of the enclosing class
d1.x; // Error, isn't accessed through an instance of the enclosing class
d2.x; // Error, isn't accessed through an instance of the enclosing class
d3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
d4.x; // OK, accessed within a class derived from their declaring class, and through an instance of the enclosing class
}
}
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // Error, neither within their declaring class nor classes derived from their declaring class
d1.x; // Error, neither within their declaring class nor classes derived from their declaring class
d2.x; // Error, neither within their declaring class nor classes derived from their declaring class
d3.x; // Error, neither within their declaring class nor classes derived from their declaring class
d4.x; // Error, neither within their declaring class nor classes derived from their declaring class
//// [protectedClassPropertyAccessibleWithinSubclass2.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.method = function () {
var b;
var d1;
var d2;
var d3;
var d4;
b.x; // OK, accessed within their declaring class
d1.x; // OK, accessed within their declaring class
d2.x; // OK, accessed within their declaring class
d3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
d4.x; // OK, accessed within their declaring class
};
return Base;
})();
var Derived1 = (function (_super) {
__extends(Derived1, _super);
function Derived1() {
_super.apply(this, arguments);
}
Derived1.prototype.method1 = function () {
var b;
var d1;
var d2;
var d3;
var d4;
b.x; // Error, isn't accessed through an instance of the enclosing class
d1.x; // OK, accessed within a class derived from their declaring class, and through an instance of the enclosing class
d2.x; // Error, isn't accessed through an instance of the enclosing class
d3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
d4.x; // Error, isn't accessed through an instance of the enclosing class
};
return Derived1;
})(Base);
var Derived2 = (function (_super) {
__extends(Derived2, _super);
function Derived2() {
_super.apply(this, arguments);
}
Derived2.prototype.method2 = function () {
var b;
var d1;
var d2;
var d3;
var d4;
b.x; // Error, isn't accessed through an instance of the enclosing class
d1.x; // Error, isn't accessed through an instance of the enclosing class
d2.x; // OK, accessed within a class derived from their declaring class, and through an instance of the enclosing class
d3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
d4.x; // OK, accessed within a class derived from their declaring class, and through an instance of the enclosing class or one of its subclasses
};
return Derived2;
})(Base);
var Derived3 = (function (_super) {
__extends(Derived3, _super);
function Derived3() {
_super.apply(this, arguments);
}
Derived3.prototype.method3 = function () {
var b;
var d1;
var d2;
var d3;
var d4;
b.x; // Error, isn't accessed through an instance of the enclosing class
d1.x; // Error, isn't accessed through an instance of the enclosing class
d2.x; // Error, isn't accessed through an instance of the enclosing class
d3.x; // OK, accessed within their declaring class
d4.x; // Error, isn't accessed through an instance of the enclosing class
};
return Derived3;
})(Derived1);
var Derived4 = (function (_super) {
__extends(Derived4, _super);
function Derived4() {
_super.apply(this, arguments);
}
Derived4.prototype.method4 = function () {
var b;
var d1;
var d2;
var d3;
var d4;
b.x; // Error, isn't accessed through an instance of the enclosing class
d1.x; // Error, isn't accessed through an instance of the enclosing class
d2.x; // Error, isn't accessed through an instance of the enclosing class
d3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
d4.x; // OK, accessed within a class derived from their declaring class, and through an instance of the enclosing class
};
return Derived4;
})(Derived2);
var b;
var d1;
var d2;
var d3;
var d4;
b.x; // Error, neither within their declaring class nor classes derived from their declaring class
d1.x; // Error, neither within their declaring class nor classes derived from their declaring class
d2.x; // Error, neither within their declaring class nor classes derived from their declaring class
d3.x; // Error, neither within their declaring class nor classes derived from their declaring class
d4.x; // Error, neither within their declaring class nor classes derived from their declaring class

View file

@ -0,0 +1,19 @@
tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass3.ts(11,15): error TS2340: Only public and protected methods of the base class are accessible via the 'super' keyword
==== tests/cases/conformance/classes/members/accessibility/protectedClassPropertyAccessibleWithinSubclass3.ts (1 errors) ====
class Base {
protected x: string;
method() {
this.x; // OK, accessed within their declaring class
}
}
class Derived extends Base {
method1() {
this.x; // OK, accessed within a subclass of the declaring class
super.x; // Error, x is not public
~
!!! error TS2340: Only public and protected methods of the base class are accessible via the 'super' keyword
}
}

View file

@ -0,0 +1,41 @@
//// [protectedClassPropertyAccessibleWithinSubclass3.ts]
class Base {
protected x: string;
method() {
this.x; // OK, accessed within their declaring class
}
}
class Derived extends Base {
method1() {
this.x; // OK, accessed within a subclass of the declaring class
super.x; // Error, x is not public
}
}
//// [protectedClassPropertyAccessibleWithinSubclass3.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.method = function () {
this.x; // OK, accessed within their declaring class
};
return Base;
})();
var Derived = (function (_super) {
__extends(Derived, _super);
function Derived() {
_super.apply(this, arguments);
}
Derived.prototype.method1 = function () {
this.x; // OK, accessed within a subclass of the declaring class
_super.prototype.x; // Error, x is not public
};
return Derived;
})(Base);

View file

@ -0,0 +1,67 @@
tests/cases/conformance/classes/members/accessibility/protectedStaticClassPropertyAccessibleWithinSubclass.ts(7,9): error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.
tests/cases/conformance/classes/members/accessibility/protectedStaticClassPropertyAccessibleWithinSubclass.ts(16,9): error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.
tests/cases/conformance/classes/members/accessibility/protectedStaticClassPropertyAccessibleWithinSubclass.ts(25,9): error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.
tests/cases/conformance/classes/members/accessibility/protectedStaticClassPropertyAccessibleWithinSubclass.ts(40,1): error TS2445: Property 'x' is protected and only accessible within class 'Base' and its subclasses.
tests/cases/conformance/classes/members/accessibility/protectedStaticClassPropertyAccessibleWithinSubclass.ts(41,1): error TS2445: Property 'x' is protected and only accessible within class 'Base' and its subclasses.
tests/cases/conformance/classes/members/accessibility/protectedStaticClassPropertyAccessibleWithinSubclass.ts(42,1): error TS2445: Property 'x' is protected and only accessible within class 'Base' and its subclasses.
tests/cases/conformance/classes/members/accessibility/protectedStaticClassPropertyAccessibleWithinSubclass.ts(43,1): error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.
==== tests/cases/conformance/classes/members/accessibility/protectedStaticClassPropertyAccessibleWithinSubclass.ts (7 errors) ====
class Base {
protected static x: string;
static staticMethod() {
Base.x; // OK, accessed within their declaring class
Derived1.x; // OK, accessed within their declaring class
Derived2.x; // OK, accessed within their declaring class
Derived3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
~~~~~~~~~~
!!! error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.
}
}
class Derived1 extends Base {
static staticMethod1() {
Base.x; // OK, accessed within a class derived from their declaring class
Derived1.x; // OK, accessed within a class derived from their declaring class
Derived2.x; // OK, accessed within a class derived from their declaring class
Derived3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
~~~~~~~~~~
!!! error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.
}
}
class Derived2 extends Base {
static staticMethod2() {
Base.x; // OK, accessed within a class derived from their declaring class
Derived1.x; // OK, accessed within a class derived from their declaring class
Derived2.x; // OK, accessed within a class derived from their declaring class
Derived3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
~~~~~~~~~~
!!! error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.
}
}
class Derived3 extends Derived1 {
protected static x: string;
static staticMethod3() {
Base.x; // OK, accessed within a class derived from their declaring class
Derived1.x; // OK, accessed within a class derived from their declaring class
Derived2.x; // OK, accessed within a class derived from their declaring class
Derived3.x; // OK, accessed within their declaring class
}
}
Base.x; // Error, neither within their declaring class nor classes derived from their declaring class
~~~~~~
!!! error TS2445: Property 'x' is protected and only accessible within class 'Base' and its subclasses.
Derived1.x; // Error, neither within their declaring class nor classes derived from their declaring class
~~~~~~~~~~
!!! error TS2445: Property 'x' is protected and only accessible within class 'Base' and its subclasses.
Derived2.x; // Error, neither within their declaring class nor classes derived from their declaring class
~~~~~~~~~~
!!! error TS2445: Property 'x' is protected and only accessible within class 'Base' and its subclasses.
Derived3.x; // Error, neither within their declaring class nor classes derived from their declaring class
~~~~~~~~~~
!!! error TS2445: Property 'x' is protected and only accessible within class 'Derived3' and its subclasses.

View file

@ -0,0 +1,106 @@
//// [protectedStaticClassPropertyAccessibleWithinSubclass.ts]
class Base {
protected static x: string;
static staticMethod() {
Base.x; // OK, accessed within their declaring class
Derived1.x; // OK, accessed within their declaring class
Derived2.x; // OK, accessed within their declaring class
Derived3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
}
}
class Derived1 extends Base {
static staticMethod1() {
Base.x; // OK, accessed within a class derived from their declaring class
Derived1.x; // OK, accessed within a class derived from their declaring class
Derived2.x; // OK, accessed within a class derived from their declaring class
Derived3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
}
}
class Derived2 extends Base {
static staticMethod2() {
Base.x; // OK, accessed within a class derived from their declaring class
Derived1.x; // OK, accessed within a class derived from their declaring class
Derived2.x; // OK, accessed within a class derived from their declaring class
Derived3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
}
}
class Derived3 extends Derived1 {
protected static x: string;
static staticMethod3() {
Base.x; // OK, accessed within a class derived from their declaring class
Derived1.x; // OK, accessed within a class derived from their declaring class
Derived2.x; // OK, accessed within a class derived from their declaring class
Derived3.x; // OK, accessed within their declaring class
}
}
Base.x; // Error, neither within their declaring class nor classes derived from their declaring class
Derived1.x; // Error, neither within their declaring class nor classes derived from their declaring class
Derived2.x; // Error, neither within their declaring class nor classes derived from their declaring class
Derived3.x; // Error, neither within their declaring class nor classes derived from their declaring class
//// [protectedStaticClassPropertyAccessibleWithinSubclass.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.staticMethod = function () {
Base.x; // OK, accessed within their declaring class
Derived1.x; // OK, accessed within their declaring class
Derived2.x; // OK, accessed within their declaring class
Derived3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
};
return Base;
})();
var Derived1 = (function (_super) {
__extends(Derived1, _super);
function Derived1() {
_super.apply(this, arguments);
}
Derived1.staticMethod1 = function () {
Base.x; // OK, accessed within a class derived from their declaring class
Derived1.x; // OK, accessed within a class derived from their declaring class
Derived2.x; // OK, accessed within a class derived from their declaring class
Derived3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
};
return Derived1;
})(Base);
var Derived2 = (function (_super) {
__extends(Derived2, _super);
function Derived2() {
_super.apply(this, arguments);
}
Derived2.staticMethod2 = function () {
Base.x; // OK, accessed within a class derived from their declaring class
Derived1.x; // OK, accessed within a class derived from their declaring class
Derived2.x; // OK, accessed within a class derived from their declaring class
Derived3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
};
return Derived2;
})(Base);
var Derived3 = (function (_super) {
__extends(Derived3, _super);
function Derived3() {
_super.apply(this, arguments);
}
Derived3.staticMethod3 = function () {
Base.x; // OK, accessed within a class derived from their declaring class
Derived1.x; // OK, accessed within a class derived from their declaring class
Derived2.x; // OK, accessed within a class derived from their declaring class
Derived3.x; // OK, accessed within their declaring class
};
return Derived3;
})(Derived1);
Base.x; // Error, neither within their declaring class nor classes derived from their declaring class
Derived1.x; // Error, neither within their declaring class nor classes derived from their declaring class
Derived2.x; // Error, neither within their declaring class nor classes derived from their declaring class
Derived3.x; // Error, neither within their declaring class nor classes derived from their declaring class

View file

@ -0,0 +1,30 @@
tests/cases/conformance/classes/members/accessibility/protectedStaticClassPropertyAccessibleWithinSubclass2.ts(11,15): error TS2340: Only public and protected methods of the base class are accessible via the 'super' keyword
tests/cases/conformance/classes/members/accessibility/protectedStaticClassPropertyAccessibleWithinSubclass2.ts(19,15): error TS2340: Only public and protected methods of the base class are accessible via the 'super' keyword
==== tests/cases/conformance/classes/members/accessibility/protectedStaticClassPropertyAccessibleWithinSubclass2.ts (2 errors) ====
class Base {
protected static x: string;
static staticMethod() {
this.x; // OK, accessed within their declaring class
}
}
class Derived1 extends Base {
static staticMethod1() {
this.x; // OK, accessed within a class derived from their declaring class
super.x; // Error, x is not public
~
!!! error TS2340: Only public and protected methods of the base class are accessible via the 'super' keyword
}
}
class Derived2 extends Derived1 {
protected static x: string;
static staticMethod3() {
this.x; // OK, accessed within a class derived from their declaring class
super.x; // Error, x is not public
~
!!! error TS2340: Only public and protected methods of the base class are accessible via the 'super' keyword
}
}

View file

@ -0,0 +1,60 @@
//// [protectedStaticClassPropertyAccessibleWithinSubclass2.ts]
class Base {
protected static x: string;
static staticMethod() {
this.x; // OK, accessed within their declaring class
}
}
class Derived1 extends Base {
static staticMethod1() {
this.x; // OK, accessed within a class derived from their declaring class
super.x; // Error, x is not public
}
}
class Derived2 extends Derived1 {
protected static x: string;
static staticMethod3() {
this.x; // OK, accessed within a class derived from their declaring class
super.x; // Error, x is not public
}
}
//// [protectedStaticClassPropertyAccessibleWithinSubclass2.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.staticMethod = function () {
this.x; // OK, accessed within their declaring class
};
return Base;
})();
var Derived1 = (function (_super) {
__extends(Derived1, _super);
function Derived1() {
_super.apply(this, arguments);
}
Derived1.staticMethod1 = function () {
this.x; // OK, accessed within a class derived from their declaring class
_super.x; // Error, x is not public
};
return Derived1;
})(Base);
var Derived2 = (function (_super) {
__extends(Derived2, _super);
function Derived2() {
_super.apply(this, arguments);
}
Derived2.staticMethod3 = function () {
this.x; // OK, accessed within a class derived from their declaring class
_super.x; // Error, x is not public
};
return Derived2;
})(Derived1);

View file

@ -0,0 +1,17 @@
tests/cases/conformance/classes/members/accessibility/protectedStaticNotAccessibleInClodule.ts(10,20): error TS2445: Property 'bar' is protected and only accessible within class 'C' and its subclasses.
==== tests/cases/conformance/classes/members/accessibility/protectedStaticNotAccessibleInClodule.ts (1 errors) ====
// Any attempt to access a private property member outside the class body that contains its declaration results in a compile-time error.
class C {
public static foo: string;
protected static bar: string;
}
module C {
export var f = C.foo; // OK
export var b = C.bar; // error
~~~~~
!!! error TS2445: Property 'bar' is protected and only accessible within class 'C' and its subclasses.
}

View file

@ -0,0 +1,25 @@
//// [protectedStaticNotAccessibleInClodule.ts]
// Any attempt to access a private property member outside the class body that contains its declaration results in a compile-time error.
class C {
public static foo: string;
protected static bar: string;
}
module C {
export var f = C.foo; // OK
export var b = C.bar; // error
}
//// [protectedStaticNotAccessibleInClodule.js]
// Any attempt to access a private property member outside the class body that contains its declaration results in a compile-time error.
var C = (function () {
function C() {
}
return C;
})();
var C;
(function (C) {
C.f = C.foo; // OK
C.b = C.bar; // error
})(C || (C = {}));

View file

@ -0,0 +1,278 @@
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 {
/// <summary>
/// Test various of variables. Including nullable,key world as variable,special format
/// </summary>
/// <returns></returns>
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 = <fs.File>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;
}
/// <summary>
/// Test different statements. Including if-else,swith,foreach,(un)checked,lock,using,try-catch-finally
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
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;
}
/// <summary>
/// Test types in ts language. Including class,struct,interface,delegate,anonymous type
/// </summary>
/// <returns></returns>
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;
}
///// <summary>
///// Test different operators
///// </summary>
///// <returns></returns>
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 += <number>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();

View file

@ -0,0 +1,52 @@
// @declaration: true
// @target: es5
// Class with protected members
class C1 {
protected x: number;
protected f() {
return this.x;
}
protected set accessor(a: number) { }
protected get accessor() { return 0; }
protected static sx: number;
protected static sf() {
return this.sx;
}
protected static set staticSetter(a: number) { }
protected static get staticGetter() { return 0; }
}
// Derived class overriding protected members
class C2 extends C1 {
protected f() {
return super.f() + this.x;
}
protected static sf() {
return super.sf() + this.sx;
}
}
// Derived class making protected members public
class C3 extends C2 {
x: number;
static sx: number;
f() {
return super.f();
}
static sf() {
return super.sf();
}
static get staticGetter() { return 1; }
}
// Protected properties in constructors
class C4 {
constructor(protected a: number, protected b) { }
}

View file

@ -0,0 +1,25 @@
class C1 {
constructor(public x: number) { }
}
var c1: C1;
c1.x // OK
class C2 {
constructor(private p: number) { }
}
var c2: C2;
c2.p // private, error
class C3 {
constructor(protected p: number) { }
}
var c3: C3;
c3.p // protected, error
class Derived extends C3 {
constructor(p: number) {
super(p);
this.p; // OK
}
}

View file

@ -0,0 +1,25 @@
class C1 {
constructor(public x?: number) { }
}
var c1: C1;
c1.x // OK
class C2 {
constructor(private p?: number) { }
}
var c2: C2;
c2.p // private, error
class C3 {
constructor(protected p?: number) { }
}
var c3: C3;
c3.p // protected, error
class Derived extends C3 {
constructor(p: number) {
super(p);
this.p; // OK
}
}

View file

@ -0,0 +1,13 @@
class Base {
constructor(protected p: number) { }
}
class Derived extends Base {
constructor(public p: number) {
super(p);
this.p; // OK
}
}
var d: Derived;
d.p; // public, OK

View file

@ -0,0 +1,94 @@
class Base {
protected x: string;
method() {
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // OK, accessed within their declaring class
d1.x; // OK, accessed within their declaring class
d2.x; // OK, accessed within their declaring class
d3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
d4.x; // OK, accessed within their declaring class
}
}
class Derived1 extends Base {
method1() {
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // Error, isn't accessed through an instance of the enclosing class
d1.x; // OK, accessed within a class derived from their declaring class, and through an instance of the enclosing class
d2.x; // Error, isn't accessed through an instance of the enclosing class
d3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
d4.x; // Error, isn't accessed through an instance of the enclosing class
}
}
class Derived2 extends Base {
method2() {
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // Error, isn't accessed through an instance of the enclosing class
d1.x; // Error, isn't accessed through an instance of the enclosing class
d2.x; // OK, accessed within a class derived from their declaring class, and through an instance of the enclosing class
d3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
d4.x; // OK, accessed within a class derived from their declaring class, and through an instance of the enclosing class or one of its subclasses
}
}
class Derived3 extends Derived1 {
protected x: string;
method3() {
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // Error, isn't accessed through an instance of the enclosing class
d1.x; // Error, isn't accessed through an instance of the enclosing class
d2.x; // Error, isn't accessed through an instance of the enclosing class
d3.x; // OK, accessed within their declaring class
d4.x; // Error, isn't accessed through an instance of the enclosing class
}
}
class Derived4 extends Derived2 {
method4() {
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // Error, isn't accessed through an instance of the enclosing class
d1.x; // Error, isn't accessed through an instance of the enclosing class
d2.x; // Error, isn't accessed through an instance of the enclosing class
d3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
d4.x; // OK, accessed within a class derived from their declaring class, and through an instance of the enclosing class
}
}
var b: Base;
var d1: Derived1;
var d2: Derived2;
var d3: Derived3;
var d4: Derived4;
b.x; // Error, neither within their declaring class nor classes derived from their declaring class
d1.x; // Error, neither within their declaring class nor classes derived from their declaring class
d2.x; // Error, neither within their declaring class nor classes derived from their declaring class
d3.x; // Error, neither within their declaring class nor classes derived from their declaring class
d4.x; // Error, neither within their declaring class nor classes derived from their declaring class

View file

@ -0,0 +1,13 @@
class Base {
protected x: string;
method() {
this.x; // OK, accessed within their declaring class
}
}
class Derived extends Base {
method1() {
this.x; // OK, accessed within a subclass of the declaring class
super.x; // Error, x is not public
}
}

View file

@ -0,0 +1,43 @@
class Base {
protected static x: string;
static staticMethod() {
Base.x; // OK, accessed within their declaring class
Derived1.x; // OK, accessed within their declaring class
Derived2.x; // OK, accessed within their declaring class
Derived3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
}
}
class Derived1 extends Base {
static staticMethod1() {
Base.x; // OK, accessed within a class derived from their declaring class
Derived1.x; // OK, accessed within a class derived from their declaring class
Derived2.x; // OK, accessed within a class derived from their declaring class
Derived3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
}
}
class Derived2 extends Base {
static staticMethod2() {
Base.x; // OK, accessed within a class derived from their declaring class
Derived1.x; // OK, accessed within a class derived from their declaring class
Derived2.x; // OK, accessed within a class derived from their declaring class
Derived3.x; // Error, redefined in a subclass, can only be accessed in the declaring class or one of its subclasses
}
}
class Derived3 extends Derived1 {
protected static x: string;
static staticMethod3() {
Base.x; // OK, accessed within a class derived from their declaring class
Derived1.x; // OK, accessed within a class derived from their declaring class
Derived2.x; // OK, accessed within a class derived from their declaring class
Derived3.x; // OK, accessed within their declaring class
}
}
Base.x; // Error, neither within their declaring class nor classes derived from their declaring class
Derived1.x; // Error, neither within their declaring class nor classes derived from their declaring class
Derived2.x; // Error, neither within their declaring class nor classes derived from their declaring class
Derived3.x; // Error, neither within their declaring class nor classes derived from their declaring class

View file

@ -0,0 +1,21 @@
class Base {
protected static x: string;
static staticMethod() {
this.x; // OK, accessed within their declaring class
}
}
class Derived1 extends Base {
static staticMethod1() {
this.x; // OK, accessed within a class derived from their declaring class
super.x; // Error, x is not public
}
}
class Derived2 extends Derived1 {
protected static x: string;
static staticMethod3() {
this.x; // OK, accessed within a class derived from their declaring class
super.x; // Error, x is not public
}
}

View file

@ -0,0 +1,11 @@
// Any attempt to access a private property member outside the class body that contains its declaration results in a compile-time error.
class C {
public static foo: string;
protected static bar: string;
}
module C {
export var f = C.foo; // OK
export var b = C.bar; // error
}

View file

@ -0,0 +1,36 @@
// @target: ES5
var x: { foo: string; }
var y: { foo: string; bar: string; }
class Base {
protected a: typeof x;
protected b(a: typeof x) { }
protected get c() { return x; }
protected set c(v: typeof x) { }
protected d: (a: typeof x) => void;
protected static r: typeof x;
protected static s(a: typeof x) { }
protected static get t() { return x; }
protected static set t(v: typeof x) { }
protected static u: (a: typeof x) => void;
constructor(a: typeof x) { }
}
class Derived extends Base {
protected a: typeof y;
protected b(a: typeof y) { }
protected get c() { return y; }
protected set c(v: typeof y) { }
protected d: (a: typeof y) => void;
protected static r: typeof y;
protected static s(a: typeof y) { }
protected static get t() { return y; }
protected static set t(a: typeof y) { }
protected static u: (a: typeof y) => void;
constructor(a: typeof y) { super(x) }
}

View file

@ -0,0 +1,63 @@
// @target: ES5
var x: { foo: string; }
var y: { foo: string; bar: string; }
class Base {
protected a: typeof x;
protected b(a: typeof x) { }
protected get c() { return x; }
protected set c(v: typeof x) { }
protected d: (a: typeof x) => void ;
protected static r: typeof x;
protected static s(a: typeof x) { }
protected static get t() { return x; }
protected static set t(v: typeof x) { }
protected static u: (a: typeof x) => void ;
constructor(a: typeof x) { }
}
// Increase visibility of all protected members to public
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(a); }
}
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];

View file

@ -0,0 +1,72 @@
// @target: ES5
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) {}
}
// Errors
// decrease visibility of all public members to protected
class Derived1 extends Base {
protected a: typeof x;
constructor(a: typeof x) { super(a); }
}
class Derived2 extends Base {
protected b(a: typeof x) { }
constructor(a: typeof x) { super(a); }
}
class Derived3 extends Base {
protected get c() { return x; }
constructor(a: typeof x) { super(a); }
}
class Derived4 extends Base {
protected set c(v: typeof x) { }
constructor(a: typeof x) { super(a); }
}
class Derived5 extends Base {
protected d: (a: typeof x) => void ;
constructor(a: typeof x) { super(a); }
}
class Derived6 extends Base {
protected static r: typeof x;
constructor(a: typeof x) { super(a); }
}
class Derived7 extends Base {
protected static s(a: typeof x) { }
constructor(a: typeof x) { super(a); }
}
class Derived8 extends Base {
protected static get t() { return x; }
constructor(a: typeof x) { super(a); }
}
class Derived9 extends Base {
protected static set t(v: typeof x) { }
constructor(a: typeof x) { super(a); }
}
class Derived10 extends Base {
protected static u: (a: typeof x) => void ;
constructor(a: typeof x) { super(a); }
}

View file

@ -0,0 +1,14 @@
var x: { foo: string; }
var y: { foo: string; bar: string; }
class Base {
protected a: typeof x;
}
class Derived1 extends Base {
public a: typeof x;
}
class Derived2 extends Derived1 {
protected a: typeof x; // Error, parent was public
}

View file

@ -0,0 +1,20 @@
// subclassing is not transitive when you can remove required parameters and add optional parameters on protected members
class C {
protected foo(x: number) { }
}
class D extends C {
protected foo() { } // ok to drop parameters
}
class E extends D {
public foo(x?: string) { } // ok to add optional parameters
}
var c: C;
var d: D;
var e: E;
c = e;
var r = c.foo(1);
var r2 = e.foo('');

View file

@ -0,0 +1,22 @@
// @target: ES5
class Base {
protected x: string;
protected fn(): string {
return '';
}
protected get a() { return 1; }
protected 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) { }
}

View file

@ -0,0 +1,22 @@
// @target: ES5
class Base {
protected static x: string;
protected static fn(): string {
return '';
}
protected static get a() { return 1; }
protected static set a(v) { }
}
// 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) { }
}

View file

@ -0,0 +1,45 @@
// @target: ES5
// 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) { }
}

View file

@ -0,0 +1,33 @@
// @target: ES5
class C {
get x() {
return 1;
}
private set x(v) {
}
}
class D {
protected get x() {
return 1;
}
private set x(v) {
}
}
class E {
protected set x(v) {
}
get x() {
return 1;
}
}
class F {
protected static set x(v) {
}
static get x() {
return 1;
}
}

View file

@ -12,10 +12,19 @@ class C {
public static foo(x: number, y: string); // error
private static foo(x: any, y?: any) { }
protected baz(x: string); // error
protected baz(x: number, y: string); // error
private baz(x: any, y?: any) { }
private static bar(x: 'hi');
public static bar(x: string); // error
private static bar(x: number, y: string);
private static bar(x: any, y?: any) { }
protected static baz(x: 'hi');
public static baz(x: string); // error
protected static baz(x: number, y: string);
protected static baz(x: any, y?: any) { }
}
class D<T> {
@ -28,6 +37,10 @@ class D<T> {
private bar(x: T, y: T);
private bar(x: any, y?: any) { }
private baz(x: string);
protected baz(x: number, y: string); // error
private baz(x: any, y?: any) { }
private static foo(x: number);
public static foo(x: number, y: string); // error
private static foo(x: any, y?: any) { }
@ -36,6 +49,10 @@ class D<T> {
public static bar(x: string); // error
private static bar(x: number, y: string);
private static bar(x: any, y?: any) { }
public static baz(x: string); // error
protected static baz(x: number, y: string);
protected static baz(x: any, y?: any) { }
}
var c: C;

View file

@ -0,0 +1,6 @@
// Errors
interface Foo {
public a: any;
private b: any;
protected c: any;
}

View file

@ -0,0 +1,27 @@
// accessing any protected outside the class is an error
class C {
protected x;
protected a = '';
protected b: string = '';
protected c() { return '' }
protected d = () => '';
protected static e;
protected static f() { return '' }
protected static g = () => '';
}
class D extends C {
method() {
// No errors
var d = new D();
var r1: string = d.x;
var r2: string = d.a;
var r3: string = d.b;
var r4: string = d.c();
var r5: string = d.d();
var r6: string = C.e;
var r7: string = C.f();
var r8: string = C.g();
}
}

View file

@ -38,6 +38,6 @@
////}
test.ranges().forEach((range) => {
verify.matchingBracePositionInCurrentFile(range.start, range.end - 1);
verify.matchingBracePositionInCurrentFile(range.end - 1, range.start);
});
verify.matchingBracePositionInCurrentFile(range.start, range.end - 1);
verify.matchingBracePositionInCurrentFile(range.end - 1, range.start);
});

View file

@ -0,0 +1,9 @@
////function f[|<T>|][|(x: T)|][|{
//// return x;
////}|]
// If there is an adjacent opening and closing brace,
// then only the opening brace should get highlighted.
test.ranges().forEach(range => {
verify.matchingBracePositionInCurrentFile(range.start, range.end - 1);
});

View file

@ -36,7 +36,7 @@ describe('Colorization', function () {
}
var finalEndOfLineState = classResult[classResult.length - 1];
assert.equal(position, code.length, "Expected accumilative length of all entries to match the length of the source. expected: " + code.length + ", but got: " + position);
assert.equal(position, code.length, "Expected cumulative length of all entries to match the length of the source. expected: " + code.length + ", but got: " + position);
return {
tuples: tuples,
@ -84,8 +84,8 @@ describe('Colorization', function () {
var actualEntry = getEntryAtPosistion(result, actualEntryPosition);
assert(actualEntry, "Could not find classification entry for '" + expectedEntry.value + "' at position: " + actualEntryPosition);
assert.equal(actualEntry.length, expectedEntry.value.length, "Classification class does not match expected.");
assert.equal(actualEntry.class, expectedEntry.class, "Classification class does not match expected.");
assert.equal(actualEntry.class, expectedEntry.class, "Classification class does not match expected. Expected: " + ts.TokenClass[expectedEntry.class] + ", Actual: " + ts.TokenClass[actualEntry.class]);
assert.equal(actualEntry.length, expectedEntry.value.length, "Classification length does not match expected. Expected: " + ts.TokenClass[expectedEntry.value.length] + ", Actual: " + ts.TokenClass[actualEntry.length]);
}
}
}
@ -105,7 +105,7 @@ describe('Colorization', function () {
punctuation(";"));
});
it("classifies correctelly a comment after a divide operator", function () {
it("correctly classifies a comment after a divide operator", function () {
test("1 / 2 // comment",
ts.EndOfLineState.Start,
numberLiteral("1"),
@ -115,7 +115,7 @@ describe('Colorization', function () {
comment("// comment"));
});
it("classifies correctelly a literal after a divide operator", function () {
it("correctly classifies a literal after a divide operator", function () {
test("1 / 2, 3 / 4",
ts.EndOfLineState.Start,
numberLiteral("1"),
@ -127,48 +127,76 @@ describe('Colorization', function () {
operator(","));
});
it("classifies correctelly an unterminated multi-line string", function () {
it("correctly classifies an unterminated multi-line string", function () {
test("'line1\\",
ts.EndOfLineState.Start,
stringLiteral("'line1\\"),
finalEndOfLineState(ts.EndOfLineState.InSingleQuoteStringLiteral));
});
it("classifies correctelly the second line of an unterminated multi-line string", function () {
it("correctly classifies the second line of an unterminated multi-line string", function () {
test("\\",
ts.EndOfLineState.InDoubleQuoteStringLiteral,
stringLiteral("\\"),
finalEndOfLineState(ts.EndOfLineState.InDoubleQuoteStringLiteral));
});
it("classifies correctelly the last line of a multi-line string", function () {
it("correctly classifies the last line of a multi-line string", function () {
test("'",
ts.EndOfLineState.InSingleQuoteStringLiteral,
stringLiteral("'"),
finalEndOfLineState(ts.EndOfLineState.Start));
});
it("classifies correctelly an unterminated multiline comment", function () {
it("correctly classifies an unterminated multiline comment", function () {
test("/*",
ts.EndOfLineState.Start,
comment("/*"),
finalEndOfLineState(ts.EndOfLineState.InMultiLineCommentTrivia));
});
it("classifies correctelly an unterminated multiline comment with trailing space", function () {
it("correctly classifies the termination of a multiline comment", function () {
test(" */ ",
ts.EndOfLineState.InMultiLineCommentTrivia,
comment(" */"),
finalEndOfLineState(ts.EndOfLineState.Start));
});
it("correctly classifies the continuation of a multiline comment", function () {
test("LOREM IPSUM DOLOR ",
ts.EndOfLineState.InMultiLineCommentTrivia,
comment("LOREM IPSUM DOLOR "),
finalEndOfLineState(ts.EndOfLineState.InMultiLineCommentTrivia));
});
it("correctly classifies an unterminated multiline comment on a line ending in '/*/'", function () {
test(" /*/",
ts.EndOfLineState.Start,
comment("/*/"),
finalEndOfLineState(ts.EndOfLineState.InMultiLineCommentTrivia));
});
it("correctly classifies an unterminated multiline comment with trailing space", function () {
test("/* ",
ts.EndOfLineState.Start,
comment("/* "),
finalEndOfLineState(ts.EndOfLineState.InMultiLineCommentTrivia));
});
it("classifies correctelly a keyword after a dot", function () {
it("correctly classifies a keyword after a dot", function () {
test("a.var",
ts.EndOfLineState.Start,
identifier("var"));
});
it("classifies keyword after a dot on previous line", function () {
it("classifies a property access with whitespace around the dot", function () {
test(" x .\tfoo ()",
ts.EndOfLineState.Start,
identifier("x"),
identifier("foo"));
});
it("classifies a keyword after a dot on previous line", function () {
test("var",
ts.EndOfLineState.Start,
keyword("var"),