Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support classExpressions in DTE #101

Merged
merged 13 commits into from
Oct 20, 2023
49 changes: 24 additions & 25 deletions external-declarations/fixed-tests.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
9008, // Declaration_emit_for_this_file_requires_adding_a_type_reference_directive_Add_a_type_reference_directive_to_0_to_unblock_declaration_emit
9009, // Assigning_properties_to_functions_without_declaring_them_is_not_supported_with_isolatedDeclarations_Add_an_explicit_declaration_for_the_properties_assigned_to_this_function
9010, // Reference directives are not supported in isolated declaration mode.
],
9011 // Heritage_clause_for_Class_Expressions_is_not_allowed_with_isolatedDeclarations
],
"with-unreliable-errors": [
2784, // 'get' and 'set' accessors cannot declare 'this' parameters.
1162, // An object member cannot be declared optional.
1162 // An object member cannot be declared optional.
]
},
"test-categories": {
Expand All @@ -26,9 +27,9 @@
"enumErrors",
"enumExportMergingES6",
"verbatimModuleSyntaxConstEnumUsage",
"templateLiteralTypes4",
"templateLiteralTypes4"
],
"code-fixer-issues" : [
"code-fixer-issues": [
"arrayFakeFlatNoCrashInferenceDeclarations",
"commonJsImportClassExpression",
"constEnumNamespaceReferenceCausesNoImport2",
Expand All @@ -50,20 +51,20 @@
"reexportClassDefinition",
"parserEqualsGreaterThanAfterFunction1",
"parserSkippedTokens16",
"declarationFiles",
"declarationFiles"
],
"not-fixed-with-unreliable-errors": [
// Language service crash on computing diagnostic (call stack size exceeded)
"binderBinaryExpressionStress",
// Bad syntax beyond recovery
// Bad syntax beyond recovery
"destructuringParameterDeclaration6",
"thisTypeInFunctionsNegative",
"thisTypeInFunctionsNegative"
],
"with-unreliable-errors": [
"thisTypeErrors", // Assertion to this in static context produces this in DTE and any in TSC
"parseInvalidNonNullableTypes", // Prefix ! operator
"thisInConstructorParameter2", // this type used in invalid context
"parseInvalidNullableTypes", // Prefix ? operator
"thisInConstructorParameter2", // this type used in invalid context
"parseInvalidNullableTypes", // Prefix ? operator
"ArrowFunction1", // Missing type annotation syntax error
"parserX_ArrowFunction1", // Missing type annotation syntax error
"typeParameterDirectlyConstrainedToItself", // Circular type constraints makes emit unreliable
Expand All @@ -80,10 +81,10 @@
"duplicatePropertiesInTypeAssertions02",
"parserCastVersusArrowFunction1",
"invalidMultipleVariableDeclarations",
"validMultipleVariableDeclarations",
"validMultipleVariableDeclarations",
"augmentedTypesVar",
"objectLiteralErrors",
"duplicateObjectLiteralProperty_computedName2",
"duplicateObjectLiteralProperty_computedName2",
"arrowFunctionExpressions",
"castingTuple", // contains both duplicate variables and print differences.
// Identifier expected.
Expand Down Expand Up @@ -117,18 +118,18 @@
"decoratorsOnComputedProperties",
"indexSignatureMustHaveTypeAnnotation",
"intTypeCheck",
// Invalid escape sequences
// Invalid escape sequences
"invalidTaggedTemplateEscapeSequences",
"objectTypeWithStringNamedPropertyOfIllegalCharacters",
"noUsedBeforeDefinedErrorInTypeContext", // Variable used before definition in type context
"accessorBodyInTypeContext", //An implementation cannot be declared in ambient contexts.
"accessorBodyInTypeContext", // An implementation cannot be declared in ambient contexts.
"commonJsExportTypeDeclarationError", // Duplicate name, TS resolves to the type alias symbol, DTE resolves to import. Neither is wrong, code is wrong.
"parseAssertEntriesError", // Syntactic invalid import assertions.
"decoratorMetadataWithImportDeclarationNameCollision7", // Import does not have the accessed member. TS removes the import as unused. A DTE will keep it as it is syntactically used.
"classExtendingNonConstructor", // Not reported as isolated declaration error, but the extends clause is invalid.
"nodeModulesImportTypeModeDeclarationEmitErrors1", // Invalid import asserts
"wellKnownSymbolExpando", // Expando function with well known symbols error in TS, but generate the expando function namepsace, DTE does not.
"genericsWithDuplicateTypeParameters1", // Duplicate type parameters
"wellKnownSymbolExpando", // Expando function with well known symbols error in TS, but generate the expando function namepsace, DTE does not.
"genericsWithDuplicateTypeParameters1" // Duplicate type parameters
],
"with-isolated-declaration-errors/9008": [
"declarationEmitHasTypesRefOnNamespaceUse",
Expand All @@ -142,13 +143,12 @@
// Will not actually error because of https://github.com/microsoft/TypeScript/issues/55636
// In isolated declarations we walk the type in the return as if it was hand written in the variable
// This triggers the difference in behavior described in the issue.
"jsxNamespaceGlobalReexport",

"jsxNamespaceGlobalReexport"
],
"with-isolated-declaration-errors": [
"typeFromPropertyAssignment38", // Nested expando functions. Can in principle be detected, but are not yet implemented
"contextualReturnTypeOfIIFE2", // Nested expando functions. Can in principle be detected, but are not yet implemented
// Computed property errors a DTE can't detect
// Computed property errors a DTE can't detect
"complicatedPrivacy",
"computedPropertyNames12_ES5",
"computedPropertyNames12_ES6",
Expand Down Expand Up @@ -216,15 +216,15 @@
"declarationEmitForModuleImportingModuleAugmentationRetainsImport" // Import augments and must be kept
],
"ts-bugs": [
// Type parameter renamed
// Reported as https://github.com/microsoft/TypeScript/issues/55653
// Type parameter renamed
// Reported as https://github.com/microsoft/TypeScript/issues/55653
"objectTypesIdentityWithGenericCallSignaturesDifferingTypeParameterCounts",
"objectTypesIdentityWithGenericCallSignaturesDifferingTypeParameterNames",
"objectTypesIdentityWithGenericConstructSignaturesDifferingTypeParameterCounts",
"typeAssertionToGenericFunctionType",
// Default type parameters is written in declarations
"conditionalTypesSimplifyWhenTrivial",
// https://github.com/microsoft/TypeScript/issues/55571
"conditionalTypesSimplifyWhenTrivial",
// https://github.com/microsoft/TypeScript/issues/55571
"reExportAliasMakesInstantiated"
],
// Needs TS Fix
Expand Down Expand Up @@ -306,8 +306,7 @@
"declarationEmitPropertyNumericStringKey",
"templateLiteralsSourceMap", // template literal is evaluated in constant value.
"nodeModulesImportTypeModeDeclarationEmit1", // resolution-mode in assert from type assertion is preserved
"literalTypesAndTypeAssertions", // (0 | 1) written in code is preserved by dte
],
"literalTypesAndTypeAssertions" // (0 | 1) written in code is preserved by dte
]
}
}

21 changes: 10 additions & 11 deletions external-declarations/original-tests.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,18 @@
"computedPropertiesNarrowed",
// error on used to be indexer, now it is a computed property
"propertyAssignment",
"invalidTaggedTemplateEscapeSequences", // Invalid escape sequences
"invalidTaggedTemplateEscapeSequences", // Invalid escape sequences
// duplicate field/accessor
"symbolDeclarationEmit12"
],
"ts-bugs": [
// https://github.com/microsoft/TypeScript/issues/55571
"reExportAliasMakesInstantiated"
],
// https://github.com/microsoft/TypeScript/issues/55571
"reExportAliasMakesInstantiated"
],
// Just Printing differences
"print-differences": [
"parseBigInt", // number literals are normalized by ts
"templateLiteralsSourceMap", // template literal is evaluated in constant value.
"parseBigInt", // number literals are normalized by ts
"templateLiteralsSourceMap" // template literal is evaluated in constant value.
],
"enums-issues": [
// External eval
Expand All @@ -60,12 +60,12 @@
"verbatimModuleSyntaxConstEnumUsage",
"templateLiteralTypes4",
"enumConstantMembers",
// merge
// merge
"mergedEnumDeclarationCodeGen",
"enumExportMergingES6",
"mergedDeclarations2",
"mergedDeclarations2"
],
// Some 9007 errors will result in differences. This is fine.
// Some 9007 errors will result in differences. This is fine.
"with-isolated-declaration-errors/9007": [
// computed property differences
"complicatedPrivacy",
Expand All @@ -74,8 +74,7 @@
"overloadsWithComputedNames",
"typeUsedAsTypeLiteralIndex", // computed property errors but in type aliases
"forwardRefInEnum", // Circular enums result in different values
"enumErrors",
"enumErrors"
]
}
}

60 changes: 30 additions & 30 deletions external-declarations/package.json
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
{
"name": "external-declarations",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "node ../built/local/tsc.js -p ./src",
"watch": "node ../built/local/tsc.js -w -p ./src",
"run-tests-parallel": "node ./build/test-runner/parallel-run.js --rootPaths=../tests/cases --libPath=../tests/lib --type=all --shardCount=8 --forceIsolatedDeclarations --outputPath=./tsc-tests/$original --configFile=./original-tests.jsonc",
"run-tests": "node ./build/test-runner/test-runner-main.js --type=all --rootPaths=../tests/cases --outputPath=./tsc-tests/$original --configFile=./original-tests.jsonc",
"transform-tests-parallel": "node ./build/code-mod/tsc-test-fixer/run-test-updater-parallel.js --rootPaths=../tests/cases --shardCount=8",
"transform-tests": "node ./build/code-mod/tsc-test-fixer/run-test-updater.js --rootPaths=../tests/cases",
"run-transformed-tests-parallel": "node ./build/test-runner/parallel-run.js --rootPaths=./tsc-tests/updated-tests --libPath=../tests/lib --type=all --shardCount=8 --outputPath=./tsc-tests/$transformed --configFile=./fixed-tests.jsonc",
"run-transformed-tests": "node ./build/test-runner/test-runner-main.js --type=all --rootPaths=./tsc-tests/updated-tests --libPath=../tests/lib --outputPath=./tsc-tests/$transformed --configFile=./fixed-tests.jsonc",
"fixer-tests": "node ./build/code-mod/fixer-test.js --rootPaths=./fixer-test/source ",
"fixer-tests-update": "node ./build/code-mod/fixer-test.js --rootPaths=./fixer-test/source --update "
},
"author": "",
"license": "ISC",
"dependencies": {
"json5": "^2.2.3",
"source-map-support": "^0.5.21",
"typescript": "../",
"@types/inquirer": "^8.2.6",
"@types/node": "^20.7.1",
"chalk": "^4.1.2",
"inquirer": "^8.2.6"
},
"devDependencies": {
"@types/node": "^18.11.18"
}
"name": "external-declarations",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "node ../built/local/tsc.js -p ./src",
"watch": "node ../built/local/tsc.js -w -p ./src",
"run-tests-parallel": "node ./build/test-runner/parallel-run.js --rootPaths=../tests/cases --libPath=../tests/lib --type=all --shardCount=8 --forceIsolatedDeclarations --outputPath=./tsc-tests/$original --configFile=./original-tests.jsonc",
"run-tests": "node ./build/test-runner/test-runner-main.js --type=all --rootPaths=../tests/cases --outputPath=./tsc-tests/$original --configFile=./original-tests.jsonc",
"transform-tests-parallel": "node ./build/code-mod/tsc-test-fixer/run-test-updater-parallel.js --rootPaths=../tests/cases --shardCount=8",
"transform-tests": "node ./build/code-mod/tsc-test-fixer/run-test-updater.js --rootPaths=../tests/cases",
"run-transformed-tests-parallel": "node ./build/test-runner/parallel-run.js --rootPaths=./tsc-tests/updated-tests --libPath=../tests/lib --type=all --shardCount=8 --outputPath=./tsc-tests/$transformed --configFile=./fixed-tests.jsonc",
"run-transformed-tests": "node ./build/test-runner/test-runner-main.js --type=all --rootPaths=./tsc-tests/updated-tests --libPath=../tests/lib --outputPath=./tsc-tests/$transformed --configFile=./fixed-tests.jsonc",
"fixer-tests": "node ./build/code-mod/fixer-test.js --rootPaths=./fixer-test/source ",
"fixer-tests-update": "node ./build/code-mod/fixer-test.js --rootPaths=./fixer-test/source --update "
},
"author": "",
"license": "ISC",
"dependencies": {
"json5": "^2.2.3",
"source-map-support": "^0.5.21",
"typescript": "../",
"@types/inquirer": "^8.2.6",
"@types/node": "^20.7.1",
"chalk": "^4.1.2",
"inquirer": "^8.2.6"
},
"devDependencies": {
"@types/node": "^18.11.18"
}
}
36 changes: 20 additions & 16 deletions external-declarations/src/code-mod/fixer-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import ts from "typescript";
import {
normalizePath,
} from "../compiler/path-utils";
import { TestCaseContent } from "../test-runner/tsc-infrastructure/test-file-parser";
import {
TestCaseContent,
} from "../test-runner/tsc-infrastructure/test-file-parser";
import {
loadTestCase,
} from "../test-runner/utils";
Expand Down Expand Up @@ -57,11 +59,11 @@ async function main() {

const updatedTestFileName = testFile.replace(rootPath, "./fixer-test/expected");
const result = await fixTestCase(caseData, {
target: ts.ScriptTarget.ES2019
target: ts.ScriptTarget.ES2019,
});
const resultFiles = !(result instanceof Error)? result : [{
unitName: caseData.testUnitData[0].name,
content: `
const resultFiles = !(result instanceof Error) ? result : [{
unitName: caseData.testUnitData[0].name,
content: `
================= CODE MOD ERROR ==============
${result.message}
${result.stack}
Expand All @@ -71,21 +73,24 @@ ${result.stack}
// ${caseData.code.split("\n").join("\n// ")}
`,
}];
await compareTestCase({
...caseData,
testUnitData: caseData.testUnitData.map(u => ({
...u,
content: resultFiles.find(o => o.unitName === u.name)?.content!,
})),
}, updatedTestFileName, !!parsedArgs.update);
await compareTestCase(
{
...caseData,
testUnitData: caseData.testUnitData.map(u => ({
...u,
content: resultFiles.find(o => o.unitName === u.name)?.content!,
})),
},
updatedTestFileName,
!!parsedArgs.update,
);
console.log(`Ran: ${count}`);
}
}

async function compareTestCase(testData: TestCaseContent & { BOM: string }, path: string, update: boolean) {
async function compareTestCase(testData: TestCaseContent & { BOM: string; }, path: string, update: boolean) {
const content = await testCaseToString(testData);
const original =
!fsSync.existsSync(path) ? undefined: await fs.readFile(path, "utf-8");
const original = !fsSync.existsSync(path) ? undefined : await fs.readFile(path, "utf-8");
if (content !== original) {
if (!update) {
throw new Error(`Expected \n${original}\n for file ${path} but seen \n${content}`);
Expand All @@ -96,5 +101,4 @@ async function compareTestCase(testData: TestCaseContent & { BOM: string }, path
}
}


main();
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ export const isolatedDeclarationsErrors = new Set([
9008,
9009,
9010,
9011,
]);
21 changes: 11 additions & 10 deletions external-declarations/src/code-mod/fixer/utils.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import chalk from "chalk";
import * as path from "path";
import { Diagnostic } from "typescript";

import {
Diagnostic,
} from "typescript";

export function printDiagnostics(diag: Diagnostic) {
const pos = getLineColumn(diag)
const pos = getLineColumn(diag);
const relative = path.relative(process.cwd(), diag.file?.fileName!);
console.log(`${chalk.blueBright(relative)}:${pos.line}:${pos.col} - ${diag.messageText}`);
}

export function getLineColumn(diag: Diagnostic) {
const text = diag.file?.text!
let line = 1;
const text = diag.file?.text!;
let line = 1;
let lineStart = text.lastIndexOf("\n", diag.start);
const col = lineStart === -1 ? diag.start!: diag.start!- lineStart;
while(lineStart > 0) {
line++
const col = lineStart === -1 ? diag.start! : diag.start! - lineStart;
while (lineStart > 0) {
line++;
lineStart = text.lastIndexOf("\n", lineStart - 1);
}
return { line, col }
}
return { line, col };
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
} from "../../utils/fs-utils";

export async function writeTestCase(testData: TestCaseContent & { BOM: string; }, path: string) {
await ensureDir(fsPath.dirname(path))
await ensureDir(fsPath.dirname(path));
await fs.writeFile(path, await testCaseToString(testData));
}
export async function testCaseToString(testData: TestCaseContent & { BOM: string; }) {
Expand Down
Loading