diff --git a/lib/tsc.js b/lib/tsc.js index fe1e5ed124a2420f8365395f2525e9306b31e1d8..7dc22917a63fca53d9c92a34a86c2c56456541d6 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -7322,6 +7322,51 @@ var ts; }; })(ts || (ts = {})); var ts; +(function (ts) { + var MemoryDotting; + (function (MemoryDotting) { + MemoryDotting.BINDE_SOURCE_FILE = 'binder(bindSourceFile: Bind)'; + MemoryDotting.CHECK_SOURCE_FILE = 'checker(checkSourceFile: Check)'; + MemoryDotting.EMIT_FILES = 'emitter(emitFiles: EmitEachOutputFile)'; + MemoryDotting.CREATE_SORUCE_FILE_PARSE = 'parser(createSourceFile: Parse)'; + MemoryDotting.BEFORE_PROGRAM = 'program(createProgram: beforeProgram)'; + MemoryDotting.TRANSFORM = 'transformer(transformNodes: Transform)'; + var memoryDottingCallback; + var memoryDottingStopCallback; + function recordStage(stage) { + if (memoryDottingCallback !== undefined) { + return memoryDottingCallback(stage); + } + return null; + } + MemoryDotting.recordStage = recordStage; + function stopRecordStage(recordInfo) { + if (memoryDottingStopCallback !== undefined && recordInfo !== null) { + memoryDottingStopCallback(recordInfo); + } + } + MemoryDotting.stopRecordStage = stopRecordStage; + function setMemoryDottingCallBack(recordCallback, stopCallback) { + if (recordCallback) { + memoryDottingCallback = recordCallback; + } + if (stopCallback) { + memoryDottingStopCallback = stopCallback; + } + } + MemoryDotting.setMemoryDottingCallBack = setMemoryDottingCallBack; + function clearCallBack() { + if (memoryDottingCallback !== undefined) { + memoryDottingCallback = undefined; + } + if (memoryDottingStopCallback !== undefined) { + memoryDottingStopCallback = undefined; + } + } + MemoryDotting.clearCallBack = clearCallBack; + })(MemoryDotting = ts.MemoryDotting || (ts.MemoryDotting = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var _a; function tokenIsIdentifierOrKeyword(token) { @@ -26391,6 +26436,7 @@ var ts; function createSourceFile(fileName, sourceText, languageVersionOrOptions, setParentNodes, scriptKind, options) { if (setParentNodes === void 0) { setParentNodes = false; } ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse", "createSourceFile", { path: fileName }, true); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.CREATE_SORUCE_FILE_PARSE); ts.performance.mark("beforeParse"); var result; sourceFileCompilerOptions = options !== null && options !== void 0 ? options : ts.defaultInitCompilerOptions; @@ -26408,6 +26454,7 @@ var ts; } ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Parse", "beforeParse", "afterParse"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; @@ -38462,7 +38509,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.annotationMagicNamePrefix = "#"; + ts.annotationMagicNamePrefix = "__$$ETS_ANNOTATION$$__"; function isInEtsFile(node) { var _a; return node !== undefined && ((_a = ts.getSourceFileOfNode(node)) === null || _a === void 0 ? void 0 : _a.scriptKind) === 8; @@ -38845,13 +38892,12 @@ var ts; return transformTypeExportImportAndConstEnumInTypeScript(context); } ts.getTypeExportImportAndConstEnumTransformer = getTypeExportImportAndConstEnumTransformer; - function getAnnotationTransformer(relativeFilePath) { - return function (context) { return transformAnnotation(context, relativeFilePath); }; + function getAnnotationTransformer() { + return function (context) { return transformAnnotation(context); }; } ts.getAnnotationTransformer = getAnnotationTransformer; - function transformAnnotation(context, relativeFilePath) { + function transformAnnotation(context) { var resolver = context.getEmitResolver(); - var annotationUniqueNamePrefix = getAnnotationUniqueNamePrefixFromFilePath(relativeFilePath); return transformSourceFile; function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -38877,35 +38923,18 @@ var ts; } } function visitAnnotationDeclaration(node) { - resolver.setAnnotationDeclarationUniquePrefix(node, annotationUniqueNamePrefix); - var uniqueName = addUniquePrefixToAnnotationNameIdentifier(node.name, annotationUniqueNamePrefix); - ts.Debug.assert(ts.isIdentifier(uniqueName)); var members = node.members.map(function (node) { var type = resolver.getAnnotationPropertyInferredType(node); var initializer = resolver.getAnnotationPropertyEvaluatedInitializer(node); return ts.factory.updateAnnotationPropertyDeclaration(node, node.name, type, initializer); }); - return ts.factory.updateAnnotationDeclaration(node, node.modifiers, uniqueName, members); + return ts.factory.updateAnnotationDeclaration(node, node.modifiers, node.name, members); } function visitAnnotation(node) { if (!node.annotationDeclaration) { return node; } - return ts.factory.updateDecorator(node, addMagicPrefixToAnnotationNameIdentifier(addUniquePrefixToAnnotationNameIdentifier(addDefaultValuesIntoAnnotationObjectLiteral(node), resolver.getAnnotationDeclarationUniquePrefix(node.annotationDeclaration)))); - } - function addUniquePrefixToAnnotationNameIdentifier(expr, prefix) { - switch (expr.kind) { - case 79: - return ts.factory.createIdentifier(prefix + expr.escapedText); - case 211: - var propAccessExpr = expr; - return ts.factory.updatePropertyAccessExpression(propAccessExpr, propAccessExpr.expression, addUniquePrefixToAnnotationNameIdentifier(propAccessExpr.name, prefix)); - case 213: - var callExpr = expr; - return ts.factory.updateCallExpression(callExpr, addUniquePrefixToAnnotationNameIdentifier(callExpr.expression, prefix), callExpr.typeArguments, callExpr.arguments); - default: - return expr; - } + return ts.factory.updateDecorator(node, addMagicPrefixToAnnotationNameIdentifier(addDefaultValuesIntoAnnotationObjectLiteral(node))); } function addMagicPrefixToAnnotationNameIdentifier(expr) { switch (expr.kind) { @@ -38962,9 +38991,6 @@ var ts; } ts.Debug.fail(); } - function getAnnotationUniqueNamePrefixFromFilePath(filePath) { - return ts.sys.createHash(filePath); - } } ts.transformAnnotation = transformAnnotation; function transformTypeExportImportAndConstEnumInTypeScript(context) { @@ -39191,9 +39217,12 @@ var ts; var output; var lineStart; var linePos; + var lineCount; + var noSpaceTrailingChars = new ts.Set([' ', ';', ',', '(', ')', '{', '}']); function updateLineCountAndPosFor(s) { var lineStartsOfS = ts.computeLineStarts(s); if (lineStartsOfS.length > 1) { + lineCount = lineCount + lineStartsOfS.length - 1; linePos = output.length - s.length + ts.last(lineStartsOfS); lineStart = (linePos - output.length) === 0; } @@ -39217,9 +39246,13 @@ var ts; output = ""; lineStart = true; linePos = 0; + lineCount = 0; } function rawWrite(s) { if (s !== undefined) { + if ((lineStart || endsWithNoSpaceTrailingChar(output)) && s.trim().length === 0) { + return; + } output += s; updateLineCountAndPosFor(s); } @@ -39230,10 +39263,15 @@ var ts; } } function writeLine(force) { - if (!lineStart || force) { - output += space; - linePos = output.length; + if (!force && (lineStart || endsWithNoSpaceTrailingChar(output))) { + return; } + output += space; + lineStart = false; + } + function endsWithNoSpaceTrailingChar(input) { + var lastChar = input.charAt(input.length - 1); + return noSpaceTrailingChars.has(lastChar); } function getTextPosWithWriteLine() { return lineStart ? output.length : (output.length + space.length); @@ -39248,7 +39286,7 @@ var ts; decreaseIndent: ts.noop, getIndent: function () { return 0; }, getTextPos: function () { return output.length; }, - getLine: function () { return 0; }, + getLine: function () { return lineCount; }, getColumn: function () { return lineStart ? 0 : output.length - linePos; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, @@ -39289,7 +39327,7 @@ var ts; return (ts.isIdentifier(nameExpr) && nameExpr.escapedText.toString() === 'Sendable'); } ts.isSendableFunctionOrType = isSendableFunctionOrType; - var JSON_SUFFIX = ".json"; + var JSON_SUFFIX = '.json'; var KIT_PREFIX = '@kit.'; var DEFAULT_KEYWORD = 'default'; var ETS_DECLARATION = '.d.ets'; @@ -39393,7 +39431,7 @@ var ts; '@kit.AccountKit', '@kit.MapKit', '@kit.Penkit', '@kit.ScenarioFusionKit', '@kit.ServiceCollaborationKit', '@kit.SpeechKit', '@kit.VisionKit', ]); - function InWhiteList(moduleSpecifierText, importName, inEtsContext) { + function inWhiteList(moduleSpecifierText, importName, inEtsContext) { if (whiteListForErrorSymbol.some(function (info) { return (info.kitName === moduleSpecifierText && info.symbolName === importName); })) { return true; } @@ -39426,7 +39464,7 @@ var ts; } var importName = ts.unescapeLeadingUnderscores(element.propertyName ? element.propertyName.escapedText : element.name.escapedText); var aliasName = element.name; - if (InWhiteList(moduleSpecifierText, importName, inEtsContext)) { + if (inWhiteList(moduleSpecifierText, importName, inEtsContext)) { hasError_1 = true; return; } @@ -39593,11 +39631,13 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.BINDE_SOURCE_FILE); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Bind", "beforeBind", "afterBind"); } ts.bindSourceFile = bindSourceFile; @@ -63326,7 +63366,8 @@ var ts; return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || node.kind === 271 || node.kind === 314 || - node.kind === 171; + node.kind === 171 || + node.kind === 172; }); } function isSymbolAssigned(symbol) { @@ -71775,6 +71816,9 @@ var ts; if (initVal === undefined || initValType === errorType) { return undefined; } + if (isArrayType(initValType) && !Array.isArray(initVal)) { + return undefined; + } if (typeof initVal === "number") { return ts.factory.createNumericLiteral(initVal); } @@ -71801,11 +71845,14 @@ var ts; args.push(ts.factory.createNumericLiteral(3)); } } - return ts.factory.createNewExpression(ts.factory.createIdentifier(typeToString(initValType, undefined, 2)), undefined, args); + return ts.factory.createNewExpression(ts.factory.createIdentifier("Array"), [nodeBuilder.typeToTypeNode(elemType)], args); } var result = new Array(initVal.length); for (var i = 0; i < initVal.length; ++i) { result[i] = annotationEvaluatedValueToExpr(initVal[i], elemType); + if (result[i] === undefined) { + return undefined; + } } return ts.factory.createArrayLiteralExpression(result); } @@ -77081,6 +77128,7 @@ var ts; } function checkSourceFile(node) { ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check", "checkSourceFile", { path: node.path }, true); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.CHECK_SOURCE_FILE); ts.performance.mark("beforeCheck"); if (host.getFileCheckedModuleInfo) { jsDocFileCheckInfo = host.getFileCheckedModuleInfo(node.fileName); @@ -77088,6 +77136,7 @@ var ts; } checkSourceFileWorker(node); ts.performance.mark("afterCheck"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Check", "beforeCheck", "afterCheck"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } @@ -78405,12 +78454,6 @@ var ts; getAnnotationPropertyInferredType: function (node) { return getNodeLinks(node).annotationPropertyInferredType; }, - setAnnotationDeclarationUniquePrefix: function (node, prefix) { - getNodeLinks(node).annotationDeclarationUniquePrefix = prefix; - }, - getAnnotationDeclarationUniquePrefix: function (node) { - return getNodeLinks(node).annotationDeclarationUniquePrefix; - }, isReferredToAnnotation: function (node) { return getNodeLinks(node).exportOrImportRefersToAnnotation; } @@ -95791,6 +95834,7 @@ var ts; var node = nodes_2[_i]; ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); } + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.TRANSFORM); ts.performance.mark("beforeTransform"); var transformersWithContext = transformers.map(function (t) { return t(context); }); var transformation = function (node) { @@ -95810,6 +95854,7 @@ var ts; } state = 2; ts.performance.mark("afterTransform"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("transformTime", "beforeTransform", "afterTransform"); return { transformed: transformed, @@ -96311,9 +96356,11 @@ var ts; var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit; var bundleBuildInfo; var emitSkipped = false; + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.EMIT_FILES); enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile); exit(); + ts.MemoryDotting.stopRecordStage(recordInfo); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -96629,8 +96676,6 @@ var ts; getAnnotationObjectLiteralEvaluatedProps: ts.notImplemented, getAnnotationPropertyEvaluatedInitializer: ts.notImplemented, getAnnotationPropertyInferredType: ts.notImplemented, - setAnnotationDeclarationUniquePrefix: ts.notImplemented, - getAnnotationDeclarationUniquePrefix: ts.notImplemented, isReferredToAnnotation: ts.notImplemented, }; function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) { @@ -102310,6 +102355,7 @@ var ts; var sourceFilesFoundSearchingNodeModules = new ts.Map(); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program", "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, true); ts.performance.mark("beforeProgram"); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.BEFORE_PROGRAM); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); var skipDefaultLib = options.noLib; @@ -102568,6 +102614,7 @@ var ts; }); verifyCompilerOptions(); ts.performance.mark("afterProgram"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Program", "beforeProgram", "afterProgram"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; diff --git a/lib/tsserver.js b/lib/tsserver.js index eac4416f28bd829a9d1ef30826147aa45d7857b9..71355649845421630d6f8467bd7df55aa7887b8c 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -10204,6 +10204,65 @@ var ts; Enable_support_of_ETS_annotations: diag(28038, ts.DiagnosticCategory.Message, "Enable_support_of_ETS_annotations_28038", "Enable support of ETS annotations"), }; })(ts || (ts = {})); +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * 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. + */ +var ts; +(function (ts) { + var MemoryDotting; + (function (MemoryDotting) { + MemoryDotting.BINDE_SOURCE_FILE = 'binder(bindSourceFile: Bind)'; + MemoryDotting.CHECK_SOURCE_FILE = 'checker(checkSourceFile: Check)'; + MemoryDotting.EMIT_FILES = 'emitter(emitFiles: EmitEachOutputFile)'; + MemoryDotting.CREATE_SORUCE_FILE_PARSE = 'parser(createSourceFile: Parse)'; + MemoryDotting.BEFORE_PROGRAM = 'program(createProgram: beforeProgram)'; + MemoryDotting.TRANSFORM = 'transformer(transformNodes: Transform)'; + var memoryDottingCallback; + var memoryDottingStopCallback; + function recordStage(stage) { + if (memoryDottingCallback !== undefined) { + return memoryDottingCallback(stage); + } + return null; + } + MemoryDotting.recordStage = recordStage; + function stopRecordStage(recordInfo) { + if (memoryDottingStopCallback !== undefined && recordInfo !== null) { + memoryDottingStopCallback(recordInfo); + } + } + MemoryDotting.stopRecordStage = stopRecordStage; + function setMemoryDottingCallBack(recordCallback, stopCallback) { + if (recordCallback) { + memoryDottingCallback = recordCallback; + } + if (stopCallback) { + memoryDottingStopCallback = stopCallback; + } + } + MemoryDotting.setMemoryDottingCallBack = setMemoryDottingCallBack; + function clearCallBack() { + if (memoryDottingCallback !== undefined) { + memoryDottingCallback = undefined; + } + if (memoryDottingStopCallback !== undefined) { + memoryDottingStopCallback = undefined; + } + } + MemoryDotting.clearCallBack = clearCallBack; + })(MemoryDotting = ts.MemoryDotting || (ts.MemoryDotting = {})); +})(ts || (ts = {})); var ts; (function (ts) { var _a; @@ -32563,6 +32622,7 @@ var ts; function createSourceFile(fileName, sourceText, languageVersionOrOptions, setParentNodes, scriptKind, options) { if (setParentNodes === void 0) { setParentNodes = false; } ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* tracing.Phase.Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.CREATE_SORUCE_FILE_PARSE); ts.performance.mark("beforeParse"); var result; sourceFileCompilerOptions = options !== null && options !== void 0 ? options : ts.defaultInitCompilerOptions; @@ -32580,6 +32640,7 @@ var ts; } ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Parse", "beforeParse", "afterParse"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; @@ -46754,7 +46815,7 @@ var ts; (function (ts) { /* @internal */ // Required for distinguishing annotations and decorators in other code analysis tools - ts.annotationMagicNamePrefix = "#"; + ts.annotationMagicNamePrefix = "__$$ETS_ANNOTATION$$__"; /* @internal */ function isInEtsFile(node) { var _a; @@ -47162,13 +47223,12 @@ var ts; return transformTypeExportImportAndConstEnumInTypeScript(context); } ts.getTypeExportImportAndConstEnumTransformer = getTypeExportImportAndConstEnumTransformer; - function getAnnotationTransformer(relativeFilePath) { - return function (context) { return transformAnnotation(context, relativeFilePath); }; + function getAnnotationTransformer() { + return function (context) { return transformAnnotation(context); }; } ts.getAnnotationTransformer = getAnnotationTransformer; - function transformAnnotation(context, relativeFilePath) { + function transformAnnotation(context) { var resolver = context.getEmitResolver(); - var annotationUniqueNamePrefix = getAnnotationUniqueNamePrefixFromFilePath(relativeFilePath); return transformSourceFile; function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -47196,19 +47256,14 @@ var ts; } } function visitAnnotationDeclaration(node) { - resolver.setAnnotationDeclarationUniquePrefix(node, annotationUniqueNamePrefix); - // Add unique prefix for AnnotationDeclaration. For example, - // @interface Anno {} --- > @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno {} - var uniqueName = addUniquePrefixToAnnotationNameIdentifier(node.name, annotationUniqueNamePrefix); - ts.Debug.assert(ts.isIdentifier(uniqueName)); // Add explicit type annotation and initializer. For example, - // @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno { + // @interface Anno { // a = 10 + 5 // } // // will be transformed to // - // @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno { + // @interface Anno { // a: number = 15 // } var members = node.members.map(function (node) { @@ -47216,7 +47271,7 @@ var ts; var initializer = resolver.getAnnotationPropertyEvaluatedInitializer(node); return ts.factory.updateAnnotationPropertyDeclaration(node, node.name, type, initializer); }); - return ts.factory.updateAnnotationDeclaration(node, node.modifiers, uniqueName, members); + return ts.factory.updateAnnotationDeclaration(node, node.modifiers, node.name, members); } function visitAnnotation(node) { if (!node.annotationDeclaration) { @@ -47233,28 +47288,9 @@ var ts; // // and // - // Add unique prefix for annotation name. For example, - // @myModule.Anno({a: 10, b: "abc"}) --- > @myModule.e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855({a: 10, b: "abc"}) - // - // and - // // Add the magic prefix for annotation name. For example, - // @myModule.Anno({a: 10, b: "abc"}) --- > @#myModule.e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855({a: 10, b: "abc"}) - return ts.factory.updateDecorator(node, addMagicPrefixToAnnotationNameIdentifier(addUniquePrefixToAnnotationNameIdentifier(addDefaultValuesIntoAnnotationObjectLiteral(node), resolver.getAnnotationDeclarationUniquePrefix(node.annotationDeclaration)))); - } - function addUniquePrefixToAnnotationNameIdentifier(expr, prefix) { - switch (expr.kind) { - case 79 /* SyntaxKind.Identifier */: - return ts.factory.createIdentifier(prefix + expr.escapedText); - case 211 /* SyntaxKind.PropertyAccessExpression */: - var propAccessExpr = expr; - return ts.factory.updatePropertyAccessExpression(propAccessExpr, propAccessExpr.expression, addUniquePrefixToAnnotationNameIdentifier(propAccessExpr.name, prefix)); - case 213 /* SyntaxKind.CallExpression */: - var callExpr = expr; - return ts.factory.updateCallExpression(callExpr, addUniquePrefixToAnnotationNameIdentifier(callExpr.expression, prefix), callExpr.typeArguments, callExpr.arguments); - default: - return expr; - } + // @myModule.Anno({a: 10, b: "abc"}) --- > @#myModule.Anno({a: 10, b: "abc"}) + return ts.factory.updateDecorator(node, addMagicPrefixToAnnotationNameIdentifier(addDefaultValuesIntoAnnotationObjectLiteral(node))); } function addMagicPrefixToAnnotationNameIdentifier(expr) { switch (expr.kind) { @@ -47313,9 +47349,6 @@ var ts; } ts.Debug.fail(); } - function getAnnotationUniqueNamePrefixFromFilePath(filePath) { - return ts.sys.createHash(filePath); - } } ts.transformAnnotation = transformAnnotation; /** @@ -47603,9 +47636,14 @@ var ts; var output; var lineStart; var linePos; + var lineCount; + // If the last character of string is the one of below chars, there is no need to write space again. + var noSpaceTrailingChars = new ts.Set([' ', ';', ',', '(', ')', '{', '}']); function updateLineCountAndPosFor(s) { var lineStartsOfS = ts.computeLineStarts(s); if (lineStartsOfS.length > 1) { + // 1: The first element of the lineStartsOfS + lineCount = lineCount + lineStartsOfS.length - 1; linePos = output.length - s.length + ts.last(lineStartsOfS); lineStart = (linePos - output.length) === 0; } @@ -47629,9 +47667,15 @@ var ts; output = ""; lineStart = true; linePos = 0; + lineCount = 0; } + // This method is used to write indentation and line breaks. If the string is blank, the writing is skipped. + // In addition, this method can be called to write comments and code in bundle mode, but obfuscation is not in bundle mode. function rawWrite(s) { if (s !== undefined) { + if ((lineStart || endsWithNoSpaceTrailingChar(output)) && s.trim().length === 0) { + return; + } output += s; updateLineCountAndPosFor(s); } @@ -47642,10 +47686,16 @@ var ts; } } function writeLine(force) { - if (!lineStart || force) { - output += space; - linePos = output.length; + if (!force && (lineStart || endsWithNoSpaceTrailingChar(output))) { + return; } + output += space; + lineStart = false; + } + function endsWithNoSpaceTrailingChar(input) { + // Get the last character of a string. + var lastChar = input.charAt(input.length - 1); + return noSpaceTrailingChars.has(lastChar); } function getTextPosWithWriteLine() { return lineStart ? output.length : (output.length + space.length); @@ -47660,7 +47710,7 @@ var ts; decreaseIndent: ts.noop, getIndent: function () { return 0; }, getTextPos: function () { return output.length; }, - getLine: function () { return 0; }, + getLine: function () { return lineCount; }, getColumn: function () { return lineStart ? 0 : output.length - linePos; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, @@ -47702,7 +47752,7 @@ var ts; return (ts.isIdentifier(nameExpr) && nameExpr.escapedText.toString() === 'Sendable'); } ts.isSendableFunctionOrType = isSendableFunctionOrType; - var JSON_SUFFIX = ".json"; + var JSON_SUFFIX = '.json'; var KIT_PREFIX = '@kit.'; var DEFAULT_KEYWORD = 'default'; var ETS_DECLARATION = '.d.ets'; @@ -47814,7 +47864,7 @@ var ts; '@kit.AccountKit', '@kit.MapKit', '@kit.Penkit', '@kit.ScenarioFusionKit', '@kit.ServiceCollaborationKit', '@kit.SpeechKit', '@kit.VisionKit', ]); - function InWhiteList(moduleSpecifierText, importName, inEtsContext) { + function inWhiteList(moduleSpecifierText, importName, inEtsContext) { if (whiteListForErrorSymbol.some(function (info) { return (info.kitName === moduleSpecifierText && info.symbolName === importName); })) { return true; } @@ -47848,7 +47898,7 @@ var ts; } var importName = ts.unescapeLeadingUnderscores(element.propertyName ? element.propertyName.escapedText : element.name.escapedText); var aliasName = element.name; - if (InWhiteList(moduleSpecifierText, importName, inEtsContext)) { + if (inWhiteList(moduleSpecifierText, importName, inEtsContext)) { hasError_1 = true; return; } @@ -48062,11 +48112,13 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.BINDE_SOURCE_FILE); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Bind", "beforeBind", "afterBind"); } ts.bindSourceFile = bindSourceFile; @@ -75461,7 +75513,8 @@ var ts; return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || node.kind === 271 /* SyntaxKind.ModuleBlock */ || node.kind === 314 /* SyntaxKind.SourceFile */ || - node.kind === 171 /* SyntaxKind.PropertyDeclaration */; + node.kind === 171 /* SyntaxKind.PropertyDeclaration */ || + node.kind === 172 /* SyntaxKind.AnnotationPropertyDeclaration */; }); } // Check if a parameter or catch variable is assigned anywhere @@ -85196,6 +85249,9 @@ var ts; if (initVal === undefined || initValType === errorType) { return undefined; } + if (isArrayType(initValType) && !Array.isArray(initVal)) { + return undefined; + } if (typeof initVal === "number") { return ts.factory.createNumericLiteral(initVal); } @@ -85228,12 +85284,14 @@ var ts; args.push(ts.factory.createNumericLiteral(3)); } } - return ts.factory.createNewExpression(ts.factory.createIdentifier(typeToString(initValType, /*enclosingDeclaration*/ undefined, 2 /* TypeFormatFlags.WriteArrayAsGenericType */)), - /*typeArguments*/ undefined, args); + return ts.factory.createNewExpression(ts.factory.createIdentifier("Array"), [nodeBuilder.typeToTypeNode(elemType)], args); } var result = new Array(initVal.length); for (var i = 0; i < initVal.length; ++i) { result[i] = annotationEvaluatedValueToExpr(initVal[i], elemType); + if (result[i] === undefined) { + return undefined; + } } return ts.factory.createArrayLiteralExpression(result); } @@ -91409,6 +91467,7 @@ var ts; } function checkSourceFile(node) { ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* tracing.Phase.Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.CHECK_SOURCE_FILE); ts.performance.mark("beforeCheck"); if (host.getFileCheckedModuleInfo) { jsDocFileCheckInfo = host.getFileCheckedModuleInfo(node.fileName); @@ -91416,6 +91475,7 @@ var ts; } checkSourceFileWorker(node); ts.performance.mark("afterCheck"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Check", "beforeCheck", "afterCheck"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } @@ -92929,12 +92989,6 @@ var ts; getAnnotationPropertyInferredType: function (node) { return getNodeLinks(node).annotationPropertyInferredType; }, - setAnnotationDeclarationUniquePrefix: function (node, prefix) { - getNodeLinks(node).annotationDeclarationUniquePrefix = prefix; - }, - getAnnotationDeclarationUniquePrefix: function (node) { - return getNodeLinks(node).annotationDeclarationUniquePrefix; - }, isReferredToAnnotation: function (node) { return getNodeLinks(node).exportOrImportRefersToAnnotation; } @@ -116015,6 +116069,7 @@ var ts; var node = nodes_2[_i]; ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); } + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.TRANSFORM); ts.performance.mark("beforeTransform"); // Chain together and initialize each transformer. var transformersWithContext = transformers.map(function (t) { return t(context); }); @@ -116038,6 +116093,7 @@ var ts; // prevent modification of the lexical environment. state = 2 /* TransformationState.Completed */; ts.performance.mark("afterTransform"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("transformTime", "beforeTransform", "afterTransform"); return { transformed: transformed, @@ -116631,10 +116687,12 @@ var ts; var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit; var bundleBuildInfo; var emitSkipped = false; + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.EMIT_FILES); // Emit each output file enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile); exit(); + ts.MemoryDotting.stopRecordStage(recordInfo); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -116986,8 +117044,6 @@ var ts; getAnnotationObjectLiteralEvaluatedProps: ts.notImplemented, getAnnotationPropertyEvaluatedInitializer: ts.notImplemented, getAnnotationPropertyInferredType: ts.notImplemented, - setAnnotationDeclarationUniquePrefix: ts.notImplemented, - getAnnotationDeclarationUniquePrefix: ts.notImplemented, isReferredToAnnotation: ts.notImplemented, }; function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) { @@ -123251,6 +123307,7 @@ var ts; var sourceFilesFoundSearchingNodeModules = new ts.Map(); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* tracing.Phase.Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeProgram"); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.BEFORE_PROGRAM); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); var skipDefaultLib = options.noLib; @@ -123542,6 +123599,7 @@ var ts; }); verifyCompilerOptions(); ts.performance.mark("afterProgram"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Program", "beforeProgram", "afterProgram"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; @@ -172327,13 +172385,12 @@ var ts; while (pos < end) { var token = ts.scanner.scan(); var textPos = ts.scanner.getTextPos(); - if (!ts.isSourceFile(parent) || !ts.isInMarkedKitImport(parent, pos, textPos)) { - if (textPos <= end) { - if (token === 79 /* SyntaxKind.Identifier */) { - ts.Debug.fail("Did not expect ".concat(ts.Debug.formatSyntaxKind(parent.kind), " to have an Identifier in its trivia")); - } - nodes.push(createNode(token, pos, textPos, parent)); + var isSourceFileOrInMarkedKitImport = !ts.isSourceFile(parent) || !ts.isInMarkedKitImport(parent, pos, textPos); + if (isSourceFileOrInMarkedKitImport && textPos <= end) { + if (token === 79 /* SyntaxKind.Identifier */) { + ts.Debug.fail("Did not expect ".concat(ts.Debug.formatSyntaxKind(parent.kind), " to have an Identifier in its trivia")); } + nodes.push(createNode(token, pos, textPos, parent)); } pos = textPos; if (token === 1 /* SyntaxKind.EndOfFileToken */) { @@ -195591,25 +195648,56 @@ var ts; (((_c = tsType.getSymbol()) === null || _c === void 0 ? void 0 : _c.getName()) === 'ReadonlyArray')); } Utils.isReadonlyArrayType = isReadonlyArrayType; - function isTypedArray(tsType) { + function isConcatArrayType(tsType) { + var _a, _b, _c; + return (isStdLibraryType(tsType) && + isTypeReference(tsType) && + ((_a = tsType.typeArguments) === null || _a === void 0 ? void 0 : _a.length) === 1 && + ((_b = tsType.target.typeParameters) === null || _b === void 0 ? void 0 : _b.length) === 1 && + (((_c = tsType.getSymbol()) === null || _c === void 0 ? void 0 : _c.getName()) === 'ConcatArray')); + } + Utils.isConcatArrayType = isConcatArrayType; + function isArrayLikeType(tsType) { + var _a, _b, _c; + return (isStdLibraryType(tsType) && + isTypeReference(tsType) && + ((_a = tsType.typeArguments) === null || _a === void 0 ? void 0 : _a.length) === 1 && + ((_b = tsType.target.typeParameters) === null || _b === void 0 ? void 0 : _b.length) === 1 && + (((_c = tsType.getSymbol()) === null || _c === void 0 ? void 0 : _c.getName()) === 'ArrayLike')); + } + Utils.isArrayLikeType = isArrayLikeType; + function isTypedArray(tsType, allowTypeArrays) { var symbol = tsType.symbol; if (!symbol) { return false; } var name = typeChecker.getFullyQualifiedName(symbol); - if (isGlobalSymbol(symbol) && Utils.TYPED_ARRAYS.includes(name)) { + if (isGlobalSymbol(symbol) && allowTypeArrays.includes(name)) { return true; } var decl = getDeclaration(symbol); return (!!decl && isArkTSCollectionsClassOrInterfaceDeclaration(decl) && - Utils.TYPED_ARRAYS.includes(symbol.getName())); + allowTypeArrays.includes(symbol.getName())); } Utils.isTypedArray = isTypedArray; function isArray(tsType) { - return isGenericArrayType(tsType) || isReadonlyArrayType(tsType) || isTypedArray(tsType); + return isGenericArrayType(tsType) || isReadonlyArrayType(tsType) || isTypedArray(tsType, Utils.TYPED_ARRAYS); } Utils.isArray = isArray; + function isCollectionArrayType(tsType) { + return isTypedArray(tsType, Utils.TYPED_COLLECTIONS); + } + Utils.isCollectionArrayType = isCollectionArrayType; + function isIndexableArray(tsType) { + return (isGenericArrayType(tsType) || + isReadonlyArrayType(tsType) || + isConcatArrayType(tsType) || + isArrayLikeType(tsType) || + isTypedArray(tsType, Utils.TYPED_ARRAYS) || + isTypedArray(tsType, Utils.TYPED_COLLECTIONS)); + } + Utils.isIndexableArray = isIndexableArray; function isTuple(tsType) { return isTypeReference(tsType) && !!(tsType.objectFlags & 8 /* ts.ObjectFlags.Tuple */); } @@ -196364,17 +196452,20 @@ var ts; "lib.es2022.sharedmemory.d.ts", "lib.es2022.string.d.ts", "lib.es2022.regexp.d.ts", "lib.es2023.array.d.ts", ]; Utils.TYPED_ARRAYS = [ - "Int8Array", - "Uint8Array", - "Uint8ClampedArray", - "Int16Array", - "Uint16Array", - "Int32Array", - "Uint32Array", - "Float32Array", - "Float64Array", - "BigInt64Array", - "BigUint64Array", + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array', + ]; + Utils.TYPED_COLLECTIONS = [ + 'BitVector' ]; var parentSymbolCache = new ts.Map(); function getParentSymbolName(symbol) { @@ -199162,6 +199253,9 @@ var ts; return; } } + if ((tsIdentSym.flags & 268435456 /* SymbolFlags.Annotation */) !== 0) { + return; + } if (tsIdentSym.flags & 512 /* SymbolFlags.ValueModule */) { this.incrementCounters(tsIdentifier, FaultID.NamespaceAsObject); } @@ -199225,7 +199319,7 @@ var ts; } return (ArkTSLinter_1_1.Utils.isLibraryType(type) || ArkTSLinter_1_1.Utils.isAnyType(type) || - ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isArray) || + ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isIndexableArray) || ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isTuple) || ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isStdRecordType) || ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isStringType) || @@ -199577,7 +199671,8 @@ var ts; var spreadExprType = ArkTSLinter_1_1.Utils.getTypeOrTypeConstraintAtLocation(node.expression); if (spreadExprType) { if (ts.isCallLikeExpression(node.parent) || ts.isArrayLiteralExpression(node.parent)) { - if (ArkTSLinter_1_1.Utils.isOrDerivedFrom(spreadExprType, ArkTSLinter_1_1.Utils.isArray)) { + if (ArkTSLinter_1_1.Utils.isOrDerivedFrom(spreadExprType, ArkTSLinter_1_1.Utils.isArray) || + ArkTSLinter_1_1.Utils.isOrDerivedFrom(spreadExprType, ArkTSLinter_1_1.Utils.isCollectionArrayType)) { return; } } diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 9219c3dbb2a44b1a101a2e622c076b109f9ce117..979482643ce56d33c84da5d1d4fe8da8f503b024 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -4600,6 +4600,24 @@ declare namespace ts { export let sys: System; export {}; } +declare namespace ts { + namespace MemoryDotting { + interface RecordInfo { + recordStage: string; + recordIndex: number; + } + const BINDE_SOURCE_FILE = "binder(bindSourceFile: Bind)"; + const CHECK_SOURCE_FILE = "checker(checkSourceFile: Check)"; + const EMIT_FILES = "emitter(emitFiles: EmitEachOutputFile)"; + const CREATE_SORUCE_FILE_PARSE = "parser(createSourceFile: Parse)"; + const BEFORE_PROGRAM = "program(createProgram: beforeProgram)"; + const TRANSFORM = "transformer(transformNodes: Transform)"; + function recordStage(stage: string): RecordInfo | null; + function stopRecordStage(recordInfo: RecordInfo | null): void; + function setMemoryDottingCallBack(recordCallback: (stage: string) => RecordInfo, stopCallback: (recordInfo: RecordInfo) => void): void; + function clearCallBack(): void; + } +} declare namespace ts { type ErrorCallback = (message: DiagnosticMessage, length: number) => void; interface Scanner { @@ -5468,8 +5486,8 @@ declare namespace ts { function pathContainsOHModules(path: string): boolean; function choosePathContainsModules(packageManagerType: string | undefined, fileName: string): boolean; function getTypeExportImportAndConstEnumTransformer(context: TransformationContext): (node: SourceFile) => SourceFile; - function getAnnotationTransformer(relativeFilePath: string): TransformerFactory; - function transformAnnotation(context: TransformationContext, relativeFilePath: string): (node: SourceFile) => SourceFile; + function getAnnotationTransformer(): TransformerFactory; + function transformAnnotation(context: TransformationContext): (node: SourceFile) => SourceFile; /** * Add 'type' flag to import/export when import/export an type member. * Replace const enum with number and string literal. @@ -13326,8 +13344,12 @@ declare namespace ts { function isTypeSymbol(symbol: Symbol | undefined): boolean; function isGenericArrayType(tsType: Type): tsType is TypeReference; function isReadonlyArrayType(tsType: Type): boolean; - function isTypedArray(tsType: ts.Type): boolean; + function isConcatArrayType(tsType: Type): boolean; + function isArrayLikeType(tsType: Type): boolean; + function isTypedArray(tsType: ts.Type, allowTypeArrays: string[]): boolean; function isArray(tsType: ts.Type): boolean; + function isCollectionArrayType(tsType: ts.Type): boolean; + function isIndexableArray(tsType: ts.Type): boolean; function isTuple(tsType: ts.Type): boolean; function isOrDerivedFrom(tsType: ts.Type, checkType: CheckType, checkedBaseTypes?: Set): boolean; function isTypeReference(tsType: Type): tsType is TypeReference; @@ -13382,6 +13404,7 @@ declare namespace ts { const NON_RETURN_FUNCTION_DECORATORS: string[]; const STANDARD_LIBRARIES: string[]; const TYPED_ARRAYS: string[]; + const TYPED_COLLECTIONS: string[]; function getParentSymbolName(symbol: Symbol): string | undefined; function isGlobalSymbol(symbol: Symbol): boolean; function isSymbolAPI(symbol: Symbol): boolean; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 62da6990715ee2e26734d261f7d950cdbee30ae1..f7d47aec9aafac78eead2776c4ff51b0c2fc276b 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -10203,6 +10203,65 @@ var ts; Enable_support_of_ETS_annotations: diag(28038, ts.DiagnosticCategory.Message, "Enable_support_of_ETS_annotations_28038", "Enable support of ETS annotations"), }; })(ts || (ts = {})); +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * 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. + */ +var ts; +(function (ts) { + var MemoryDotting; + (function (MemoryDotting) { + MemoryDotting.BINDE_SOURCE_FILE = 'binder(bindSourceFile: Bind)'; + MemoryDotting.CHECK_SOURCE_FILE = 'checker(checkSourceFile: Check)'; + MemoryDotting.EMIT_FILES = 'emitter(emitFiles: EmitEachOutputFile)'; + MemoryDotting.CREATE_SORUCE_FILE_PARSE = 'parser(createSourceFile: Parse)'; + MemoryDotting.BEFORE_PROGRAM = 'program(createProgram: beforeProgram)'; + MemoryDotting.TRANSFORM = 'transformer(transformNodes: Transform)'; + var memoryDottingCallback; + var memoryDottingStopCallback; + function recordStage(stage) { + if (memoryDottingCallback !== undefined) { + return memoryDottingCallback(stage); + } + return null; + } + MemoryDotting.recordStage = recordStage; + function stopRecordStage(recordInfo) { + if (memoryDottingStopCallback !== undefined && recordInfo !== null) { + memoryDottingStopCallback(recordInfo); + } + } + MemoryDotting.stopRecordStage = stopRecordStage; + function setMemoryDottingCallBack(recordCallback, stopCallback) { + if (recordCallback) { + memoryDottingCallback = recordCallback; + } + if (stopCallback) { + memoryDottingStopCallback = stopCallback; + } + } + MemoryDotting.setMemoryDottingCallBack = setMemoryDottingCallBack; + function clearCallBack() { + if (memoryDottingCallback !== undefined) { + memoryDottingCallback = undefined; + } + if (memoryDottingStopCallback !== undefined) { + memoryDottingStopCallback = undefined; + } + } + MemoryDotting.clearCallBack = clearCallBack; + })(MemoryDotting = ts.MemoryDotting || (ts.MemoryDotting = {})); +})(ts || (ts = {})); var ts; (function (ts) { var _a; @@ -32562,6 +32621,7 @@ var ts; function createSourceFile(fileName, sourceText, languageVersionOrOptions, setParentNodes, scriptKind, options) { if (setParentNodes === void 0) { setParentNodes = false; } ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* tracing.Phase.Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.CREATE_SORUCE_FILE_PARSE); ts.performance.mark("beforeParse"); var result; sourceFileCompilerOptions = options !== null && options !== void 0 ? options : ts.defaultInitCompilerOptions; @@ -32579,6 +32639,7 @@ var ts; } ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Parse", "beforeParse", "afterParse"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; @@ -46753,7 +46814,7 @@ var ts; (function (ts) { /* @internal */ // Required for distinguishing annotations and decorators in other code analysis tools - ts.annotationMagicNamePrefix = "#"; + ts.annotationMagicNamePrefix = "__$$ETS_ANNOTATION$$__"; /* @internal */ function isInEtsFile(node) { var _a; @@ -47161,13 +47222,12 @@ var ts; return transformTypeExportImportAndConstEnumInTypeScript(context); } ts.getTypeExportImportAndConstEnumTransformer = getTypeExportImportAndConstEnumTransformer; - function getAnnotationTransformer(relativeFilePath) { - return function (context) { return transformAnnotation(context, relativeFilePath); }; + function getAnnotationTransformer() { + return function (context) { return transformAnnotation(context); }; } ts.getAnnotationTransformer = getAnnotationTransformer; - function transformAnnotation(context, relativeFilePath) { + function transformAnnotation(context) { var resolver = context.getEmitResolver(); - var annotationUniqueNamePrefix = getAnnotationUniqueNamePrefixFromFilePath(relativeFilePath); return transformSourceFile; function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -47195,19 +47255,14 @@ var ts; } } function visitAnnotationDeclaration(node) { - resolver.setAnnotationDeclarationUniquePrefix(node, annotationUniqueNamePrefix); - // Add unique prefix for AnnotationDeclaration. For example, - // @interface Anno {} --- > @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno {} - var uniqueName = addUniquePrefixToAnnotationNameIdentifier(node.name, annotationUniqueNamePrefix); - ts.Debug.assert(ts.isIdentifier(uniqueName)); // Add explicit type annotation and initializer. For example, - // @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno { + // @interface Anno { // a = 10 + 5 // } // // will be transformed to // - // @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno { + // @interface Anno { // a: number = 15 // } var members = node.members.map(function (node) { @@ -47215,7 +47270,7 @@ var ts; var initializer = resolver.getAnnotationPropertyEvaluatedInitializer(node); return ts.factory.updateAnnotationPropertyDeclaration(node, node.name, type, initializer); }); - return ts.factory.updateAnnotationDeclaration(node, node.modifiers, uniqueName, members); + return ts.factory.updateAnnotationDeclaration(node, node.modifiers, node.name, members); } function visitAnnotation(node) { if (!node.annotationDeclaration) { @@ -47232,28 +47287,9 @@ var ts; // // and // - // Add unique prefix for annotation name. For example, - // @myModule.Anno({a: 10, b: "abc"}) --- > @myModule.e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855({a: 10, b: "abc"}) - // - // and - // // Add the magic prefix for annotation name. For example, - // @myModule.Anno({a: 10, b: "abc"}) --- > @#myModule.e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855({a: 10, b: "abc"}) - return ts.factory.updateDecorator(node, addMagicPrefixToAnnotationNameIdentifier(addUniquePrefixToAnnotationNameIdentifier(addDefaultValuesIntoAnnotationObjectLiteral(node), resolver.getAnnotationDeclarationUniquePrefix(node.annotationDeclaration)))); - } - function addUniquePrefixToAnnotationNameIdentifier(expr, prefix) { - switch (expr.kind) { - case 79 /* SyntaxKind.Identifier */: - return ts.factory.createIdentifier(prefix + expr.escapedText); - case 211 /* SyntaxKind.PropertyAccessExpression */: - var propAccessExpr = expr; - return ts.factory.updatePropertyAccessExpression(propAccessExpr, propAccessExpr.expression, addUniquePrefixToAnnotationNameIdentifier(propAccessExpr.name, prefix)); - case 213 /* SyntaxKind.CallExpression */: - var callExpr = expr; - return ts.factory.updateCallExpression(callExpr, addUniquePrefixToAnnotationNameIdentifier(callExpr.expression, prefix), callExpr.typeArguments, callExpr.arguments); - default: - return expr; - } + // @myModule.Anno({a: 10, b: "abc"}) --- > @#myModule.Anno({a: 10, b: "abc"}) + return ts.factory.updateDecorator(node, addMagicPrefixToAnnotationNameIdentifier(addDefaultValuesIntoAnnotationObjectLiteral(node))); } function addMagicPrefixToAnnotationNameIdentifier(expr) { switch (expr.kind) { @@ -47312,9 +47348,6 @@ var ts; } ts.Debug.fail(); } - function getAnnotationUniqueNamePrefixFromFilePath(filePath) { - return ts.sys.createHash(filePath); - } } ts.transformAnnotation = transformAnnotation; /** @@ -47602,9 +47635,14 @@ var ts; var output; var lineStart; var linePos; + var lineCount; + // If the last character of string is the one of below chars, there is no need to write space again. + var noSpaceTrailingChars = new ts.Set([' ', ';', ',', '(', ')', '{', '}']); function updateLineCountAndPosFor(s) { var lineStartsOfS = ts.computeLineStarts(s); if (lineStartsOfS.length > 1) { + // 1: The first element of the lineStartsOfS + lineCount = lineCount + lineStartsOfS.length - 1; linePos = output.length - s.length + ts.last(lineStartsOfS); lineStart = (linePos - output.length) === 0; } @@ -47628,9 +47666,15 @@ var ts; output = ""; lineStart = true; linePos = 0; + lineCount = 0; } + // This method is used to write indentation and line breaks. If the string is blank, the writing is skipped. + // In addition, this method can be called to write comments and code in bundle mode, but obfuscation is not in bundle mode. function rawWrite(s) { if (s !== undefined) { + if ((lineStart || endsWithNoSpaceTrailingChar(output)) && s.trim().length === 0) { + return; + } output += s; updateLineCountAndPosFor(s); } @@ -47641,10 +47685,16 @@ var ts; } } function writeLine(force) { - if (!lineStart || force) { - output += space; - linePos = output.length; + if (!force && (lineStart || endsWithNoSpaceTrailingChar(output))) { + return; } + output += space; + lineStart = false; + } + function endsWithNoSpaceTrailingChar(input) { + // Get the last character of a string. + var lastChar = input.charAt(input.length - 1); + return noSpaceTrailingChars.has(lastChar); } function getTextPosWithWriteLine() { return lineStart ? output.length : (output.length + space.length); @@ -47659,7 +47709,7 @@ var ts; decreaseIndent: ts.noop, getIndent: function () { return 0; }, getTextPos: function () { return output.length; }, - getLine: function () { return 0; }, + getLine: function () { return lineCount; }, getColumn: function () { return lineStart ? 0 : output.length - linePos; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, @@ -47701,7 +47751,7 @@ var ts; return (ts.isIdentifier(nameExpr) && nameExpr.escapedText.toString() === 'Sendable'); } ts.isSendableFunctionOrType = isSendableFunctionOrType; - var JSON_SUFFIX = ".json"; + var JSON_SUFFIX = '.json'; var KIT_PREFIX = '@kit.'; var DEFAULT_KEYWORD = 'default'; var ETS_DECLARATION = '.d.ets'; @@ -47813,7 +47863,7 @@ var ts; '@kit.AccountKit', '@kit.MapKit', '@kit.Penkit', '@kit.ScenarioFusionKit', '@kit.ServiceCollaborationKit', '@kit.SpeechKit', '@kit.VisionKit', ]); - function InWhiteList(moduleSpecifierText, importName, inEtsContext) { + function inWhiteList(moduleSpecifierText, importName, inEtsContext) { if (whiteListForErrorSymbol.some(function (info) { return (info.kitName === moduleSpecifierText && info.symbolName === importName); })) { return true; } @@ -47847,7 +47897,7 @@ var ts; } var importName = ts.unescapeLeadingUnderscores(element.propertyName ? element.propertyName.escapedText : element.name.escapedText); var aliasName = element.name; - if (InWhiteList(moduleSpecifierText, importName, inEtsContext)) { + if (inWhiteList(moduleSpecifierText, importName, inEtsContext)) { hasError_1 = true; return; } @@ -48061,11 +48111,13 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.BINDE_SOURCE_FILE); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Bind", "beforeBind", "afterBind"); } ts.bindSourceFile = bindSourceFile; @@ -75460,7 +75512,8 @@ var ts; return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || node.kind === 271 /* SyntaxKind.ModuleBlock */ || node.kind === 314 /* SyntaxKind.SourceFile */ || - node.kind === 171 /* SyntaxKind.PropertyDeclaration */; + node.kind === 171 /* SyntaxKind.PropertyDeclaration */ || + node.kind === 172 /* SyntaxKind.AnnotationPropertyDeclaration */; }); } // Check if a parameter or catch variable is assigned anywhere @@ -85195,6 +85248,9 @@ var ts; if (initVal === undefined || initValType === errorType) { return undefined; } + if (isArrayType(initValType) && !Array.isArray(initVal)) { + return undefined; + } if (typeof initVal === "number") { return ts.factory.createNumericLiteral(initVal); } @@ -85227,12 +85283,14 @@ var ts; args.push(ts.factory.createNumericLiteral(3)); } } - return ts.factory.createNewExpression(ts.factory.createIdentifier(typeToString(initValType, /*enclosingDeclaration*/ undefined, 2 /* TypeFormatFlags.WriteArrayAsGenericType */)), - /*typeArguments*/ undefined, args); + return ts.factory.createNewExpression(ts.factory.createIdentifier("Array"), [nodeBuilder.typeToTypeNode(elemType)], args); } var result = new Array(initVal.length); for (var i = 0; i < initVal.length; ++i) { result[i] = annotationEvaluatedValueToExpr(initVal[i], elemType); + if (result[i] === undefined) { + return undefined; + } } return ts.factory.createArrayLiteralExpression(result); } @@ -91408,6 +91466,7 @@ var ts; } function checkSourceFile(node) { ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* tracing.Phase.Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.CHECK_SOURCE_FILE); ts.performance.mark("beforeCheck"); if (host.getFileCheckedModuleInfo) { jsDocFileCheckInfo = host.getFileCheckedModuleInfo(node.fileName); @@ -91415,6 +91474,7 @@ var ts; } checkSourceFileWorker(node); ts.performance.mark("afterCheck"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Check", "beforeCheck", "afterCheck"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } @@ -92928,12 +92988,6 @@ var ts; getAnnotationPropertyInferredType: function (node) { return getNodeLinks(node).annotationPropertyInferredType; }, - setAnnotationDeclarationUniquePrefix: function (node, prefix) { - getNodeLinks(node).annotationDeclarationUniquePrefix = prefix; - }, - getAnnotationDeclarationUniquePrefix: function (node) { - return getNodeLinks(node).annotationDeclarationUniquePrefix; - }, isReferredToAnnotation: function (node) { return getNodeLinks(node).exportOrImportRefersToAnnotation; } @@ -116014,6 +116068,7 @@ var ts; var node = nodes_2[_i]; ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); } + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.TRANSFORM); ts.performance.mark("beforeTransform"); // Chain together and initialize each transformer. var transformersWithContext = transformers.map(function (t) { return t(context); }); @@ -116037,6 +116092,7 @@ var ts; // prevent modification of the lexical environment. state = 2 /* TransformationState.Completed */; ts.performance.mark("afterTransform"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("transformTime", "beforeTransform", "afterTransform"); return { transformed: transformed, @@ -116630,10 +116686,12 @@ var ts; var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit; var bundleBuildInfo; var emitSkipped = false; + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.EMIT_FILES); // Emit each output file enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile); exit(); + ts.MemoryDotting.stopRecordStage(recordInfo); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -116985,8 +117043,6 @@ var ts; getAnnotationObjectLiteralEvaluatedProps: ts.notImplemented, getAnnotationPropertyEvaluatedInitializer: ts.notImplemented, getAnnotationPropertyInferredType: ts.notImplemented, - setAnnotationDeclarationUniquePrefix: ts.notImplemented, - getAnnotationDeclarationUniquePrefix: ts.notImplemented, isReferredToAnnotation: ts.notImplemented, }; function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) { @@ -123250,6 +123306,7 @@ var ts; var sourceFilesFoundSearchingNodeModules = new ts.Map(); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* tracing.Phase.Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeProgram"); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.BEFORE_PROGRAM); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); var skipDefaultLib = options.noLib; @@ -123541,6 +123598,7 @@ var ts; }); verifyCompilerOptions(); ts.performance.mark("afterProgram"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Program", "beforeProgram", "afterProgram"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; @@ -172746,13 +172804,12 @@ var ts; while (pos < end) { var token = ts.scanner.scan(); var textPos = ts.scanner.getTextPos(); - if (!ts.isSourceFile(parent) || !ts.isInMarkedKitImport(parent, pos, textPos)) { - if (textPos <= end) { - if (token === 79 /* SyntaxKind.Identifier */) { - ts.Debug.fail("Did not expect ".concat(ts.Debug.formatSyntaxKind(parent.kind), " to have an Identifier in its trivia")); - } - nodes.push(createNode(token, pos, textPos, parent)); + var isSourceFileOrInMarkedKitImport = !ts.isSourceFile(parent) || !ts.isInMarkedKitImport(parent, pos, textPos); + if (isSourceFileOrInMarkedKitImport && textPos <= end) { + if (token === 79 /* SyntaxKind.Identifier */) { + ts.Debug.fail("Did not expect ".concat(ts.Debug.formatSyntaxKind(parent.kind), " to have an Identifier in its trivia")); } + nodes.push(createNode(token, pos, textPos, parent)); } pos = textPos; if (token === 1 /* SyntaxKind.EndOfFileToken */) { @@ -195336,25 +195393,56 @@ var ts; (((_c = tsType.getSymbol()) === null || _c === void 0 ? void 0 : _c.getName()) === 'ReadonlyArray')); } Utils.isReadonlyArrayType = isReadonlyArrayType; - function isTypedArray(tsType) { + function isConcatArrayType(tsType) { + var _a, _b, _c; + return (isStdLibraryType(tsType) && + isTypeReference(tsType) && + ((_a = tsType.typeArguments) === null || _a === void 0 ? void 0 : _a.length) === 1 && + ((_b = tsType.target.typeParameters) === null || _b === void 0 ? void 0 : _b.length) === 1 && + (((_c = tsType.getSymbol()) === null || _c === void 0 ? void 0 : _c.getName()) === 'ConcatArray')); + } + Utils.isConcatArrayType = isConcatArrayType; + function isArrayLikeType(tsType) { + var _a, _b, _c; + return (isStdLibraryType(tsType) && + isTypeReference(tsType) && + ((_a = tsType.typeArguments) === null || _a === void 0 ? void 0 : _a.length) === 1 && + ((_b = tsType.target.typeParameters) === null || _b === void 0 ? void 0 : _b.length) === 1 && + (((_c = tsType.getSymbol()) === null || _c === void 0 ? void 0 : _c.getName()) === 'ArrayLike')); + } + Utils.isArrayLikeType = isArrayLikeType; + function isTypedArray(tsType, allowTypeArrays) { var symbol = tsType.symbol; if (!symbol) { return false; } var name = typeChecker.getFullyQualifiedName(symbol); - if (isGlobalSymbol(symbol) && Utils.TYPED_ARRAYS.includes(name)) { + if (isGlobalSymbol(symbol) && allowTypeArrays.includes(name)) { return true; } var decl = getDeclaration(symbol); return (!!decl && isArkTSCollectionsClassOrInterfaceDeclaration(decl) && - Utils.TYPED_ARRAYS.includes(symbol.getName())); + allowTypeArrays.includes(symbol.getName())); } Utils.isTypedArray = isTypedArray; function isArray(tsType) { - return isGenericArrayType(tsType) || isReadonlyArrayType(tsType) || isTypedArray(tsType); + return isGenericArrayType(tsType) || isReadonlyArrayType(tsType) || isTypedArray(tsType, Utils.TYPED_ARRAYS); } Utils.isArray = isArray; + function isCollectionArrayType(tsType) { + return isTypedArray(tsType, Utils.TYPED_COLLECTIONS); + } + Utils.isCollectionArrayType = isCollectionArrayType; + function isIndexableArray(tsType) { + return (isGenericArrayType(tsType) || + isReadonlyArrayType(tsType) || + isConcatArrayType(tsType) || + isArrayLikeType(tsType) || + isTypedArray(tsType, Utils.TYPED_ARRAYS) || + isTypedArray(tsType, Utils.TYPED_COLLECTIONS)); + } + Utils.isIndexableArray = isIndexableArray; function isTuple(tsType) { return isTypeReference(tsType) && !!(tsType.objectFlags & 8 /* ts.ObjectFlags.Tuple */); } @@ -196109,17 +196197,20 @@ var ts; "lib.es2022.sharedmemory.d.ts", "lib.es2022.string.d.ts", "lib.es2022.regexp.d.ts", "lib.es2023.array.d.ts", ]; Utils.TYPED_ARRAYS = [ - "Int8Array", - "Uint8Array", - "Uint8ClampedArray", - "Int16Array", - "Uint16Array", - "Int32Array", - "Uint32Array", - "Float32Array", - "Float64Array", - "BigInt64Array", - "BigUint64Array", + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array', + ]; + Utils.TYPED_COLLECTIONS = [ + 'BitVector' ]; var parentSymbolCache = new ts.Map(); function getParentSymbolName(symbol) { @@ -198907,6 +198998,9 @@ var ts; return; } } + if ((tsIdentSym.flags & 268435456 /* SymbolFlags.Annotation */) !== 0) { + return; + } if (tsIdentSym.flags & 512 /* SymbolFlags.ValueModule */) { this.incrementCounters(tsIdentifier, FaultID.NamespaceAsObject); } @@ -198970,7 +199064,7 @@ var ts; } return (ArkTSLinter_1_1.Utils.isLibraryType(type) || ArkTSLinter_1_1.Utils.isAnyType(type) || - ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isArray) || + ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isIndexableArray) || ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isTuple) || ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isStdRecordType) || ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isStringType) || @@ -199322,7 +199416,8 @@ var ts; var spreadExprType = ArkTSLinter_1_1.Utils.getTypeOrTypeConstraintAtLocation(node.expression); if (spreadExprType) { if (ts.isCallLikeExpression(node.parent) || ts.isArrayLiteralExpression(node.parent)) { - if (ArkTSLinter_1_1.Utils.isOrDerivedFrom(spreadExprType, ArkTSLinter_1_1.Utils.isArray)) { + if (ArkTSLinter_1_1.Utils.isOrDerivedFrom(spreadExprType, ArkTSLinter_1_1.Utils.isArray) || + ArkTSLinter_1_1.Utils.isOrDerivedFrom(spreadExprType, ArkTSLinter_1_1.Utils.isCollectionArrayType)) { return; } } diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 40cd06e4080f1e4b1a5fe19e9bf6c7e136580bfb..8549ac7989321380d8127e8fa4c1c5a0f6364a0e 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -4600,6 +4600,24 @@ declare namespace ts { export let sys: System; export {}; } +declare namespace ts { + namespace MemoryDotting { + interface RecordInfo { + recordStage: string; + recordIndex: number; + } + const BINDE_SOURCE_FILE = "binder(bindSourceFile: Bind)"; + const CHECK_SOURCE_FILE = "checker(checkSourceFile: Check)"; + const EMIT_FILES = "emitter(emitFiles: EmitEachOutputFile)"; + const CREATE_SORUCE_FILE_PARSE = "parser(createSourceFile: Parse)"; + const BEFORE_PROGRAM = "program(createProgram: beforeProgram)"; + const TRANSFORM = "transformer(transformNodes: Transform)"; + function recordStage(stage: string): RecordInfo | null; + function stopRecordStage(recordInfo: RecordInfo | null): void; + function setMemoryDottingCallBack(recordCallback: (stage: string) => RecordInfo, stopCallback: (recordInfo: RecordInfo) => void): void; + function clearCallBack(): void; + } +} declare namespace ts { type ErrorCallback = (message: DiagnosticMessage, length: number) => void; interface Scanner { @@ -5468,8 +5486,8 @@ declare namespace ts { function pathContainsOHModules(path: string): boolean; function choosePathContainsModules(packageManagerType: string | undefined, fileName: string): boolean; function getTypeExportImportAndConstEnumTransformer(context: TransformationContext): (node: SourceFile) => SourceFile; - function getAnnotationTransformer(relativeFilePath: string): TransformerFactory; - function transformAnnotation(context: TransformationContext, relativeFilePath: string): (node: SourceFile) => SourceFile; + function getAnnotationTransformer(): TransformerFactory; + function transformAnnotation(context: TransformationContext): (node: SourceFile) => SourceFile; /** * Add 'type' flag to import/export when import/export an type member. * Replace const enum with number and string literal. @@ -9380,8 +9398,12 @@ declare namespace ts { function isTypeSymbol(symbol: Symbol | undefined): boolean; function isGenericArrayType(tsType: Type): tsType is TypeReference; function isReadonlyArrayType(tsType: Type): boolean; - function isTypedArray(tsType: ts.Type): boolean; + function isConcatArrayType(tsType: Type): boolean; + function isArrayLikeType(tsType: Type): boolean; + function isTypedArray(tsType: ts.Type, allowTypeArrays: string[]): boolean; function isArray(tsType: ts.Type): boolean; + function isCollectionArrayType(tsType: ts.Type): boolean; + function isIndexableArray(tsType: ts.Type): boolean; function isTuple(tsType: ts.Type): boolean; function isOrDerivedFrom(tsType: ts.Type, checkType: CheckType, checkedBaseTypes?: Set): boolean; function isTypeReference(tsType: Type): tsType is TypeReference; @@ -9436,6 +9458,7 @@ declare namespace ts { const NON_RETURN_FUNCTION_DECORATORS: string[]; const STANDARD_LIBRARIES: string[]; const TYPED_ARRAYS: string[]; + const TYPED_COLLECTIONS: string[]; function getParentSymbolName(symbol: Symbol): string | undefined; function isGlobalSymbol(symbol: Symbol): boolean; function isSymbolAPI(symbol: Symbol): boolean; diff --git a/lib/typescript.js b/lib/typescript.js index 185992062a38ee9e0f557c1fc48a2b667313bf4b..aaf74f1c243ae17ebb5f508e6633c2c66a283a41 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -10194,6 +10194,65 @@ var ts; Enable_support_of_ETS_annotations: diag(28038, ts.DiagnosticCategory.Message, "Enable_support_of_ETS_annotations_28038", "Enable support of ETS annotations"), }; })(ts || (ts = {})); +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * 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. + */ +var ts; +(function (ts) { + var MemoryDotting; + (function (MemoryDotting) { + MemoryDotting.BINDE_SOURCE_FILE = 'binder(bindSourceFile: Bind)'; + MemoryDotting.CHECK_SOURCE_FILE = 'checker(checkSourceFile: Check)'; + MemoryDotting.EMIT_FILES = 'emitter(emitFiles: EmitEachOutputFile)'; + MemoryDotting.CREATE_SORUCE_FILE_PARSE = 'parser(createSourceFile: Parse)'; + MemoryDotting.BEFORE_PROGRAM = 'program(createProgram: beforeProgram)'; + MemoryDotting.TRANSFORM = 'transformer(transformNodes: Transform)'; + var memoryDottingCallback; + var memoryDottingStopCallback; + function recordStage(stage) { + if (memoryDottingCallback !== undefined) { + return memoryDottingCallback(stage); + } + return null; + } + MemoryDotting.recordStage = recordStage; + function stopRecordStage(recordInfo) { + if (memoryDottingStopCallback !== undefined && recordInfo !== null) { + memoryDottingStopCallback(recordInfo); + } + } + MemoryDotting.stopRecordStage = stopRecordStage; + function setMemoryDottingCallBack(recordCallback, stopCallback) { + if (recordCallback) { + memoryDottingCallback = recordCallback; + } + if (stopCallback) { + memoryDottingStopCallback = stopCallback; + } + } + MemoryDotting.setMemoryDottingCallBack = setMemoryDottingCallBack; + function clearCallBack() { + if (memoryDottingCallback !== undefined) { + memoryDottingCallback = undefined; + } + if (memoryDottingStopCallback !== undefined) { + memoryDottingStopCallback = undefined; + } + } + MemoryDotting.clearCallBack = clearCallBack; + })(MemoryDotting = ts.MemoryDotting || (ts.MemoryDotting = {})); +})(ts || (ts = {})); var ts; (function (ts) { var _a; @@ -32553,6 +32612,7 @@ var ts; function createSourceFile(fileName, sourceText, languageVersionOrOptions, setParentNodes, scriptKind, options) { if (setParentNodes === void 0) { setParentNodes = false; } ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* tracing.Phase.Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.CREATE_SORUCE_FILE_PARSE); ts.performance.mark("beforeParse"); var result; sourceFileCompilerOptions = options !== null && options !== void 0 ? options : ts.defaultInitCompilerOptions; @@ -32570,6 +32630,7 @@ var ts; } ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Parse", "beforeParse", "afterParse"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; @@ -46744,7 +46805,7 @@ var ts; (function (ts) { /* @internal */ // Required for distinguishing annotations and decorators in other code analysis tools - ts.annotationMagicNamePrefix = "#"; + ts.annotationMagicNamePrefix = "__$$ETS_ANNOTATION$$__"; /* @internal */ function isInEtsFile(node) { var _a; @@ -47152,13 +47213,12 @@ var ts; return transformTypeExportImportAndConstEnumInTypeScript(context); } ts.getTypeExportImportAndConstEnumTransformer = getTypeExportImportAndConstEnumTransformer; - function getAnnotationTransformer(relativeFilePath) { - return function (context) { return transformAnnotation(context, relativeFilePath); }; + function getAnnotationTransformer() { + return function (context) { return transformAnnotation(context); }; } ts.getAnnotationTransformer = getAnnotationTransformer; - function transformAnnotation(context, relativeFilePath) { + function transformAnnotation(context) { var resolver = context.getEmitResolver(); - var annotationUniqueNamePrefix = getAnnotationUniqueNamePrefixFromFilePath(relativeFilePath); return transformSourceFile; function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -47186,19 +47246,14 @@ var ts; } } function visitAnnotationDeclaration(node) { - resolver.setAnnotationDeclarationUniquePrefix(node, annotationUniqueNamePrefix); - // Add unique prefix for AnnotationDeclaration. For example, - // @interface Anno {} --- > @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno {} - var uniqueName = addUniquePrefixToAnnotationNameIdentifier(node.name, annotationUniqueNamePrefix); - ts.Debug.assert(ts.isIdentifier(uniqueName)); // Add explicit type annotation and initializer. For example, - // @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno { + // @interface Anno { // a = 10 + 5 // } // // will be transformed to // - // @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno { + // @interface Anno { // a: number = 15 // } var members = node.members.map(function (node) { @@ -47206,7 +47261,7 @@ var ts; var initializer = resolver.getAnnotationPropertyEvaluatedInitializer(node); return ts.factory.updateAnnotationPropertyDeclaration(node, node.name, type, initializer); }); - return ts.factory.updateAnnotationDeclaration(node, node.modifiers, uniqueName, members); + return ts.factory.updateAnnotationDeclaration(node, node.modifiers, node.name, members); } function visitAnnotation(node) { if (!node.annotationDeclaration) { @@ -47223,28 +47278,9 @@ var ts; // // and // - // Add unique prefix for annotation name. For example, - // @myModule.Anno({a: 10, b: "abc"}) --- > @myModule.e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855({a: 10, b: "abc"}) - // - // and - // // Add the magic prefix for annotation name. For example, - // @myModule.Anno({a: 10, b: "abc"}) --- > @#myModule.e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855({a: 10, b: "abc"}) - return ts.factory.updateDecorator(node, addMagicPrefixToAnnotationNameIdentifier(addUniquePrefixToAnnotationNameIdentifier(addDefaultValuesIntoAnnotationObjectLiteral(node), resolver.getAnnotationDeclarationUniquePrefix(node.annotationDeclaration)))); - } - function addUniquePrefixToAnnotationNameIdentifier(expr, prefix) { - switch (expr.kind) { - case 79 /* SyntaxKind.Identifier */: - return ts.factory.createIdentifier(prefix + expr.escapedText); - case 211 /* SyntaxKind.PropertyAccessExpression */: - var propAccessExpr = expr; - return ts.factory.updatePropertyAccessExpression(propAccessExpr, propAccessExpr.expression, addUniquePrefixToAnnotationNameIdentifier(propAccessExpr.name, prefix)); - case 213 /* SyntaxKind.CallExpression */: - var callExpr = expr; - return ts.factory.updateCallExpression(callExpr, addUniquePrefixToAnnotationNameIdentifier(callExpr.expression, prefix), callExpr.typeArguments, callExpr.arguments); - default: - return expr; - } + // @myModule.Anno({a: 10, b: "abc"}) --- > @#myModule.Anno({a: 10, b: "abc"}) + return ts.factory.updateDecorator(node, addMagicPrefixToAnnotationNameIdentifier(addDefaultValuesIntoAnnotationObjectLiteral(node))); } function addMagicPrefixToAnnotationNameIdentifier(expr) { switch (expr.kind) { @@ -47303,9 +47339,6 @@ var ts; } ts.Debug.fail(); } - function getAnnotationUniqueNamePrefixFromFilePath(filePath) { - return ts.sys.createHash(filePath); - } } ts.transformAnnotation = transformAnnotation; /** @@ -47593,9 +47626,14 @@ var ts; var output; var lineStart; var linePos; + var lineCount; + // If the last character of string is the one of below chars, there is no need to write space again. + var noSpaceTrailingChars = new ts.Set([' ', ';', ',', '(', ')', '{', '}']); function updateLineCountAndPosFor(s) { var lineStartsOfS = ts.computeLineStarts(s); if (lineStartsOfS.length > 1) { + // 1: The first element of the lineStartsOfS + lineCount = lineCount + lineStartsOfS.length - 1; linePos = output.length - s.length + ts.last(lineStartsOfS); lineStart = (linePos - output.length) === 0; } @@ -47619,9 +47657,15 @@ var ts; output = ""; lineStart = true; linePos = 0; + lineCount = 0; } + // This method is used to write indentation and line breaks. If the string is blank, the writing is skipped. + // In addition, this method can be called to write comments and code in bundle mode, but obfuscation is not in bundle mode. function rawWrite(s) { if (s !== undefined) { + if ((lineStart || endsWithNoSpaceTrailingChar(output)) && s.trim().length === 0) { + return; + } output += s; updateLineCountAndPosFor(s); } @@ -47632,10 +47676,16 @@ var ts; } } function writeLine(force) { - if (!lineStart || force) { - output += space; - linePos = output.length; + if (!force && (lineStart || endsWithNoSpaceTrailingChar(output))) { + return; } + output += space; + lineStart = false; + } + function endsWithNoSpaceTrailingChar(input) { + // Get the last character of a string. + var lastChar = input.charAt(input.length - 1); + return noSpaceTrailingChars.has(lastChar); } function getTextPosWithWriteLine() { return lineStart ? output.length : (output.length + space.length); @@ -47650,7 +47700,7 @@ var ts; decreaseIndent: ts.noop, getIndent: function () { return 0; }, getTextPos: function () { return output.length; }, - getLine: function () { return 0; }, + getLine: function () { return lineCount; }, getColumn: function () { return lineStart ? 0 : output.length - linePos; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, @@ -47692,7 +47742,7 @@ var ts; return (ts.isIdentifier(nameExpr) && nameExpr.escapedText.toString() === 'Sendable'); } ts.isSendableFunctionOrType = isSendableFunctionOrType; - var JSON_SUFFIX = ".json"; + var JSON_SUFFIX = '.json'; var KIT_PREFIX = '@kit.'; var DEFAULT_KEYWORD = 'default'; var ETS_DECLARATION = '.d.ets'; @@ -47804,7 +47854,7 @@ var ts; '@kit.AccountKit', '@kit.MapKit', '@kit.Penkit', '@kit.ScenarioFusionKit', '@kit.ServiceCollaborationKit', '@kit.SpeechKit', '@kit.VisionKit', ]); - function InWhiteList(moduleSpecifierText, importName, inEtsContext) { + function inWhiteList(moduleSpecifierText, importName, inEtsContext) { if (whiteListForErrorSymbol.some(function (info) { return (info.kitName === moduleSpecifierText && info.symbolName === importName); })) { return true; } @@ -47838,7 +47888,7 @@ var ts; } var importName = ts.unescapeLeadingUnderscores(element.propertyName ? element.propertyName.escapedText : element.name.escapedText); var aliasName = element.name; - if (InWhiteList(moduleSpecifierText, importName, inEtsContext)) { + if (inWhiteList(moduleSpecifierText, importName, inEtsContext)) { hasError_1 = true; return; } @@ -48052,11 +48102,13 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.BINDE_SOURCE_FILE); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Bind", "beforeBind", "afterBind"); } ts.bindSourceFile = bindSourceFile; @@ -75451,7 +75503,8 @@ var ts; return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || node.kind === 271 /* SyntaxKind.ModuleBlock */ || node.kind === 314 /* SyntaxKind.SourceFile */ || - node.kind === 171 /* SyntaxKind.PropertyDeclaration */; + node.kind === 171 /* SyntaxKind.PropertyDeclaration */ || + node.kind === 172 /* SyntaxKind.AnnotationPropertyDeclaration */; }); } // Check if a parameter or catch variable is assigned anywhere @@ -85186,6 +85239,9 @@ var ts; if (initVal === undefined || initValType === errorType) { return undefined; } + if (isArrayType(initValType) && !Array.isArray(initVal)) { + return undefined; + } if (typeof initVal === "number") { return ts.factory.createNumericLiteral(initVal); } @@ -85218,12 +85274,14 @@ var ts; args.push(ts.factory.createNumericLiteral(3)); } } - return ts.factory.createNewExpression(ts.factory.createIdentifier(typeToString(initValType, /*enclosingDeclaration*/ undefined, 2 /* TypeFormatFlags.WriteArrayAsGenericType */)), - /*typeArguments*/ undefined, args); + return ts.factory.createNewExpression(ts.factory.createIdentifier("Array"), [nodeBuilder.typeToTypeNode(elemType)], args); } var result = new Array(initVal.length); for (var i = 0; i < initVal.length; ++i) { result[i] = annotationEvaluatedValueToExpr(initVal[i], elemType); + if (result[i] === undefined) { + return undefined; + } } return ts.factory.createArrayLiteralExpression(result); } @@ -91399,6 +91457,7 @@ var ts; } function checkSourceFile(node) { ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* tracing.Phase.Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.CHECK_SOURCE_FILE); ts.performance.mark("beforeCheck"); if (host.getFileCheckedModuleInfo) { jsDocFileCheckInfo = host.getFileCheckedModuleInfo(node.fileName); @@ -91406,6 +91465,7 @@ var ts; } checkSourceFileWorker(node); ts.performance.mark("afterCheck"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Check", "beforeCheck", "afterCheck"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } @@ -92919,12 +92979,6 @@ var ts; getAnnotationPropertyInferredType: function (node) { return getNodeLinks(node).annotationPropertyInferredType; }, - setAnnotationDeclarationUniquePrefix: function (node, prefix) { - getNodeLinks(node).annotationDeclarationUniquePrefix = prefix; - }, - getAnnotationDeclarationUniquePrefix: function (node) { - return getNodeLinks(node).annotationDeclarationUniquePrefix; - }, isReferredToAnnotation: function (node) { return getNodeLinks(node).exportOrImportRefersToAnnotation; } @@ -116005,6 +116059,7 @@ var ts; var node = nodes_2[_i]; ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); } + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.TRANSFORM); ts.performance.mark("beforeTransform"); // Chain together and initialize each transformer. var transformersWithContext = transformers.map(function (t) { return t(context); }); @@ -116028,6 +116083,7 @@ var ts; // prevent modification of the lexical environment. state = 2 /* TransformationState.Completed */; ts.performance.mark("afterTransform"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("transformTime", "beforeTransform", "afterTransform"); return { transformed: transformed, @@ -116621,10 +116677,12 @@ var ts; var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit; var bundleBuildInfo; var emitSkipped = false; + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.EMIT_FILES); // Emit each output file enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile); exit(); + ts.MemoryDotting.stopRecordStage(recordInfo); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -116976,8 +117034,6 @@ var ts; getAnnotationObjectLiteralEvaluatedProps: ts.notImplemented, getAnnotationPropertyEvaluatedInitializer: ts.notImplemented, getAnnotationPropertyInferredType: ts.notImplemented, - setAnnotationDeclarationUniquePrefix: ts.notImplemented, - getAnnotationDeclarationUniquePrefix: ts.notImplemented, isReferredToAnnotation: ts.notImplemented, }; function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) { @@ -123241,6 +123297,7 @@ var ts; var sourceFilesFoundSearchingNodeModules = new ts.Map(); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* tracing.Phase.Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeProgram"); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.BEFORE_PROGRAM); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); var skipDefaultLib = options.noLib; @@ -123532,6 +123589,7 @@ var ts; }); verifyCompilerOptions(); ts.performance.mark("afterProgram"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Program", "beforeProgram", "afterProgram"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; @@ -172737,13 +172795,12 @@ var ts; while (pos < end) { var token = ts.scanner.scan(); var textPos = ts.scanner.getTextPos(); - if (!ts.isSourceFile(parent) || !ts.isInMarkedKitImport(parent, pos, textPos)) { - if (textPos <= end) { - if (token === 79 /* SyntaxKind.Identifier */) { - ts.Debug.fail("Did not expect ".concat(ts.Debug.formatSyntaxKind(parent.kind), " to have an Identifier in its trivia")); - } - nodes.push(createNode(token, pos, textPos, parent)); + var isSourceFileOrInMarkedKitImport = !ts.isSourceFile(parent) || !ts.isInMarkedKitImport(parent, pos, textPos); + if (isSourceFileOrInMarkedKitImport && textPos <= end) { + if (token === 79 /* SyntaxKind.Identifier */) { + ts.Debug.fail("Did not expect ".concat(ts.Debug.formatSyntaxKind(parent.kind), " to have an Identifier in its trivia")); } + nodes.push(createNode(token, pos, textPos, parent)); } pos = textPos; if (token === 1 /* SyntaxKind.EndOfFileToken */) { @@ -184430,25 +184487,56 @@ var ts; (((_c = tsType.getSymbol()) === null || _c === void 0 ? void 0 : _c.getName()) === 'ReadonlyArray')); } Utils.isReadonlyArrayType = isReadonlyArrayType; - function isTypedArray(tsType) { + function isConcatArrayType(tsType) { + var _a, _b, _c; + return (isStdLibraryType(tsType) && + isTypeReference(tsType) && + ((_a = tsType.typeArguments) === null || _a === void 0 ? void 0 : _a.length) === 1 && + ((_b = tsType.target.typeParameters) === null || _b === void 0 ? void 0 : _b.length) === 1 && + (((_c = tsType.getSymbol()) === null || _c === void 0 ? void 0 : _c.getName()) === 'ConcatArray')); + } + Utils.isConcatArrayType = isConcatArrayType; + function isArrayLikeType(tsType) { + var _a, _b, _c; + return (isStdLibraryType(tsType) && + isTypeReference(tsType) && + ((_a = tsType.typeArguments) === null || _a === void 0 ? void 0 : _a.length) === 1 && + ((_b = tsType.target.typeParameters) === null || _b === void 0 ? void 0 : _b.length) === 1 && + (((_c = tsType.getSymbol()) === null || _c === void 0 ? void 0 : _c.getName()) === 'ArrayLike')); + } + Utils.isArrayLikeType = isArrayLikeType; + function isTypedArray(tsType, allowTypeArrays) { var symbol = tsType.symbol; if (!symbol) { return false; } var name = typeChecker.getFullyQualifiedName(symbol); - if (isGlobalSymbol(symbol) && Utils.TYPED_ARRAYS.includes(name)) { + if (isGlobalSymbol(symbol) && allowTypeArrays.includes(name)) { return true; } var decl = getDeclaration(symbol); return (!!decl && isArkTSCollectionsClassOrInterfaceDeclaration(decl) && - Utils.TYPED_ARRAYS.includes(symbol.getName())); + allowTypeArrays.includes(symbol.getName())); } Utils.isTypedArray = isTypedArray; function isArray(tsType) { - return isGenericArrayType(tsType) || isReadonlyArrayType(tsType) || isTypedArray(tsType); + return isGenericArrayType(tsType) || isReadonlyArrayType(tsType) || isTypedArray(tsType, Utils.TYPED_ARRAYS); } Utils.isArray = isArray; + function isCollectionArrayType(tsType) { + return isTypedArray(tsType, Utils.TYPED_COLLECTIONS); + } + Utils.isCollectionArrayType = isCollectionArrayType; + function isIndexableArray(tsType) { + return (isGenericArrayType(tsType) || + isReadonlyArrayType(tsType) || + isConcatArrayType(tsType) || + isArrayLikeType(tsType) || + isTypedArray(tsType, Utils.TYPED_ARRAYS) || + isTypedArray(tsType, Utils.TYPED_COLLECTIONS)); + } + Utils.isIndexableArray = isIndexableArray; function isTuple(tsType) { return isTypeReference(tsType) && !!(tsType.objectFlags & 8 /* ts.ObjectFlags.Tuple */); } @@ -185203,17 +185291,20 @@ var ts; "lib.es2022.sharedmemory.d.ts", "lib.es2022.string.d.ts", "lib.es2022.regexp.d.ts", "lib.es2023.array.d.ts", ]; Utils.TYPED_ARRAYS = [ - "Int8Array", - "Uint8Array", - "Uint8ClampedArray", - "Int16Array", - "Uint16Array", - "Int32Array", - "Uint32Array", - "Float32Array", - "Float64Array", - "BigInt64Array", - "BigUint64Array", + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array', + ]; + Utils.TYPED_COLLECTIONS = [ + 'BitVector' ]; var parentSymbolCache = new ts.Map(); function getParentSymbolName(symbol) { @@ -188001,6 +188092,9 @@ var ts; return; } } + if ((tsIdentSym.flags & 268435456 /* SymbolFlags.Annotation */) !== 0) { + return; + } if (tsIdentSym.flags & 512 /* SymbolFlags.ValueModule */) { this.incrementCounters(tsIdentifier, FaultID.NamespaceAsObject); } @@ -188064,7 +188158,7 @@ var ts; } return (ArkTSLinter_1_1.Utils.isLibraryType(type) || ArkTSLinter_1_1.Utils.isAnyType(type) || - ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isArray) || + ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isIndexableArray) || ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isTuple) || ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isStdRecordType) || ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isStringType) || @@ -188416,7 +188510,8 @@ var ts; var spreadExprType = ArkTSLinter_1_1.Utils.getTypeOrTypeConstraintAtLocation(node.expression); if (spreadExprType) { if (ts.isCallLikeExpression(node.parent) || ts.isArrayLiteralExpression(node.parent)) { - if (ArkTSLinter_1_1.Utils.isOrDerivedFrom(spreadExprType, ArkTSLinter_1_1.Utils.isArray)) { + if (ArkTSLinter_1_1.Utils.isOrDerivedFrom(spreadExprType, ArkTSLinter_1_1.Utils.isArray) || + ArkTSLinter_1_1.Utils.isOrDerivedFrom(spreadExprType, ArkTSLinter_1_1.Utils.isCollectionArrayType)) { return; } } diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 85e82a69ad88bb85bb6d120fac8b98ff68b1ba3b..f3cd6bac62360d2333573b11e992a612c136a2a9 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -4600,6 +4600,24 @@ declare namespace ts { export let sys: System; export {}; } +declare namespace ts { + namespace MemoryDotting { + interface RecordInfo { + recordStage: string; + recordIndex: number; + } + const BINDE_SOURCE_FILE = "binder(bindSourceFile: Bind)"; + const CHECK_SOURCE_FILE = "checker(checkSourceFile: Check)"; + const EMIT_FILES = "emitter(emitFiles: EmitEachOutputFile)"; + const CREATE_SORUCE_FILE_PARSE = "parser(createSourceFile: Parse)"; + const BEFORE_PROGRAM = "program(createProgram: beforeProgram)"; + const TRANSFORM = "transformer(transformNodes: Transform)"; + function recordStage(stage: string): RecordInfo | null; + function stopRecordStage(recordInfo: RecordInfo | null): void; + function setMemoryDottingCallBack(recordCallback: (stage: string) => RecordInfo, stopCallback: (recordInfo: RecordInfo) => void): void; + function clearCallBack(): void; + } +} declare namespace ts { type ErrorCallback = (message: DiagnosticMessage, length: number) => void; interface Scanner { @@ -5468,8 +5486,8 @@ declare namespace ts { function pathContainsOHModules(path: string): boolean; function choosePathContainsModules(packageManagerType: string | undefined, fileName: string): boolean; function getTypeExportImportAndConstEnumTransformer(context: TransformationContext): (node: SourceFile) => SourceFile; - function getAnnotationTransformer(relativeFilePath: string): TransformerFactory; - function transformAnnotation(context: TransformationContext, relativeFilePath: string): (node: SourceFile) => SourceFile; + function getAnnotationTransformer(): TransformerFactory; + function transformAnnotation(context: TransformationContext): (node: SourceFile) => SourceFile; /** * Add 'type' flag to import/export when import/export an type member. * Replace const enum with number and string literal. @@ -9380,8 +9398,12 @@ declare namespace ts { function isTypeSymbol(symbol: Symbol | undefined): boolean; function isGenericArrayType(tsType: Type): tsType is TypeReference; function isReadonlyArrayType(tsType: Type): boolean; - function isTypedArray(tsType: ts.Type): boolean; + function isConcatArrayType(tsType: Type): boolean; + function isArrayLikeType(tsType: Type): boolean; + function isTypedArray(tsType: ts.Type, allowTypeArrays: string[]): boolean; function isArray(tsType: ts.Type): boolean; + function isCollectionArrayType(tsType: ts.Type): boolean; + function isIndexableArray(tsType: ts.Type): boolean; function isTuple(tsType: ts.Type): boolean; function isOrDerivedFrom(tsType: ts.Type, checkType: CheckType, checkedBaseTypes?: Set): boolean; function isTypeReference(tsType: Type): tsType is TypeReference; @@ -9436,6 +9458,7 @@ declare namespace ts { const NON_RETURN_FUNCTION_DECORATORS: string[]; const STANDARD_LIBRARIES: string[]; const TYPED_ARRAYS: string[]; + const TYPED_COLLECTIONS: string[]; function getParentSymbolName(symbol: Symbol): string | undefined; function isGlobalSymbol(symbol: Symbol): boolean; function isSymbolAPI(symbol: Symbol): boolean; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 3faa07cc6e597aff466cd930239f4509dbd9bdce..30be59ad8a44b4e786182c7c719c68376f23647c 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -10194,6 +10194,65 @@ var ts; Enable_support_of_ETS_annotations: diag(28038, ts.DiagnosticCategory.Message, "Enable_support_of_ETS_annotations_28038", "Enable support of ETS annotations"), }; })(ts || (ts = {})); +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * 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. + */ +var ts; +(function (ts) { + var MemoryDotting; + (function (MemoryDotting) { + MemoryDotting.BINDE_SOURCE_FILE = 'binder(bindSourceFile: Bind)'; + MemoryDotting.CHECK_SOURCE_FILE = 'checker(checkSourceFile: Check)'; + MemoryDotting.EMIT_FILES = 'emitter(emitFiles: EmitEachOutputFile)'; + MemoryDotting.CREATE_SORUCE_FILE_PARSE = 'parser(createSourceFile: Parse)'; + MemoryDotting.BEFORE_PROGRAM = 'program(createProgram: beforeProgram)'; + MemoryDotting.TRANSFORM = 'transformer(transformNodes: Transform)'; + var memoryDottingCallback; + var memoryDottingStopCallback; + function recordStage(stage) { + if (memoryDottingCallback !== undefined) { + return memoryDottingCallback(stage); + } + return null; + } + MemoryDotting.recordStage = recordStage; + function stopRecordStage(recordInfo) { + if (memoryDottingStopCallback !== undefined && recordInfo !== null) { + memoryDottingStopCallback(recordInfo); + } + } + MemoryDotting.stopRecordStage = stopRecordStage; + function setMemoryDottingCallBack(recordCallback, stopCallback) { + if (recordCallback) { + memoryDottingCallback = recordCallback; + } + if (stopCallback) { + memoryDottingStopCallback = stopCallback; + } + } + MemoryDotting.setMemoryDottingCallBack = setMemoryDottingCallBack; + function clearCallBack() { + if (memoryDottingCallback !== undefined) { + memoryDottingCallback = undefined; + } + if (memoryDottingStopCallback !== undefined) { + memoryDottingStopCallback = undefined; + } + } + MemoryDotting.clearCallBack = clearCallBack; + })(MemoryDotting = ts.MemoryDotting || (ts.MemoryDotting = {})); +})(ts || (ts = {})); var ts; (function (ts) { var _a; @@ -32553,6 +32612,7 @@ var ts; function createSourceFile(fileName, sourceText, languageVersionOrOptions, setParentNodes, scriptKind, options) { if (setParentNodes === void 0) { setParentNodes = false; } ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* tracing.Phase.Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.CREATE_SORUCE_FILE_PARSE); ts.performance.mark("beforeParse"); var result; sourceFileCompilerOptions = options !== null && options !== void 0 ? options : ts.defaultInitCompilerOptions; @@ -32570,6 +32630,7 @@ var ts; } ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Parse", "beforeParse", "afterParse"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; @@ -46744,7 +46805,7 @@ var ts; (function (ts) { /* @internal */ // Required for distinguishing annotations and decorators in other code analysis tools - ts.annotationMagicNamePrefix = "#"; + ts.annotationMagicNamePrefix = "__$$ETS_ANNOTATION$$__"; /* @internal */ function isInEtsFile(node) { var _a; @@ -47152,13 +47213,12 @@ var ts; return transformTypeExportImportAndConstEnumInTypeScript(context); } ts.getTypeExportImportAndConstEnumTransformer = getTypeExportImportAndConstEnumTransformer; - function getAnnotationTransformer(relativeFilePath) { - return function (context) { return transformAnnotation(context, relativeFilePath); }; + function getAnnotationTransformer() { + return function (context) { return transformAnnotation(context); }; } ts.getAnnotationTransformer = getAnnotationTransformer; - function transformAnnotation(context, relativeFilePath) { + function transformAnnotation(context) { var resolver = context.getEmitResolver(); - var annotationUniqueNamePrefix = getAnnotationUniqueNamePrefixFromFilePath(relativeFilePath); return transformSourceFile; function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -47186,19 +47246,14 @@ var ts; } } function visitAnnotationDeclaration(node) { - resolver.setAnnotationDeclarationUniquePrefix(node, annotationUniqueNamePrefix); - // Add unique prefix for AnnotationDeclaration. For example, - // @interface Anno {} --- > @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno {} - var uniqueName = addUniquePrefixToAnnotationNameIdentifier(node.name, annotationUniqueNamePrefix); - ts.Debug.assert(ts.isIdentifier(uniqueName)); // Add explicit type annotation and initializer. For example, - // @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno { + // @interface Anno { // a = 10 + 5 // } // // will be transformed to // - // @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno { + // @interface Anno { // a: number = 15 // } var members = node.members.map(function (node) { @@ -47206,7 +47261,7 @@ var ts; var initializer = resolver.getAnnotationPropertyEvaluatedInitializer(node); return ts.factory.updateAnnotationPropertyDeclaration(node, node.name, type, initializer); }); - return ts.factory.updateAnnotationDeclaration(node, node.modifiers, uniqueName, members); + return ts.factory.updateAnnotationDeclaration(node, node.modifiers, node.name, members); } function visitAnnotation(node) { if (!node.annotationDeclaration) { @@ -47223,28 +47278,9 @@ var ts; // // and // - // Add unique prefix for annotation name. For example, - // @myModule.Anno({a: 10, b: "abc"}) --- > @myModule.e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855({a: 10, b: "abc"}) - // - // and - // // Add the magic prefix for annotation name. For example, - // @myModule.Anno({a: 10, b: "abc"}) --- > @#myModule.e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855({a: 10, b: "abc"}) - return ts.factory.updateDecorator(node, addMagicPrefixToAnnotationNameIdentifier(addUniquePrefixToAnnotationNameIdentifier(addDefaultValuesIntoAnnotationObjectLiteral(node), resolver.getAnnotationDeclarationUniquePrefix(node.annotationDeclaration)))); - } - function addUniquePrefixToAnnotationNameIdentifier(expr, prefix) { - switch (expr.kind) { - case 79 /* SyntaxKind.Identifier */: - return ts.factory.createIdentifier(prefix + expr.escapedText); - case 211 /* SyntaxKind.PropertyAccessExpression */: - var propAccessExpr = expr; - return ts.factory.updatePropertyAccessExpression(propAccessExpr, propAccessExpr.expression, addUniquePrefixToAnnotationNameIdentifier(propAccessExpr.name, prefix)); - case 213 /* SyntaxKind.CallExpression */: - var callExpr = expr; - return ts.factory.updateCallExpression(callExpr, addUniquePrefixToAnnotationNameIdentifier(callExpr.expression, prefix), callExpr.typeArguments, callExpr.arguments); - default: - return expr; - } + // @myModule.Anno({a: 10, b: "abc"}) --- > @#myModule.Anno({a: 10, b: "abc"}) + return ts.factory.updateDecorator(node, addMagicPrefixToAnnotationNameIdentifier(addDefaultValuesIntoAnnotationObjectLiteral(node))); } function addMagicPrefixToAnnotationNameIdentifier(expr) { switch (expr.kind) { @@ -47303,9 +47339,6 @@ var ts; } ts.Debug.fail(); } - function getAnnotationUniqueNamePrefixFromFilePath(filePath) { - return ts.sys.createHash(filePath); - } } ts.transformAnnotation = transformAnnotation; /** @@ -47593,9 +47626,14 @@ var ts; var output; var lineStart; var linePos; + var lineCount; + // If the last character of string is the one of below chars, there is no need to write space again. + var noSpaceTrailingChars = new ts.Set([' ', ';', ',', '(', ')', '{', '}']); function updateLineCountAndPosFor(s) { var lineStartsOfS = ts.computeLineStarts(s); if (lineStartsOfS.length > 1) { + // 1: The first element of the lineStartsOfS + lineCount = lineCount + lineStartsOfS.length - 1; linePos = output.length - s.length + ts.last(lineStartsOfS); lineStart = (linePos - output.length) === 0; } @@ -47619,9 +47657,15 @@ var ts; output = ""; lineStart = true; linePos = 0; + lineCount = 0; } + // This method is used to write indentation and line breaks. If the string is blank, the writing is skipped. + // In addition, this method can be called to write comments and code in bundle mode, but obfuscation is not in bundle mode. function rawWrite(s) { if (s !== undefined) { + if ((lineStart || endsWithNoSpaceTrailingChar(output)) && s.trim().length === 0) { + return; + } output += s; updateLineCountAndPosFor(s); } @@ -47632,10 +47676,16 @@ var ts; } } function writeLine(force) { - if (!lineStart || force) { - output += space; - linePos = output.length; + if (!force && (lineStart || endsWithNoSpaceTrailingChar(output))) { + return; } + output += space; + lineStart = false; + } + function endsWithNoSpaceTrailingChar(input) { + // Get the last character of a string. + var lastChar = input.charAt(input.length - 1); + return noSpaceTrailingChars.has(lastChar); } function getTextPosWithWriteLine() { return lineStart ? output.length : (output.length + space.length); @@ -47650,7 +47700,7 @@ var ts; decreaseIndent: ts.noop, getIndent: function () { return 0; }, getTextPos: function () { return output.length; }, - getLine: function () { return 0; }, + getLine: function () { return lineCount; }, getColumn: function () { return lineStart ? 0 : output.length - linePos; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, @@ -47692,7 +47742,7 @@ var ts; return (ts.isIdentifier(nameExpr) && nameExpr.escapedText.toString() === 'Sendable'); } ts.isSendableFunctionOrType = isSendableFunctionOrType; - var JSON_SUFFIX = ".json"; + var JSON_SUFFIX = '.json'; var KIT_PREFIX = '@kit.'; var DEFAULT_KEYWORD = 'default'; var ETS_DECLARATION = '.d.ets'; @@ -47804,7 +47854,7 @@ var ts; '@kit.AccountKit', '@kit.MapKit', '@kit.Penkit', '@kit.ScenarioFusionKit', '@kit.ServiceCollaborationKit', '@kit.SpeechKit', '@kit.VisionKit', ]); - function InWhiteList(moduleSpecifierText, importName, inEtsContext) { + function inWhiteList(moduleSpecifierText, importName, inEtsContext) { if (whiteListForErrorSymbol.some(function (info) { return (info.kitName === moduleSpecifierText && info.symbolName === importName); })) { return true; } @@ -47838,7 +47888,7 @@ var ts; } var importName = ts.unescapeLeadingUnderscores(element.propertyName ? element.propertyName.escapedText : element.name.escapedText); var aliasName = element.name; - if (InWhiteList(moduleSpecifierText, importName, inEtsContext)) { + if (inWhiteList(moduleSpecifierText, importName, inEtsContext)) { hasError_1 = true; return; } @@ -48052,11 +48102,13 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.BINDE_SOURCE_FILE); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Bind", "beforeBind", "afterBind"); } ts.bindSourceFile = bindSourceFile; @@ -75451,7 +75503,8 @@ var ts; return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || node.kind === 271 /* SyntaxKind.ModuleBlock */ || node.kind === 314 /* SyntaxKind.SourceFile */ || - node.kind === 171 /* SyntaxKind.PropertyDeclaration */; + node.kind === 171 /* SyntaxKind.PropertyDeclaration */ || + node.kind === 172 /* SyntaxKind.AnnotationPropertyDeclaration */; }); } // Check if a parameter or catch variable is assigned anywhere @@ -85186,6 +85239,9 @@ var ts; if (initVal === undefined || initValType === errorType) { return undefined; } + if (isArrayType(initValType) && !Array.isArray(initVal)) { + return undefined; + } if (typeof initVal === "number") { return ts.factory.createNumericLiteral(initVal); } @@ -85218,12 +85274,14 @@ var ts; args.push(ts.factory.createNumericLiteral(3)); } } - return ts.factory.createNewExpression(ts.factory.createIdentifier(typeToString(initValType, /*enclosingDeclaration*/ undefined, 2 /* TypeFormatFlags.WriteArrayAsGenericType */)), - /*typeArguments*/ undefined, args); + return ts.factory.createNewExpression(ts.factory.createIdentifier("Array"), [nodeBuilder.typeToTypeNode(elemType)], args); } var result = new Array(initVal.length); for (var i = 0; i < initVal.length; ++i) { result[i] = annotationEvaluatedValueToExpr(initVal[i], elemType); + if (result[i] === undefined) { + return undefined; + } } return ts.factory.createArrayLiteralExpression(result); } @@ -91399,6 +91457,7 @@ var ts; } function checkSourceFile(node) { ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* tracing.Phase.Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.CHECK_SOURCE_FILE); ts.performance.mark("beforeCheck"); if (host.getFileCheckedModuleInfo) { jsDocFileCheckInfo = host.getFileCheckedModuleInfo(node.fileName); @@ -91406,6 +91465,7 @@ var ts; } checkSourceFileWorker(node); ts.performance.mark("afterCheck"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Check", "beforeCheck", "afterCheck"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } @@ -92919,12 +92979,6 @@ var ts; getAnnotationPropertyInferredType: function (node) { return getNodeLinks(node).annotationPropertyInferredType; }, - setAnnotationDeclarationUniquePrefix: function (node, prefix) { - getNodeLinks(node).annotationDeclarationUniquePrefix = prefix; - }, - getAnnotationDeclarationUniquePrefix: function (node) { - return getNodeLinks(node).annotationDeclarationUniquePrefix; - }, isReferredToAnnotation: function (node) { return getNodeLinks(node).exportOrImportRefersToAnnotation; } @@ -116005,6 +116059,7 @@ var ts; var node = nodes_2[_i]; ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); } + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.TRANSFORM); ts.performance.mark("beforeTransform"); // Chain together and initialize each transformer. var transformersWithContext = transformers.map(function (t) { return t(context); }); @@ -116028,6 +116083,7 @@ var ts; // prevent modification of the lexical environment. state = 2 /* TransformationState.Completed */; ts.performance.mark("afterTransform"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("transformTime", "beforeTransform", "afterTransform"); return { transformed: transformed, @@ -116621,10 +116677,12 @@ var ts; var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit; var bundleBuildInfo; var emitSkipped = false; + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.EMIT_FILES); // Emit each output file enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile); exit(); + ts.MemoryDotting.stopRecordStage(recordInfo); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -116976,8 +117034,6 @@ var ts; getAnnotationObjectLiteralEvaluatedProps: ts.notImplemented, getAnnotationPropertyEvaluatedInitializer: ts.notImplemented, getAnnotationPropertyInferredType: ts.notImplemented, - setAnnotationDeclarationUniquePrefix: ts.notImplemented, - getAnnotationDeclarationUniquePrefix: ts.notImplemented, isReferredToAnnotation: ts.notImplemented, }; function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) { @@ -123241,6 +123297,7 @@ var ts; var sourceFilesFoundSearchingNodeModules = new ts.Map(); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* tracing.Phase.Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeProgram"); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.BEFORE_PROGRAM); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); var skipDefaultLib = options.noLib; @@ -123532,6 +123589,7 @@ var ts; }); verifyCompilerOptions(); ts.performance.mark("afterProgram"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Program", "beforeProgram", "afterProgram"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; @@ -172737,13 +172795,12 @@ var ts; while (pos < end) { var token = ts.scanner.scan(); var textPos = ts.scanner.getTextPos(); - if (!ts.isSourceFile(parent) || !ts.isInMarkedKitImport(parent, pos, textPos)) { - if (textPos <= end) { - if (token === 79 /* SyntaxKind.Identifier */) { - ts.Debug.fail("Did not expect ".concat(ts.Debug.formatSyntaxKind(parent.kind), " to have an Identifier in its trivia")); - } - nodes.push(createNode(token, pos, textPos, parent)); + var isSourceFileOrInMarkedKitImport = !ts.isSourceFile(parent) || !ts.isInMarkedKitImport(parent, pos, textPos); + if (isSourceFileOrInMarkedKitImport && textPos <= end) { + if (token === 79 /* SyntaxKind.Identifier */) { + ts.Debug.fail("Did not expect ".concat(ts.Debug.formatSyntaxKind(parent.kind), " to have an Identifier in its trivia")); } + nodes.push(createNode(token, pos, textPos, parent)); } pos = textPos; if (token === 1 /* SyntaxKind.EndOfFileToken */) { @@ -184430,25 +184487,56 @@ var ts; (((_c = tsType.getSymbol()) === null || _c === void 0 ? void 0 : _c.getName()) === 'ReadonlyArray')); } Utils.isReadonlyArrayType = isReadonlyArrayType; - function isTypedArray(tsType) { + function isConcatArrayType(tsType) { + var _a, _b, _c; + return (isStdLibraryType(tsType) && + isTypeReference(tsType) && + ((_a = tsType.typeArguments) === null || _a === void 0 ? void 0 : _a.length) === 1 && + ((_b = tsType.target.typeParameters) === null || _b === void 0 ? void 0 : _b.length) === 1 && + (((_c = tsType.getSymbol()) === null || _c === void 0 ? void 0 : _c.getName()) === 'ConcatArray')); + } + Utils.isConcatArrayType = isConcatArrayType; + function isArrayLikeType(tsType) { + var _a, _b, _c; + return (isStdLibraryType(tsType) && + isTypeReference(tsType) && + ((_a = tsType.typeArguments) === null || _a === void 0 ? void 0 : _a.length) === 1 && + ((_b = tsType.target.typeParameters) === null || _b === void 0 ? void 0 : _b.length) === 1 && + (((_c = tsType.getSymbol()) === null || _c === void 0 ? void 0 : _c.getName()) === 'ArrayLike')); + } + Utils.isArrayLikeType = isArrayLikeType; + function isTypedArray(tsType, allowTypeArrays) { var symbol = tsType.symbol; if (!symbol) { return false; } var name = typeChecker.getFullyQualifiedName(symbol); - if (isGlobalSymbol(symbol) && Utils.TYPED_ARRAYS.includes(name)) { + if (isGlobalSymbol(symbol) && allowTypeArrays.includes(name)) { return true; } var decl = getDeclaration(symbol); return (!!decl && isArkTSCollectionsClassOrInterfaceDeclaration(decl) && - Utils.TYPED_ARRAYS.includes(symbol.getName())); + allowTypeArrays.includes(symbol.getName())); } Utils.isTypedArray = isTypedArray; function isArray(tsType) { - return isGenericArrayType(tsType) || isReadonlyArrayType(tsType) || isTypedArray(tsType); + return isGenericArrayType(tsType) || isReadonlyArrayType(tsType) || isTypedArray(tsType, Utils.TYPED_ARRAYS); } Utils.isArray = isArray; + function isCollectionArrayType(tsType) { + return isTypedArray(tsType, Utils.TYPED_COLLECTIONS); + } + Utils.isCollectionArrayType = isCollectionArrayType; + function isIndexableArray(tsType) { + return (isGenericArrayType(tsType) || + isReadonlyArrayType(tsType) || + isConcatArrayType(tsType) || + isArrayLikeType(tsType) || + isTypedArray(tsType, Utils.TYPED_ARRAYS) || + isTypedArray(tsType, Utils.TYPED_COLLECTIONS)); + } + Utils.isIndexableArray = isIndexableArray; function isTuple(tsType) { return isTypeReference(tsType) && !!(tsType.objectFlags & 8 /* ts.ObjectFlags.Tuple */); } @@ -185203,17 +185291,20 @@ var ts; "lib.es2022.sharedmemory.d.ts", "lib.es2022.string.d.ts", "lib.es2022.regexp.d.ts", "lib.es2023.array.d.ts", ]; Utils.TYPED_ARRAYS = [ - "Int8Array", - "Uint8Array", - "Uint8ClampedArray", - "Int16Array", - "Uint16Array", - "Int32Array", - "Uint32Array", - "Float32Array", - "Float64Array", - "BigInt64Array", - "BigUint64Array", + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array', + ]; + Utils.TYPED_COLLECTIONS = [ + 'BitVector' ]; var parentSymbolCache = new ts.Map(); function getParentSymbolName(symbol) { @@ -188001,6 +188092,9 @@ var ts; return; } } + if ((tsIdentSym.flags & 268435456 /* SymbolFlags.Annotation */) !== 0) { + return; + } if (tsIdentSym.flags & 512 /* SymbolFlags.ValueModule */) { this.incrementCounters(tsIdentifier, FaultID.NamespaceAsObject); } @@ -188064,7 +188158,7 @@ var ts; } return (ArkTSLinter_1_1.Utils.isLibraryType(type) || ArkTSLinter_1_1.Utils.isAnyType(type) || - ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isArray) || + ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isIndexableArray) || ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isTuple) || ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isStdRecordType) || ArkTSLinter_1_1.Utils.isOrDerivedFrom(type, ArkTSLinter_1_1.Utils.isStringType) || @@ -188416,7 +188510,8 @@ var ts; var spreadExprType = ArkTSLinter_1_1.Utils.getTypeOrTypeConstraintAtLocation(node.expression); if (spreadExprType) { if (ts.isCallLikeExpression(node.parent) || ts.isArrayLiteralExpression(node.parent)) { - if (ArkTSLinter_1_1.Utils.isOrDerivedFrom(spreadExprType, ArkTSLinter_1_1.Utils.isArray)) { + if (ArkTSLinter_1_1.Utils.isOrDerivedFrom(spreadExprType, ArkTSLinter_1_1.Utils.isArray) || + ArkTSLinter_1_1.Utils.isOrDerivedFrom(spreadExprType, ArkTSLinter_1_1.Utils.isCollectionArrayType)) { return; } } diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 17d831e717d32b5b34e710443896c9a36281495d..bde210f9f2b95f7f7e2ef2d8fe85fe8e250ad164 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -10184,6 +10184,65 @@ var ts; Enable_support_of_ETS_annotations: diag(28038, ts.DiagnosticCategory.Message, "Enable_support_of_ETS_annotations_28038", "Enable support of ETS annotations"), }; })(ts || (ts = {})); +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * 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. + */ +var ts; +(function (ts) { + var MemoryDotting; + (function (MemoryDotting) { + MemoryDotting.BINDE_SOURCE_FILE = 'binder(bindSourceFile: Bind)'; + MemoryDotting.CHECK_SOURCE_FILE = 'checker(checkSourceFile: Check)'; + MemoryDotting.EMIT_FILES = 'emitter(emitFiles: EmitEachOutputFile)'; + MemoryDotting.CREATE_SORUCE_FILE_PARSE = 'parser(createSourceFile: Parse)'; + MemoryDotting.BEFORE_PROGRAM = 'program(createProgram: beforeProgram)'; + MemoryDotting.TRANSFORM = 'transformer(transformNodes: Transform)'; + var memoryDottingCallback; + var memoryDottingStopCallback; + function recordStage(stage) { + if (memoryDottingCallback !== undefined) { + return memoryDottingCallback(stage); + } + return null; + } + MemoryDotting.recordStage = recordStage; + function stopRecordStage(recordInfo) { + if (memoryDottingStopCallback !== undefined && recordInfo !== null) { + memoryDottingStopCallback(recordInfo); + } + } + MemoryDotting.stopRecordStage = stopRecordStage; + function setMemoryDottingCallBack(recordCallback, stopCallback) { + if (recordCallback) { + memoryDottingCallback = recordCallback; + } + if (stopCallback) { + memoryDottingStopCallback = stopCallback; + } + } + MemoryDotting.setMemoryDottingCallBack = setMemoryDottingCallBack; + function clearCallBack() { + if (memoryDottingCallback !== undefined) { + memoryDottingCallback = undefined; + } + if (memoryDottingStopCallback !== undefined) { + memoryDottingStopCallback = undefined; + } + } + MemoryDotting.clearCallBack = clearCallBack; + })(MemoryDotting = ts.MemoryDotting || (ts.MemoryDotting = {})); +})(ts || (ts = {})); var ts; (function (ts) { var _a; @@ -32543,6 +32602,7 @@ var ts; function createSourceFile(fileName, sourceText, languageVersionOrOptions, setParentNodes, scriptKind, options) { if (setParentNodes === void 0) { setParentNodes = false; } ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("parse" /* tracing.Phase.Parse */, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.CREATE_SORUCE_FILE_PARSE); ts.performance.mark("beforeParse"); var result; sourceFileCompilerOptions = options !== null && options !== void 0 ? options : ts.defaultInitCompilerOptions; @@ -32560,6 +32620,7 @@ var ts; } ts.perfLogger.logStopParseSourceFile(); ts.performance.mark("afterParse"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Parse", "beforeParse", "afterParse"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return result; @@ -46734,7 +46795,7 @@ var ts; (function (ts) { /* @internal */ // Required for distinguishing annotations and decorators in other code analysis tools - ts.annotationMagicNamePrefix = "#"; + ts.annotationMagicNamePrefix = "__$$ETS_ANNOTATION$$__"; /* @internal */ function isInEtsFile(node) { var _a; @@ -47142,13 +47203,12 @@ var ts; return transformTypeExportImportAndConstEnumInTypeScript(context); } ts.getTypeExportImportAndConstEnumTransformer = getTypeExportImportAndConstEnumTransformer; - function getAnnotationTransformer(relativeFilePath) { - return function (context) { return transformAnnotation(context, relativeFilePath); }; + function getAnnotationTransformer() { + return function (context) { return transformAnnotation(context); }; } ts.getAnnotationTransformer = getAnnotationTransformer; - function transformAnnotation(context, relativeFilePath) { + function transformAnnotation(context) { var resolver = context.getEmitResolver(); - var annotationUniqueNamePrefix = getAnnotationUniqueNamePrefixFromFilePath(relativeFilePath); return transformSourceFile; function transformSourceFile(node) { if (node.isDeclarationFile) { @@ -47176,19 +47236,14 @@ var ts; } } function visitAnnotationDeclaration(node) { - resolver.setAnnotationDeclarationUniquePrefix(node, annotationUniqueNamePrefix); - // Add unique prefix for AnnotationDeclaration. For example, - // @interface Anno {} --- > @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno {} - var uniqueName = addUniquePrefixToAnnotationNameIdentifier(node.name, annotationUniqueNamePrefix); - ts.Debug.assert(ts.isIdentifier(uniqueName)); // Add explicit type annotation and initializer. For example, - // @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno { + // @interface Anno { // a = 10 + 5 // } // // will be transformed to // - // @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno { + // @interface Anno { // a: number = 15 // } var members = node.members.map(function (node) { @@ -47196,7 +47251,7 @@ var ts; var initializer = resolver.getAnnotationPropertyEvaluatedInitializer(node); return ts.factory.updateAnnotationPropertyDeclaration(node, node.name, type, initializer); }); - return ts.factory.updateAnnotationDeclaration(node, node.modifiers, uniqueName, members); + return ts.factory.updateAnnotationDeclaration(node, node.modifiers, node.name, members); } function visitAnnotation(node) { if (!node.annotationDeclaration) { @@ -47213,28 +47268,9 @@ var ts; // // and // - // Add unique prefix for annotation name. For example, - // @myModule.Anno({a: 10, b: "abc"}) --- > @myModule.e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855({a: 10, b: "abc"}) - // - // and - // // Add the magic prefix for annotation name. For example, - // @myModule.Anno({a: 10, b: "abc"}) --- > @#myModule.e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855({a: 10, b: "abc"}) - return ts.factory.updateDecorator(node, addMagicPrefixToAnnotationNameIdentifier(addUniquePrefixToAnnotationNameIdentifier(addDefaultValuesIntoAnnotationObjectLiteral(node), resolver.getAnnotationDeclarationUniquePrefix(node.annotationDeclaration)))); - } - function addUniquePrefixToAnnotationNameIdentifier(expr, prefix) { - switch (expr.kind) { - case 79 /* SyntaxKind.Identifier */: - return ts.factory.createIdentifier(prefix + expr.escapedText); - case 211 /* SyntaxKind.PropertyAccessExpression */: - var propAccessExpr = expr; - return ts.factory.updatePropertyAccessExpression(propAccessExpr, propAccessExpr.expression, addUniquePrefixToAnnotationNameIdentifier(propAccessExpr.name, prefix)); - case 213 /* SyntaxKind.CallExpression */: - var callExpr = expr; - return ts.factory.updateCallExpression(callExpr, addUniquePrefixToAnnotationNameIdentifier(callExpr.expression, prefix), callExpr.typeArguments, callExpr.arguments); - default: - return expr; - } + // @myModule.Anno({a: 10, b: "abc"}) --- > @#myModule.Anno({a: 10, b: "abc"}) + return ts.factory.updateDecorator(node, addMagicPrefixToAnnotationNameIdentifier(addDefaultValuesIntoAnnotationObjectLiteral(node))); } function addMagicPrefixToAnnotationNameIdentifier(expr) { switch (expr.kind) { @@ -47293,9 +47329,6 @@ var ts; } ts.Debug.fail(); } - function getAnnotationUniqueNamePrefixFromFilePath(filePath) { - return ts.sys.createHash(filePath); - } } ts.transformAnnotation = transformAnnotation; /** @@ -47583,9 +47616,14 @@ var ts; var output; var lineStart; var linePos; + var lineCount; + // If the last character of string is the one of below chars, there is no need to write space again. + var noSpaceTrailingChars = new ts.Set([' ', ';', ',', '(', ')', '{', '}']); function updateLineCountAndPosFor(s) { var lineStartsOfS = ts.computeLineStarts(s); if (lineStartsOfS.length > 1) { + // 1: The first element of the lineStartsOfS + lineCount = lineCount + lineStartsOfS.length - 1; linePos = output.length - s.length + ts.last(lineStartsOfS); lineStart = (linePos - output.length) === 0; } @@ -47609,9 +47647,15 @@ var ts; output = ""; lineStart = true; linePos = 0; + lineCount = 0; } + // This method is used to write indentation and line breaks. If the string is blank, the writing is skipped. + // In addition, this method can be called to write comments and code in bundle mode, but obfuscation is not in bundle mode. function rawWrite(s) { if (s !== undefined) { + if ((lineStart || endsWithNoSpaceTrailingChar(output)) && s.trim().length === 0) { + return; + } output += s; updateLineCountAndPosFor(s); } @@ -47622,10 +47666,16 @@ var ts; } } function writeLine(force) { - if (!lineStart || force) { - output += space; - linePos = output.length; + if (!force && (lineStart || endsWithNoSpaceTrailingChar(output))) { + return; } + output += space; + lineStart = false; + } + function endsWithNoSpaceTrailingChar(input) { + // Get the last character of a string. + var lastChar = input.charAt(input.length - 1); + return noSpaceTrailingChars.has(lastChar); } function getTextPosWithWriteLine() { return lineStart ? output.length : (output.length + space.length); @@ -47640,7 +47690,7 @@ var ts; decreaseIndent: ts.noop, getIndent: function () { return 0; }, getTextPos: function () { return output.length; }, - getLine: function () { return 0; }, + getLine: function () { return lineCount; }, getColumn: function () { return lineStart ? 0 : output.length - linePos; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, @@ -47682,7 +47732,7 @@ var ts; return (ts.isIdentifier(nameExpr) && nameExpr.escapedText.toString() === 'Sendable'); } ts.isSendableFunctionOrType = isSendableFunctionOrType; - var JSON_SUFFIX = ".json"; + var JSON_SUFFIX = '.json'; var KIT_PREFIX = '@kit.'; var DEFAULT_KEYWORD = 'default'; var ETS_DECLARATION = '.d.ets'; @@ -47794,7 +47844,7 @@ var ts; '@kit.AccountKit', '@kit.MapKit', '@kit.Penkit', '@kit.ScenarioFusionKit', '@kit.ServiceCollaborationKit', '@kit.SpeechKit', '@kit.VisionKit', ]); - function InWhiteList(moduleSpecifierText, importName, inEtsContext) { + function inWhiteList(moduleSpecifierText, importName, inEtsContext) { if (whiteListForErrorSymbol.some(function (info) { return (info.kitName === moduleSpecifierText && info.symbolName === importName); })) { return true; } @@ -47828,7 +47878,7 @@ var ts; } var importName = ts.unescapeLeadingUnderscores(element.propertyName ? element.propertyName.escapedText : element.name.escapedText); var aliasName = element.name; - if (InWhiteList(moduleSpecifierText, importName, inEtsContext)) { + if (inWhiteList(moduleSpecifierText, importName, inEtsContext)) { hasError_1 = true; return; } @@ -48042,11 +48092,13 @@ var ts; } var binder = createBinder(); function bindSourceFile(file, options) { + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.BINDE_SOURCE_FILE); ts.performance.mark("beforeBind"); ts.perfLogger.logStartBindFile("" + file.fileName); binder(file, options); ts.perfLogger.logStopBindFile(); ts.performance.mark("afterBind"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Bind", "beforeBind", "afterBind"); } ts.bindSourceFile = bindSourceFile; @@ -75441,7 +75493,8 @@ var ts; return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) || node.kind === 271 /* SyntaxKind.ModuleBlock */ || node.kind === 314 /* SyntaxKind.SourceFile */ || - node.kind === 171 /* SyntaxKind.PropertyDeclaration */; + node.kind === 171 /* SyntaxKind.PropertyDeclaration */ || + node.kind === 172 /* SyntaxKind.AnnotationPropertyDeclaration */; }); } // Check if a parameter or catch variable is assigned anywhere @@ -85176,6 +85229,9 @@ var ts; if (initVal === undefined || initValType === errorType) { return undefined; } + if (isArrayType(initValType) && !Array.isArray(initVal)) { + return undefined; + } if (typeof initVal === "number") { return ts.factory.createNumericLiteral(initVal); } @@ -85208,12 +85264,14 @@ var ts; args.push(ts.factory.createNumericLiteral(3)); } } - return ts.factory.createNewExpression(ts.factory.createIdentifier(typeToString(initValType, /*enclosingDeclaration*/ undefined, 2 /* TypeFormatFlags.WriteArrayAsGenericType */)), - /*typeArguments*/ undefined, args); + return ts.factory.createNewExpression(ts.factory.createIdentifier("Array"), [nodeBuilder.typeToTypeNode(elemType)], args); } var result = new Array(initVal.length); for (var i = 0; i < initVal.length; ++i) { result[i] = annotationEvaluatedValueToExpr(initVal[i], elemType); + if (result[i] === undefined) { + return undefined; + } } return ts.factory.createArrayLiteralExpression(result); } @@ -91389,6 +91447,7 @@ var ts; } function checkSourceFile(node) { ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("check" /* tracing.Phase.Check */, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.CHECK_SOURCE_FILE); ts.performance.mark("beforeCheck"); if (host.getFileCheckedModuleInfo) { jsDocFileCheckInfo = host.getFileCheckedModuleInfo(node.fileName); @@ -91396,6 +91455,7 @@ var ts; } checkSourceFileWorker(node); ts.performance.mark("afterCheck"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Check", "beforeCheck", "afterCheck"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); } @@ -92909,12 +92969,6 @@ var ts; getAnnotationPropertyInferredType: function (node) { return getNodeLinks(node).annotationPropertyInferredType; }, - setAnnotationDeclarationUniquePrefix: function (node, prefix) { - getNodeLinks(node).annotationDeclarationUniquePrefix = prefix; - }, - getAnnotationDeclarationUniquePrefix: function (node) { - return getNodeLinks(node).annotationDeclarationUniquePrefix; - }, isReferredToAnnotation: function (node) { return getNodeLinks(node).exportOrImportRefersToAnnotation; } @@ -115995,6 +116049,7 @@ var ts; var node = nodes_2[_i]; ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node))); } + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.TRANSFORM); ts.performance.mark("beforeTransform"); // Chain together and initialize each transformer. var transformersWithContext = transformers.map(function (t) { return t(context); }); @@ -116018,6 +116073,7 @@ var ts; // prevent modification of the lexical environment. state = 2 /* TransformationState.Completed */; ts.performance.mark("afterTransform"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("transformTime", "beforeTransform", "afterTransform"); return { transformed: transformed, @@ -116611,10 +116667,12 @@ var ts; var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit; var bundleBuildInfo; var emitSkipped = false; + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.EMIT_FILES); // Emit each output file enter(); forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile); exit(); + ts.MemoryDotting.stopRecordStage(recordInfo); return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -116966,8 +117024,6 @@ var ts; getAnnotationObjectLiteralEvaluatedProps: ts.notImplemented, getAnnotationPropertyEvaluatedInitializer: ts.notImplemented, getAnnotationPropertyInferredType: ts.notImplemented, - setAnnotationDeclarationUniquePrefix: ts.notImplemented, - getAnnotationDeclarationUniquePrefix: ts.notImplemented, isReferredToAnnotation: ts.notImplemented, }; function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) { @@ -123231,6 +123287,7 @@ var ts; var sourceFilesFoundSearchingNodeModules = new ts.Map(); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.push("program" /* tracing.Phase.Program */, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); ts.performance.mark("beforeProgram"); + var recordInfo = ts.MemoryDotting.recordStage(ts.MemoryDotting.BEFORE_PROGRAM); var host = createProgramOptions.host || createCompilerHost(options); var configParsingHost = parseConfigHostFromCompilerHostLike(host); var skipDefaultLib = options.noLib; @@ -123522,6 +123579,7 @@ var ts; }); verifyCompilerOptions(); ts.performance.mark("afterProgram"); + ts.MemoryDotting.stopRecordStage(recordInfo); ts.performance.measure("Program", "beforeProgram", "afterProgram"); ts.tracing === null || ts.tracing === void 0 ? void 0 : ts.tracing.pop(); return program; diff --git a/package.json b/package.json index c4ff6dc39f3b228e58e77d9b8f2e92cb0192397e..027160c55371f6e5c3d20d386072886513d4ade6 100644 --- a/package.json +++ b/package.json @@ -118,7 +118,9 @@ "release": "gulp LKG", "baseline": "gulp baseline-accept", "lint": "gulp lint", - "setup-hooks": "node scripts/link-hooks.mjs" + "setup-hooks": "node scripts/link-hooks.mjs", + "test:system-api": "tsc ./tests/system_api_test/system_api_test.ts && node ./tests/system_api_test/system_api_test.js", + "alltest": "npm run test && npm run test:system-api" }, "browser": { "fs": false, diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index bf5b592dfe62328562d4d1e0457b705ef5cc2087..f880a4f9d1ba696fc34f5f12868147f6f5edafd2 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -174,11 +174,13 @@ namespace ts { const binder = createBinder(); export function bindSourceFile(file: SourceFile, options: CompilerOptions) { + const recordInfo = MemoryDotting.recordStage(MemoryDotting.BINDE_SOURCE_FILE); performance.mark("beforeBind"); perfLogger.logStartBindFile("" + file.fileName); binder(file, options); perfLogger.logStopBindFile(); performance.mark("afterBind"); + MemoryDotting.stopRecordStage(recordInfo); performance.measure("Bind", "beforeBind", "afterBind"); } diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c55f55667d034d7d10e06f82bce6cf79bb5862a6..5e7ffb361acba8f40bdce5dc8ef3a444ed1347b2 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -26050,8 +26050,9 @@ namespace ts { isFunctionLike(node) && !getImmediatelyInvokedFunctionExpression(node) || node.kind === SyntaxKind.ModuleBlock || node.kind === SyntaxKind.SourceFile || - node.kind === SyntaxKind.PropertyDeclaration)!; - } + node.kind === SyntaxKind.PropertyDeclaration || + node.kind === SyntaxKind.AnnotationPropertyDeclaration)!; + } // Check if a parameter or catch variable is assigned anywhere function isSymbolAssigned(symbol: Symbol) { @@ -36774,6 +36775,9 @@ namespace ts { if (initVal === undefined || initValType === errorType) { return undefined; } + if (isArrayType(initValType) && !Array.isArray(initVal)) { + return undefined; + } if (typeof initVal === "number") { return factory.createNumericLiteral(initVal); } @@ -36807,15 +36811,16 @@ namespace ts { } } return factory.createNewExpression( - factory.createIdentifier( - typeToString(initValType, /*enclosingDeclaration*/undefined, TypeFormatFlags.WriteArrayAsGenericType) - ), - /*typeArguments*/ undefined, + factory.createIdentifier("Array"), + [nodeBuilder.typeToTypeNode(elemType) as TypeNode], args); } const result = new Array(initVal.length); for (let i = 0; i < initVal.length; ++i) { result[i] = annotationEvaluatedValueToExpr(initVal[i], elemType)!; + if (result[i] === undefined){ + return undefined; + } } return factory.createArrayLiteralExpression(result); } @@ -43695,6 +43700,7 @@ namespace ts { function checkSourceFile(node: SourceFile) { tracing?.push(tracing.Phase.Check, "checkSourceFile", { path: node.path }, /*separateBeginAndEnd*/ true); + const recordInfo = MemoryDotting.recordStage(MemoryDotting.CHECK_SOURCE_FILE); performance.mark("beforeCheck"); if (host.getFileCheckedModuleInfo) { jsDocFileCheckInfo = host.getFileCheckedModuleInfo(node.fileName); @@ -43702,6 +43708,7 @@ namespace ts { } checkSourceFileWorker(node); performance.mark("afterCheck"); + MemoryDotting.stopRecordStage(recordInfo); performance.measure("Check", "beforeCheck", "afterCheck"); tracing?.pop(); } @@ -45388,12 +45395,6 @@ namespace ts { getAnnotationPropertyInferredType: (node: AnnotationPropertyDeclaration): TypeNode | undefined => { return getNodeLinks(node).annotationPropertyInferredType; }, - setAnnotationDeclarationUniquePrefix: (node: AnnotationDeclaration, prefix: string): void => { - getNodeLinks(node).annotationDeclarationUniquePrefix = prefix; - }, - getAnnotationDeclarationUniquePrefix: (node: AnnotationDeclaration): string | undefined => { - return getNodeLinks(node).annotationDeclarationUniquePrefix; - }, isReferredToAnnotation: (node: ImportSpecifier | ExportSpecifier | ExportAssignment): boolean | undefined => { return getNodeLinks(node).exportOrImportRefersToAnnotation; } @@ -47620,4 +47621,4 @@ namespace ts { export function signatureHasLiteralTypes(s: Signature) { return !!(s.flags & SignatureFlags.HasLiteralTypes); } -} \ No newline at end of file +} diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 06a78426da118406bac01c6bc34ba391560f0104..0b0e89debdd293e8c7313b37ff258ea75f1839e3 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -292,6 +292,7 @@ namespace ts { const { enter, exit } = performance.createTimer("printTime", "beforePrint", "afterPrint"); let bundleBuildInfo: BundleBuildInfo | undefined; let emitSkipped = false; + const recordInfo = MemoryDotting.recordStage(MemoryDotting.EMIT_FILES); // Emit each output file enter(); @@ -304,6 +305,7 @@ namespace ts { !targetSourceFile ); exit(); + MemoryDotting.stopRecordStage(recordInfo); return { @@ -715,8 +717,6 @@ namespace ts { getAnnotationObjectLiteralEvaluatedProps: notImplemented, getAnnotationPropertyEvaluatedInitializer: notImplemented, getAnnotationPropertyInferredType: notImplemented, - setAnnotationDeclarationUniquePrefix: notImplemented, - getAnnotationDeclarationUniquePrefix: notImplemented, isReferredToAnnotation: notImplemented, }; diff --git a/src/compiler/memorydotting/memoryDotting.ts b/src/compiler/memorydotting/memoryDotting.ts new file mode 100755 index 0000000000000000000000000000000000000000..9437d81d2df0a959c1d5b63f901cf9fd333d4559 --- /dev/null +++ b/src/compiler/memorydotting/memoryDotting.ts @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * 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. + */ + +namespace ts { + export namespace MemoryDotting { + export interface RecordInfo { + recordStage: string, + recordIndex: number + } + export const BINDE_SOURCE_FILE = 'binder(bindSourceFile: Bind)'; + export const CHECK_SOURCE_FILE = 'checker(checkSourceFile: Check)'; + export const EMIT_FILES = 'emitter(emitFiles: EmitEachOutputFile)'; + export const CREATE_SORUCE_FILE_PARSE = 'parser(createSourceFile: Parse)'; + export const BEFORE_PROGRAM = 'program(createProgram: beforeProgram)'; + export const TRANSFORM = 'transformer(transformNodes: Transform)'; + + let memoryDottingCallback: ((stage: string) => RecordInfo) | undefined; + let memoryDottingStopCallback: ((recordInfo: RecordInfo) => void) | undefined; + + export function recordStage(stage: string): RecordInfo | null { + if (memoryDottingCallback !== undefined) { + return memoryDottingCallback(stage); + } + return null; + } + + export function stopRecordStage(recordInfo: RecordInfo | null): void { + if (memoryDottingStopCallback !== undefined && recordInfo !== null) { + memoryDottingStopCallback(recordInfo); + } + } + + export function setMemoryDottingCallBack(recordCallback: (stage: string) => RecordInfo, stopCallback: (recordInfo: RecordInfo) => void): void { + if (recordCallback) { + memoryDottingCallback = recordCallback; + } + if (stopCallback) { + memoryDottingStopCallback = stopCallback; + } + } + + export function clearCallBack(): void { + if (memoryDottingCallback !== undefined) { + memoryDottingCallback = undefined; + } + if (memoryDottingStopCallback !== undefined) { + memoryDottingStopCallback = undefined; + } + } + } +} + diff --git a/src/compiler/ohApi.ts b/src/compiler/ohApi.ts index e42aa9e333b53120173ed0f2a0d049c04cf39a11..e9f0dec2405c807a7a34e2e2c97609eed27add25 100644 --- a/src/compiler/ohApi.ts +++ b/src/compiler/ohApi.ts @@ -1,7 +1,7 @@ namespace ts { /* @internal */ // Required for distinguishing annotations and decorators in other code analysis tools - export const annotationMagicNamePrefix = "#"; + export const annotationMagicNamePrefix = "__$$ETS_ANNOTATION$$__"; /* @internal */ export function isInEtsFile(node: Node |undefined): boolean { @@ -398,13 +398,12 @@ namespace ts { return transformTypeExportImportAndConstEnumInTypeScript(context); } - export function getAnnotationTransformer(relativeFilePath: string): TransformerFactory { - return (context: TransformationContext) => transformAnnotation(context, relativeFilePath); + export function getAnnotationTransformer(): TransformerFactory { + return (context: TransformationContext) => transformAnnotation(context); } - export function transformAnnotation(context: TransformationContext, relativeFilePath: string): (node: SourceFile) => SourceFile { + export function transformAnnotation(context: TransformationContext): (node: SourceFile) => SourceFile { const resolver = context.getEmitResolver(); - const annotationUniqueNamePrefix = getAnnotationUniqueNamePrefixFromFilePath(relativeFilePath); return transformSourceFile; @@ -440,21 +439,14 @@ namespace ts { } function visitAnnotationDeclaration(node: AnnotationDeclaration): VisitResult { - resolver.setAnnotationDeclarationUniquePrefix(node, annotationUniqueNamePrefix); - - // Add unique prefix for AnnotationDeclaration. For example, - // @interface Anno {} --- > @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno {} - const uniqueName = addUniquePrefixToAnnotationNameIdentifier(node.name, annotationUniqueNamePrefix); - Debug.assert(isIdentifier(uniqueName)); - // Add explicit type annotation and initializer. For example, - // @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno { + // @interface Anno { // a = 10 + 5 // } // // will be transformed to // - // @interface e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855Anno { + // @interface Anno { // a: number = 15 // } const members = node.members.map((node: AnnotationPropertyDeclaration) => { @@ -463,7 +455,7 @@ namespace ts { return factory.updateAnnotationPropertyDeclaration(node, node.name, type, initializer); }); - return factory.updateAnnotationDeclaration(node, node.modifiers, uniqueName, members); + return factory.updateAnnotationDeclaration(node, node.modifiers, node.name, members); } function visitAnnotation(node: Annotation): VisitResult { @@ -481,50 +473,15 @@ namespace ts { // // and // - // Add unique prefix for annotation name. For example, - // @myModule.Anno({a: 10, b: "abc"}) --- > @myModule.e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855({a: 10, b: "abc"}) - // - // and - // // Add the magic prefix for annotation name. For example, - // @myModule.Anno({a: 10, b: "abc"}) --- > @#myModule.e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855({a: 10, b: "abc"}) + // @myModule.Anno({a: 10, b: "abc"}) --- > @#myModule.Anno({a: 10, b: "abc"}) return factory.updateDecorator( node, addMagicPrefixToAnnotationNameIdentifier( - addUniquePrefixToAnnotationNameIdentifier( - addDefaultValuesIntoAnnotationObjectLiteral(node), - resolver.getAnnotationDeclarationUniquePrefix(node.annotationDeclaration)! - ) - ) + addDefaultValuesIntoAnnotationObjectLiteral(node)) ); } - function addUniquePrefixToAnnotationNameIdentifier(expr: Expression, prefix: string): Identifier | PropertyAccessExpression | CallExpression { - switch (expr.kind) { - case SyntaxKind.Identifier: - return factory.createIdentifier( - prefix + (expr as Identifier).escapedText - ); - case SyntaxKind.PropertyAccessExpression: - const propAccessExpr = expr as PropertyAccessExpression; - return factory.updatePropertyAccessExpression( - propAccessExpr, - propAccessExpr.expression, - addUniquePrefixToAnnotationNameIdentifier(propAccessExpr.name, prefix) as MemberName - ); - case SyntaxKind.CallExpression: - const callExpr = expr as CallExpression; - return factory.updateCallExpression( - callExpr, - addUniquePrefixToAnnotationNameIdentifier(callExpr.expression, prefix), - callExpr.typeArguments, - callExpr.arguments - ); - default: - return expr as (Identifier | PropertyAccessExpression | CallExpression); - } - } - function addMagicPrefixToAnnotationNameIdentifier(expr: Expression): Identifier | PropertyAccessExpression | CallExpression { switch (expr.kind) { case SyntaxKind.Identifier: @@ -601,10 +558,6 @@ namespace ts { } Debug.fail(); } - - function getAnnotationUniqueNamePrefixFromFilePath(filePath: string): string { - return sys.createHash!(filePath); - } } /** @@ -930,10 +883,15 @@ namespace ts { let output: string; let lineStart: boolean; let linePos: number; + let lineCount: number; + // If the last character of string is the one of below chars, there is no need to write space again. + const noSpaceTrailingChars: Set = new Set([' ', ';', ',', '(', ')', '{', '}']); function updateLineCountAndPosFor(s: string) { const lineStartsOfS = computeLineStarts(s); if (lineStartsOfS.length > 1) { + // 1: The first element of the lineStartsOfS + lineCount = lineCount + lineStartsOfS.length - 1; linePos = output.length - s.length + last(lineStartsOfS); lineStart = (linePos - output.length) === 0; } @@ -960,10 +918,16 @@ namespace ts { output = ""; lineStart = true; linePos = 0; + lineCount = 0; } + // This method is used to write indentation and line breaks. If the string is blank, the writing is skipped. + // In addition, this method can be called to write comments and code in bundle mode, but obfuscation is not in bundle mode. function rawWrite(s: string) { if (s !== undefined) { + if ((lineStart || endsWithNoSpaceTrailingChar(output)) && s.trim().length === 0) { + return; + } output += s; updateLineCountAndPosFor(s); } @@ -975,11 +939,18 @@ namespace ts { } } - function writeLine(force?: boolean) { - if (!lineStart || force) { - output += space; - linePos = output.length; + function writeLine(force?: boolean): void { + if (!force && (lineStart || endsWithNoSpaceTrailingChar(output))) { + return; } + output += space; + lineStart = false; + } + + function endsWithNoSpaceTrailingChar(input: string): boolean { + // Get the last character of a string. + const lastChar: string = input.charAt(input.length - 1); + return noSpaceTrailingChars.has(lastChar); } function getTextPosWithWriteLine() { @@ -997,7 +968,7 @@ namespace ts { decreaseIndent: noop, getIndent: () => 0, getTextPos: () => output.length, - getLine: () => 0, + getLine: () => lineCount, getColumn: () => lineStart ? 0 : output.length - linePos, getText: () => output, isAtStartOfLine: () => lineStart, @@ -1038,10 +1009,10 @@ namespace ts { return (isIdentifier(nameExpr) && nameExpr.escapedText.toString() === 'Sendable'); } - const JSON_SUFFIX = ".json"; + const JSON_SUFFIX = '.json'; const KIT_PREFIX = '@kit.'; const DEFAULT_KEYWORD = 'default'; - const ETS_DECLARATION = '.d.ets' + const ETS_DECLARATION = '.d.ets'; const OHOS_KIT_CONFIG_PATH = './openharmony/ets/build-tools/ets-loader/kit_configs'; const HMS_KIT_CONFIG_PATH = './hms/ets/build-tools/ets-loader/kit_configs'; @@ -1104,7 +1075,9 @@ namespace ts { function createNameImportDeclaration(factory: NodeFactory, isType: boolean, name: Identifier, source: string, oldStatement: ImportDeclaration, importSpecifier: TextRange): ImportDeclaration { const oldModuleSpecifier = oldStatement.moduleSpecifier; - const newModuleSpecifier = setNoOriginalText(setVirtualNodeAndKitImportFlags(factory.createStringLiteral(source), oldModuleSpecifier.pos, oldModuleSpecifier.end)); + const newModuleSpecifier = setNoOriginalText(setVirtualNodeAndKitImportFlags( + factory.createStringLiteral(source), oldModuleSpecifier.pos, oldModuleSpecifier.end) + ); const newImportClause = setVirtualNodeAndKitImportFlags(factory.createImportClause(isType, name, undefined), importSpecifier.pos, importSpecifier.end); const newImportDeclaration = setVirtualNodeAndKitImportFlags( factory.createImportDeclaration(undefined, newImportClause, newModuleSpecifier), oldStatement.pos, oldStatement.end); @@ -1114,14 +1087,17 @@ namespace ts { function createBindingImportDeclaration(factory: NodeFactory, isType: boolean, propname: string, name: Identifier, source: string, oldStatement: ImportDeclaration, importSpecifier: TextRange): ImportDeclaration { const oldModuleSpecifier = oldStatement.moduleSpecifier; - const newModuleSpecifier = setNoOriginalText(setVirtualNodeAndKitImportFlags(factory.createStringLiteral(source), oldModuleSpecifier.pos, oldModuleSpecifier.end)); + const newModuleSpecifier = setNoOriginalText( + setVirtualNodeAndKitImportFlags(factory.createStringLiteral(source), oldModuleSpecifier.pos, oldModuleSpecifier.end)); const newPropertyName = setNoOriginalText(setVirtualNodeAndKitImportFlags(factory.createIdentifier(propname), name.pos, name.end)); // The location information of the newImportSpecific is created using the location information of the old importSpecifier. - const newImportSpecific = setVirtualNodeAndKitImportFlags(factory.createImportSpecifier(false, newPropertyName, name), importSpecifier.pos, importSpecifier.end); + const newImportSpecific = setVirtualNodeAndKitImportFlags( + factory.createImportSpecifier(false, newPropertyName, name), importSpecifier.pos, importSpecifier.end); // The location information of the newNamedBindings is created using the location information of the old importSpecifier. const newNamedBindings = setVirtualNodeAndKitImportFlags(factory.createNamedImports([newImportSpecific]), importSpecifier.pos, importSpecifier.end); // The location information of the newImportClause is created using the location information of the old importSpecifier. - const newImportClause = setVirtualNodeAndKitImportFlags(factory.createImportClause(isType, undefined, newNamedBindings), importSpecifier.pos, importSpecifier.end); + const newImportClause = setVirtualNodeAndKitImportFlags( + factory.createImportClause(isType, undefined, newNamedBindings), importSpecifier.pos, importSpecifier.end); const newImportDeclaration = setVirtualNodeAndKitImportFlags( factory.createImportDeclaration(undefined, newImportClause, newModuleSpecifier), oldStatement.pos, oldStatement.end); return newImportDeclaration; @@ -1151,14 +1127,14 @@ namespace ts { } function excludeStatementForKitImport(statement: Statement): boolean { - if (!isImportDeclaration(statement) || // check is ImportDeclaration - !statement.importClause || // exclude import 'mode' - statement.importClause.isLazy || // exclude import lazy, it may report error - (statement.importClause.namedBindings && ts.isNamespaceImport(statement.importClause.namedBindings)) || // exclude namespace import - !isStringLiteral(statement.moduleSpecifier) || statement.illegalDecorators || // exclude if may has error + if (!isImportDeclaration(statement) || // check is ImportDeclaration + !statement.importClause || // exclude import 'mode' + statement.importClause.isLazy || // exclude import lazy, it may report error + (statement.importClause.namedBindings && ts.isNamespaceImport(statement.importClause.namedBindings)) || // exclude namespace import + !isStringLiteral(statement.moduleSpecifier) || statement.illegalDecorators || // exclude if may has error !statement.moduleSpecifier.text.startsWith(KIT_PREFIX) || // is not kit import - statement.modifiers || // exclude if has modifiers - statement.assertClause) { // not support assertClause + statement.modifiers || // exclude if has modifiers + statement.assertClause) { // not support assertClause return true; } return false; @@ -1186,7 +1162,7 @@ namespace ts { '@kit.ServiceCollaborationKit', '@kit.SpeechKit', '@kit.VisionKit', ]); - function InWhiteList(moduleSpecifierText: string, importName: string, inEtsContext: boolean): boolean { + function inWhiteList(moduleSpecifierText: string, importName: string, inEtsContext: boolean): boolean { if (whiteListForErrorSymbol.some(info => (info.kitName === moduleSpecifierText && info.symbolName === importName))) { return true; } @@ -1226,7 +1202,7 @@ namespace ts { const importName = unescapeLeadingUnderscores(element.propertyName ? element.propertyName.escapedText : element.name.escapedText); const aliasName = element.name; - if (InWhiteList(moduleSpecifierText, importName, inEtsContext)) { + if (inWhiteList(moduleSpecifierText, importName, inEtsContext)) { hasError = true; return; } @@ -1285,7 +1261,7 @@ namespace ts { list.push(...newImportStatements); markKitImport(statement, markedkitImportRanges); } - ) + ); return list; } } \ No newline at end of file diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 04fc0fa870ba2d6c151a11489770d00e1b26200e..33fac9f73d5d970d98cd37e9c772adb9daefbb4e 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -955,6 +955,7 @@ namespace ts { let sourceFileCompilerOptions: CompilerOptions; export function createSourceFile(fileName: string, sourceText: string, languageVersionOrOptions: ScriptTarget | CreateSourceFileOptions, setParentNodes = false, scriptKind?: ScriptKind, options?: CompilerOptions): SourceFile { tracing?.push(tracing.Phase.Parse, "createSourceFile", { path: fileName }, /*separateBeginAndEnd*/ true); + const recordInfo = MemoryDotting.recordStage(MemoryDotting.CREATE_SORUCE_FILE_PARSE); performance.mark("beforeParse"); let result: SourceFile; sourceFileCompilerOptions = options ?? defaultInitCompilerOptions; @@ -977,6 +978,7 @@ namespace ts { perfLogger.logStopParseSourceFile(); performance.mark("afterParse"); + MemoryDotting.stopRecordStage(recordInfo); performance.measure("Parse", "beforeParse", "afterParse"); tracing?.pop(); return result; @@ -6251,7 +6253,7 @@ namespace ts { (item: any) => item.name === rootNodeName); if (type === 'callExpressionComponentType' && syntaxComponents && syntaxComponents.length && syntaxComponents[0]?.attributes?.includes(currentNodeName)) { - setSyntaxComponentContext(true); + setSyntaxComponentContext(true); } else if (type === 'etsComponentType') { typeArguments = parseEtsTypeArguments(pos, `${rootNodeName}Attribute`); } diff --git a/src/compiler/program.ts b/src/compiler/program.ts index e84f98bda23358d026dcb9e01fc1ff16fb0f142d..645262a8ba2b61cdc756cbff3c0d289bf6f1db88 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -1064,6 +1064,7 @@ namespace ts { tracing?.push(tracing.Phase.Program, "createProgram", { configFilePath: options.configFilePath, rootDir: options.rootDir }, /*separateBeginAndEnd*/ true); performance.mark("beforeProgram"); + const recordInfo = MemoryDotting.recordStage(MemoryDotting.BEFORE_PROGRAM); const host = createProgramOptions.host || createCompilerHost(options); const configParsingHost = parseConfigHostFromCompilerHostLike(host); @@ -1385,6 +1386,7 @@ namespace ts { verifyCompilerOptions(); performance.mark("afterProgram"); + MemoryDotting.stopRecordStage(recordInfo); performance.measure("Program", "beforeProgram", "afterProgram"); tracing?.pop(); diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts index 9f1a22abce11b2d01e2715b94a54d5ab4cc8d4a1..817a85393bb8e40bac51a9d416e3c3f0ca350d9d 100644 --- a/src/compiler/transformer.ts +++ b/src/compiler/transformer.ts @@ -222,6 +222,7 @@ namespace ts { disposeEmitNodes(getSourceFileOfNode(getParseTreeNode(node))); } + const recordInfo = MemoryDotting.recordStage(MemoryDotting.TRANSFORM); performance.mark("beforeTransform"); // Chain together and initialize each transformer. @@ -248,6 +249,7 @@ namespace ts { state = TransformationState.Completed; performance.mark("afterTransform"); + MemoryDotting.stopRecordStage(recordInfo); performance.measure("transformTime", "beforeTransform", "afterTransform"); return { diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index b361a8ee88fc73458461181730dd7a3bd785a801..e35b59673a30cf77e826951e779c59c18c9135d5 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -22,6 +22,7 @@ "sys.ts", "path.ts", "diagnosticInformationMap.generated.ts", + "memorydotting/memoryDotting.ts", "scanner.ts", "utilitiesPublic.ts", "utilities.ts", diff --git a/src/compiler/types.ts b/src/compiler/types.ts index a28de2412b036c2d4f8265ce599ab37b96de24a3..4a4ef80d0a1fdf6cb1776d2fcf68ad62a6d7dcef 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -802,9 +802,9 @@ namespace ts { /* @internal */ TypeCached = 1 << 27, // If a type was cached for node at any point /* @internal */ Deprecated = 1 << 28, // If has '@deprecated' JSDoc tag - /* @internal */ KitImportFlags = 1 << 29, // If node was in a converted kit-import statement - EtsContext = 1 << 30, // If context was parsed as a Struct - /* @internal */ NoOriginalText = 1 << 31, // If don't has original text in source file + /* @internal */ KitImportFlags = 1 << 29, // If node was in a converted kit-import statement + EtsContext = 1 << 30, // If context was parsed as a Struct + /* @internal */ NoOriginalText = 1 << 31, // If don't has original text in source file BlockScoped = Let | Const, @@ -5378,8 +5378,6 @@ namespace ts { getAnnotationObjectLiteralEvaluatedProps(node: Annotation): ESMap<__String, Expression> | undefined; getAnnotationPropertyEvaluatedInitializer(node: AnnotationPropertyDeclaration): Expression | undefined; getAnnotationPropertyInferredType(node: AnnotationPropertyDeclaration): TypeNode | undefined; - setAnnotationDeclarationUniquePrefix(node: AnnotationDeclaration, name: string): void; - getAnnotationDeclarationUniquePrefix(node: AnnotationDeclaration): string | undefined; isReferredToAnnotation(node: ImportSpecifier | ExportSpecifier | ExportAssignment): boolean | undefined; } diff --git a/src/linter/ArkTSLinter_1_1/TypeScriptLinter.ts b/src/linter/ArkTSLinter_1_1/TypeScriptLinter.ts index ae7b848552ff577196aac7cf1317d0b9b4f11ec3..991e20227d12b48eb7a291cfcd232a6915823cd4 100644 --- a/src/linter/ArkTSLinter_1_1/TypeScriptLinter.ts +++ b/src/linter/ArkTSLinter_1_1/TypeScriptLinter.ts @@ -1746,6 +1746,9 @@ export class TypeScriptLinter { return; } } + if ((tsIdentSym.flags & SymbolFlags.Annotation) !== 0) { + return; + } if (tsIdentSym.flags & SymbolFlags.ValueModule) { this.incrementCounters(tsIdentifier, FaultID.NamespaceAsObject); @@ -1820,7 +1823,7 @@ export class TypeScriptLinter { return ( Utils.isLibraryType(type) || Utils.isAnyType(type) || - Utils.isOrDerivedFrom(type, Utils.isArray) || + Utils.isOrDerivedFrom(type, Utils.isIndexableArray) || Utils.isOrDerivedFrom(type, Utils.isTuple) || Utils.isOrDerivedFrom(type, Utils.isStdRecordType) || Utils.isOrDerivedFrom(type, Utils.isStringType) || @@ -2238,7 +2241,10 @@ export class TypeScriptLinter { const spreadExprType = Utils.getTypeOrTypeConstraintAtLocation(node.expression); if (spreadExprType) { if (ts.isCallLikeExpression(node.parent) || ts.isArrayLiteralExpression(node.parent)) { - if (Utils.isOrDerivedFrom(spreadExprType, Utils.isArray)) { + if ( + Utils.isOrDerivedFrom(spreadExprType, Utils.isArray) || + Utils.isOrDerivedFrom(spreadExprType, Utils.isCollectionArrayType) + ) { return; } } diff --git a/src/linter/ArkTSLinter_1_1/Utils.ts b/src/linter/ArkTSLinter_1_1/Utils.ts index b6dc69c2eb45913a7b004363e248afaa004576a4..1b0e0717c363d52f611d6798c3a8f55412a368ae 100644 --- a/src/linter/ArkTSLinter_1_1/Utils.ts +++ b/src/linter/ArkTSLinter_1_1/Utils.ts @@ -509,25 +509,60 @@ export function isReadonlyArrayType(tsType: Type): boolean { ); } -export function isTypedArray(tsType: ts.Type): boolean { +export function isConcatArrayType(tsType: Type): boolean { + return ( + isStdLibraryType(tsType) && + isTypeReference(tsType) && + tsType.typeArguments?.length === 1 && + tsType.target.typeParameters?.length === 1 && + (tsType.getSymbol()?.getName() === 'ConcatArray') + ); +} + +export function isArrayLikeType(tsType: Type): boolean { + return ( + isStdLibraryType(tsType) && + isTypeReference(tsType) && + tsType.typeArguments?.length === 1 && + tsType.target.typeParameters?.length === 1 && + (tsType.getSymbol()?.getName() === 'ArrayLike') + ); +} + +export function isTypedArray(tsType: ts.Type, allowTypeArrays: string[]): boolean { const symbol = tsType.symbol; if (!symbol) { return false; } const name = typeChecker.getFullyQualifiedName(symbol); - if (isGlobalSymbol(symbol) && TYPED_ARRAYS.includes(name)) { + if (isGlobalSymbol(symbol) && allowTypeArrays.includes(name)) { return true; } const decl = getDeclaration(symbol); return ( !!decl && isArkTSCollectionsClassOrInterfaceDeclaration(decl) && - TYPED_ARRAYS.includes(symbol.getName()) + allowTypeArrays.includes(symbol.getName()) ); } export function isArray(tsType: ts.Type): boolean { - return isGenericArrayType(tsType) || isReadonlyArrayType(tsType) || isTypedArray(tsType); + return isGenericArrayType(tsType) || isReadonlyArrayType(tsType) || isTypedArray(tsType, TYPED_ARRAYS); +} + +export function isCollectionArrayType(tsType: ts.Type): boolean { + return isTypedArray(tsType, TYPED_COLLECTIONS); +} + +export function isIndexableArray(tsType: ts.Type): boolean { + return ( + isGenericArrayType(tsType) || + isReadonlyArrayType(tsType) || + isConcatArrayType(tsType) || + isArrayLikeType(tsType) || + isTypedArray(tsType, TYPED_ARRAYS) || + isTypedArray(tsType, TYPED_COLLECTIONS) + ); } export function isTuple(tsType: ts.Type): boolean { @@ -1363,17 +1398,21 @@ export const STANDARD_LIBRARIES = [ ]; export const TYPED_ARRAYS = [ - "Int8Array", - "Uint8Array", - "Uint8ClampedArray", - "Int16Array", - "Uint16Array", - "Int32Array", - "Uint32Array", - "Float32Array", - "Float64Array", - "BigInt64Array", - "BigUint64Array", + 'Int8Array', + 'Uint8Array', + 'Uint8ClampedArray', + 'Int16Array', + 'Uint16Array', + 'Int32Array', + 'Uint32Array', + 'Float32Array', + 'Float64Array', + 'BigInt64Array', + 'BigUint64Array', + ]; + +export const TYPED_COLLECTIONS = [ + 'BitVector' ]; let parentSymbolCache: ESMap | undefined = new Map(); diff --git a/src/services/services.ts b/src/services/services.ts index 117c3dcac95c6c78f2c48076c1162e25b9d885fc..425bc5146a0322562ec1555c324c230a0b236e5e 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -184,13 +184,12 @@ namespace ts { while (pos < end) { const token = scanner.scan(); const textPos = scanner.getTextPos(); - if (!isSourceFile(parent) || !isInMarkedKitImport(parent, pos, textPos)) { - if (textPos <= end) { - if (token === SyntaxKind.Identifier) { - Debug.fail(`Did not expect ${Debug.formatSyntaxKind(parent.kind)} to have an Identifier in its trivia`); - } - nodes.push(createNode(token, pos, textPos, parent)); + const isSourceFileOrInMarkedKitImport: boolean = !isSourceFile(parent) || !isInMarkedKitImport(parent, pos, textPos); + if (isSourceFileOrInMarkedKitImport && textPos <= end) { + if (token === SyntaxKind.Identifier) { + Debug.fail(`Did not expect ${Debug.formatSyntaxKind(parent.kind)} to have an Identifier in its trivia`); } + nodes.push(createNode(token, pos, textPos, parent)); } pos = textPos; if (token === SyntaxKind.EndOfFileToken) { diff --git a/tests/arkTSTest/testcase/arkts-no-props-by-index/arkts-no-props-by-index-11-ok.ets b/tests/arkTSTest/testcase/arkts-no-props-by-index/arkts-no-props-by-index-11-ok.ets new file mode 100644 index 0000000000000000000000000000000000000000..24fb89ebd1210b8112a51ed7f70c08b39f67f5df --- /dev/null +++ b/tests/arkTSTest/testcase/arkts-no-props-by-index/arkts-no-props-by-index-11-ok.ets @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * 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. + */ + +import collections from '../common-lib/@arkts.collections'; + +@Sendable +class MyClass extends collections.BitVector { + constructor() { + super(0); + for (let i = 0; i < this.length; i++) { + this[i] = 1; + } + } +} \ No newline at end of file diff --git a/tests/arkTSTest/testcase/arkts-no-props-by-index/arkts-no-props-by-index-11-ok.json b/tests/arkTSTest/testcase/arkts-no-props-by-index/arkts-no-props-by-index-11-ok.json new file mode 100644 index 0000000000000000000000000000000000000000..a47484cd352277b00749b18e9f8de1f09402ce5b --- /dev/null +++ b/tests/arkTSTest/testcase/arkts-no-props-by-index/arkts-no-props-by-index-11-ok.json @@ -0,0 +1,33 @@ +{ + "arktsVersion_1_0": [ + { + "messageText": "No decorators except ArkUI decorators are currently allowed (arkts-no-decorators-except-arkui)", + "expectLineAndCharacter": { + "line": 17, + "character": 3 + } + }, + { + "messageText": "Indexed signatures are not supported (arkts-no-indexed-signatures)", + "expectLineAndCharacter": { + "line": 19, + "character": 5 + } + }, + { + "messageText": "No decorators except ArkUI decorators are currently allowed (arkts-no-decorators-except-arkui)", + "expectLineAndCharacter": { + "line": 18, + "character": 1 + } + }, + { + "messageText": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "expectLineAndCharacter": { + "line": 23, + "character": 7 + } + } + ], + "arktsVersion_1_1": [] +} \ No newline at end of file diff --git a/tests/arkTSTest/testcase/arkts-no-props-by-index/arkts-no-props-by-index-12-ok.ets b/tests/arkTSTest/testcase/arkts-no-props-by-index/arkts-no-props-by-index-12-ok.ets new file mode 100644 index 0000000000000000000000000000000000000000..124db910fca229a8bd01541e6d5f087e72959d82 --- /dev/null +++ b/tests/arkTSTest/testcase/arkts-no-props-by-index/arkts-no-props-by-index-12-ok.ets @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * 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. + */ + +const arrayLike: ArrayLike = [1, 2, 3]; +arrayLike[0]; + +const concatArray: ConcatArray = [1]; +concatArray[0]; \ No newline at end of file diff --git a/tests/arkTSTest/testcase/arkts-no-props-by-index/arkts-no-props-by-index-12-ok.json b/tests/arkTSTest/testcase/arkts-no-props-by-index/arkts-no-props-by-index-12-ok.json new file mode 100644 index 0000000000000000000000000000000000000000..27f2271930a16e3a6eef2797ef552f56afd1417d --- /dev/null +++ b/tests/arkTSTest/testcase/arkts-no-props-by-index/arkts-no-props-by-index-12-ok.json @@ -0,0 +1,4 @@ +{ + "arktsVersion_1_0": [], + "arktsVersion_1_1": [] +} \ No newline at end of file diff --git a/tests/arkTSTest/testcase/arkts-no-spread/arkts-no-spread-11-ok.ets b/tests/arkTSTest/testcase/arkts-no-spread/arkts-no-spread-11-ok.ets new file mode 100644 index 0000000000000000000000000000000000000000..1d4929ad4b7614b0f5c6b0ffc29f1af30dccbe46 --- /dev/null +++ b/tests/arkTSTest/testcase/arkts-no-spread/arkts-no-spread-11-ok.ets @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * 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. + */ + +// Description: Expand the subclass of Array + +import collections from '../common-lib/@arkts.collections'; + +const arr: collections.BitVector = new collections.BitVector(10); +arr[0] = 1; +const targetArr: number[] = [...arr]; \ No newline at end of file diff --git a/tests/arkTSTest/testcase/arkts-no-spread/arkts-no-spread-11-ok.json b/tests/arkTSTest/testcase/arkts-no-spread/arkts-no-spread-11-ok.json new file mode 100644 index 0000000000000000000000000000000000000000..11fe10e50a45fc3f8180eae87ff57b9da58ab354 --- /dev/null +++ b/tests/arkTSTest/testcase/arkts-no-spread/arkts-no-spread-11-ok.json @@ -0,0 +1,33 @@ +{ + "arktsVersion_1_0": [ + { + "messageText": "No decorators except ArkUI decorators are currently allowed (arkts-no-decorators-except-arkui)", + "expectLineAndCharacter": { + "line": 17, + "character": 3 + } + }, + { + "messageText": "Indexed signatures are not supported (arkts-no-indexed-signatures)", + "expectLineAndCharacter": { + "line": 19, + "character": 5 + } + }, + { + "messageText": "Indexed access is not supported for fields (arkts-no-props-by-index)", + "expectLineAndCharacter": { + "line": 21, + "character": 1 + } + }, + { + "messageText": "It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread)", + "expectLineAndCharacter": { + "line": 22, + "character": 30 + } + } + ], + "arktsVersion_1_1": [] +} \ No newline at end of file diff --git a/tests/arkTSTest/testcase/common-lib/@arkts.collections.d.ets b/tests/arkTSTest/testcase/common-lib/@arkts.collections.d.ets new file mode 100644 index 0000000000000000000000000000000000000000..d25d68742f2c6a871fcd2959b99cb409b5223f0d --- /dev/null +++ b/tests/arkTSTest/testcase/common-lib/@arkts.collections.d.ets @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * 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. + */ + +declare namespace collections { + @Sendable + class BitVector { + [index: number]: number; + } +} + +export default collections; \ No newline at end of file diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 9219c3dbb2a44b1a101a2e622c076b109f9ce117..979482643ce56d33c84da5d1d4fe8da8f503b024 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -4600,6 +4600,24 @@ declare namespace ts { export let sys: System; export {}; } +declare namespace ts { + namespace MemoryDotting { + interface RecordInfo { + recordStage: string; + recordIndex: number; + } + const BINDE_SOURCE_FILE = "binder(bindSourceFile: Bind)"; + const CHECK_SOURCE_FILE = "checker(checkSourceFile: Check)"; + const EMIT_FILES = "emitter(emitFiles: EmitEachOutputFile)"; + const CREATE_SORUCE_FILE_PARSE = "parser(createSourceFile: Parse)"; + const BEFORE_PROGRAM = "program(createProgram: beforeProgram)"; + const TRANSFORM = "transformer(transformNodes: Transform)"; + function recordStage(stage: string): RecordInfo | null; + function stopRecordStage(recordInfo: RecordInfo | null): void; + function setMemoryDottingCallBack(recordCallback: (stage: string) => RecordInfo, stopCallback: (recordInfo: RecordInfo) => void): void; + function clearCallBack(): void; + } +} declare namespace ts { type ErrorCallback = (message: DiagnosticMessage, length: number) => void; interface Scanner { @@ -5468,8 +5486,8 @@ declare namespace ts { function pathContainsOHModules(path: string): boolean; function choosePathContainsModules(packageManagerType: string | undefined, fileName: string): boolean; function getTypeExportImportAndConstEnumTransformer(context: TransformationContext): (node: SourceFile) => SourceFile; - function getAnnotationTransformer(relativeFilePath: string): TransformerFactory; - function transformAnnotation(context: TransformationContext, relativeFilePath: string): (node: SourceFile) => SourceFile; + function getAnnotationTransformer(): TransformerFactory; + function transformAnnotation(context: TransformationContext): (node: SourceFile) => SourceFile; /** * Add 'type' flag to import/export when import/export an type member. * Replace const enum with number and string literal. @@ -13326,8 +13344,12 @@ declare namespace ts { function isTypeSymbol(symbol: Symbol | undefined): boolean; function isGenericArrayType(tsType: Type): tsType is TypeReference; function isReadonlyArrayType(tsType: Type): boolean; - function isTypedArray(tsType: ts.Type): boolean; + function isConcatArrayType(tsType: Type): boolean; + function isArrayLikeType(tsType: Type): boolean; + function isTypedArray(tsType: ts.Type, allowTypeArrays: string[]): boolean; function isArray(tsType: ts.Type): boolean; + function isCollectionArrayType(tsType: ts.Type): boolean; + function isIndexableArray(tsType: ts.Type): boolean; function isTuple(tsType: ts.Type): boolean; function isOrDerivedFrom(tsType: ts.Type, checkType: CheckType, checkedBaseTypes?: Set): boolean; function isTypeReference(tsType: Type): tsType is TypeReference; @@ -13382,6 +13404,7 @@ declare namespace ts { const NON_RETURN_FUNCTION_DECORATORS: string[]; const STANDARD_LIBRARIES: string[]; const TYPED_ARRAYS: string[]; + const TYPED_COLLECTIONS: string[]; function getParentSymbolName(symbol: Symbol): string | undefined; function isGlobalSymbol(symbol: Symbol): boolean; function isSymbolAPI(symbol: Symbol): boolean; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 40cd06e4080f1e4b1a5fe19e9bf6c7e136580bfb..8549ac7989321380d8127e8fa4c1c5a0f6364a0e 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -4600,6 +4600,24 @@ declare namespace ts { export let sys: System; export {}; } +declare namespace ts { + namespace MemoryDotting { + interface RecordInfo { + recordStage: string; + recordIndex: number; + } + const BINDE_SOURCE_FILE = "binder(bindSourceFile: Bind)"; + const CHECK_SOURCE_FILE = "checker(checkSourceFile: Check)"; + const EMIT_FILES = "emitter(emitFiles: EmitEachOutputFile)"; + const CREATE_SORUCE_FILE_PARSE = "parser(createSourceFile: Parse)"; + const BEFORE_PROGRAM = "program(createProgram: beforeProgram)"; + const TRANSFORM = "transformer(transformNodes: Transform)"; + function recordStage(stage: string): RecordInfo | null; + function stopRecordStage(recordInfo: RecordInfo | null): void; + function setMemoryDottingCallBack(recordCallback: (stage: string) => RecordInfo, stopCallback: (recordInfo: RecordInfo) => void): void; + function clearCallBack(): void; + } +} declare namespace ts { type ErrorCallback = (message: DiagnosticMessage, length: number) => void; interface Scanner { @@ -5468,8 +5486,8 @@ declare namespace ts { function pathContainsOHModules(path: string): boolean; function choosePathContainsModules(packageManagerType: string | undefined, fileName: string): boolean; function getTypeExportImportAndConstEnumTransformer(context: TransformationContext): (node: SourceFile) => SourceFile; - function getAnnotationTransformer(relativeFilePath: string): TransformerFactory; - function transformAnnotation(context: TransformationContext, relativeFilePath: string): (node: SourceFile) => SourceFile; + function getAnnotationTransformer(): TransformerFactory; + function transformAnnotation(context: TransformationContext): (node: SourceFile) => SourceFile; /** * Add 'type' flag to import/export when import/export an type member. * Replace const enum with number and string literal. @@ -9380,8 +9398,12 @@ declare namespace ts { function isTypeSymbol(symbol: Symbol | undefined): boolean; function isGenericArrayType(tsType: Type): tsType is TypeReference; function isReadonlyArrayType(tsType: Type): boolean; - function isTypedArray(tsType: ts.Type): boolean; + function isConcatArrayType(tsType: Type): boolean; + function isArrayLikeType(tsType: Type): boolean; + function isTypedArray(tsType: ts.Type, allowTypeArrays: string[]): boolean; function isArray(tsType: ts.Type): boolean; + function isCollectionArrayType(tsType: ts.Type): boolean; + function isIndexableArray(tsType: ts.Type): boolean; function isTuple(tsType: ts.Type): boolean; function isOrDerivedFrom(tsType: ts.Type, checkType: CheckType, checkedBaseTypes?: Set): boolean; function isTypeReference(tsType: Type): tsType is TypeReference; @@ -9436,6 +9458,7 @@ declare namespace ts { const NON_RETURN_FUNCTION_DECORATORS: string[]; const STANDARD_LIBRARIES: string[]; const TYPED_ARRAYS: string[]; + const TYPED_COLLECTIONS: string[]; function getParentSymbolName(symbol: Symbol): string | undefined; function isGlobalSymbol(symbol: Symbol): boolean; function isSymbolAPI(symbol: Symbol): boolean; diff --git a/tests/system_api_test/README.md b/tests/system_api_test/README.md new file mode 100644 index 0000000000000000000000000000000000000000..35c6b06c29807aab279ce8440875c2cba60cfd32 --- /dev/null +++ b/tests/system_api_test/README.md @@ -0,0 +1,37 @@ +# 说明 + +这是tsc系统api测试套,用来确保每次在tsc的lib库中新增的接口被添加到混淆的预置语言白名单中,避免因为被混淆而出现功能问题 + +# 测试步骤 + +0. 环境准备: + * node版本不低于6.0.0 + * 需要拉取typescript仓和arkguard仓的代码 + +1. 执行npm install + +2. 如果在tsc的lib目录中新增了文件,需要将文件名添加到system_api_test.ts的scanFilesList数组中,其他情况则不需要 + +3. 执行npm run test:system-api或者执行npm run alltest + +# 查看结果 + +命令行的结果中会打印如下信息: + +``` +----------------------------- System Api Test summary ----------------------------- +Run result:success! +Scan file counts: 45 +Number of missing system api: 0 +Missing system api: [] +``` + +上面的信息依次为扫描的lib库中的文件数量,混淆预置语言白名单中缺少的system api数量和具体名称,测试套执行结果 + +# 期望结果 + +缺少的system api的数量为零,测试套执行结果为success + +# 测试套结果为fail时的处理方式 + +将缺少的system api名称同步添加到arkguard仓的es_reserved_properties.json和es_reserved_properties_optimized.json文件中 diff --git a/tests/system_api_test/system_api_test.ts b/tests/system_api_test/system_api_test.ts new file mode 100644 index 0000000000000000000000000000000000000000..393614b9b0ec3179622d83d693de0d3fb5a7a272 --- /dev/null +++ b/tests/system_api_test/system_api_test.ts @@ -0,0 +1,179 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * 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. + */ + +import * as fs from 'fs'; +import * as path from 'path'; +import { parse } from 'json5'; +import { + createSourceFile, + forEachChild, + isComputedPropertyName, + isParameter, + isPropertyAccessExpression, + isStringLiteral, + isTypeParameterDeclaration, + ScriptTarget + } from 'typescript'; + +export const visitTscLibNode = (astNode): void => { + if (!astNode || !astNode.name) { + return; + } + let nameToAdd: string; + if (isStringLiteral(astNode.name)) { + nameToAdd = astNode.name.text; + } else if (isComputedPropertyName(astNode.name)) { + nameToAdd = isPropertyAccessExpression(astNode.name.expression) ? + undefined : astNode.name.expression.getText(); + } else { + nameToAdd = astNode.name.getText(); + } + + if (nameToAdd && !isParameter(astNode) && !isTypeParameterDeclaration(astNode)) { + resultSet.add(nameToAdd); + } + + forEachChild(astNode, visitTscLibNode); +}; + +interface SystemApiWhitelist { + [key: string]: string[]; +} +const runTest = (files: string[], expectedFilePath: string, directoryPath: string): void => { + let systemApiWhitelist: SystemApiWhitelist = { + es2015: [], es2016: [], es2017: [], es2018: [], es2019: [], es2020: [], es2021: [] + }; + + if (fs.existsSync(expectedFilePath)) { + systemApiWhitelist = parse(fs.readFileSync(expectedFilePath, 'utf-8')); + } else { + console.error(`LanguageWhitelist file does not exist in the directory ${expectedFilePath}`); + } + + for (const key of Object.keys(systemApiWhitelist)) { + systemApiWhitelist[key].forEach(element => expectSet.add(element)); + } + + files.forEach(fileName => { + const filePath = path.join(directoryPath, fileName); + if (fs.existsSync(filePath)) { + fileCount++; + const sourceFile = createSourceFile(fileName, fs.readFileSync(filePath).toString(), ScriptTarget.ES2015, true); + forEachChild(sourceFile, visitTscLibNode); + } else { + console.error(`File ${fileName} does not exist in the directory ${directoryPath}`); + } + }); + + const missingElements: string[] = []; + resultSet.forEach(element => { + if (!expectSet.has(element) && !skipElements.includes(element)) { + missingElements.push(element); + } + }); + + const result: string = (fileCount === scanFilesList.length) && (missingElements.length === 0) ? + 'success!' : 'fail!'; + console.log('----------------------------- System Api Test summary -----------------------------'); + console.log('Run result:', result); + console.log('Scan file counts:', fileCount); + console.log('Number of missing system api:', missingElements.length); + console.log('Missing system api:', missingElements); +}; + +const scanFilesList: string[] = [ + 'lib.es2015.collection.d.ts', + 'lib.es2015.core.d.ts', + 'lib.es2015.d.ts', + 'lib.es2015.generator.d.ts', + 'lib.es2015.iterable.d.ts', + 'lib.es2015.promise.d.ts', + 'lib.es2015.proxy.d.ts', + 'lib.es2015.reflect.d.ts', + 'lib.es2015.symbol.d.ts', + 'lib.es2015.symbol.wellknown.d.ts', + 'lib.es2016.array.include.d.ts', + 'lib.es2016.d.ts', + 'lib.es2017.d.ts', + 'lib.es2017.intl.d.ts', + 'lib.es2017.object.d.ts', + 'lib.es2017.sharedmemory.d.ts', + 'lib.es2017.string.d.ts', + 'lib.es2017.typedarrays.d.ts', + 'lib.es2018.asyncgenerator.d.ts', + 'lib.es2018.asynciterable.d.ts', + 'lib.es2018.d.ts', + 'lib.es2018.intl.d.ts', + 'lib.es2018.promise.d.ts', + 'lib.es2018.regexp.d.ts', + 'lib.es2019.array.d.ts', + 'lib.es2019.d.ts', + 'lib.es2019.intl.d.ts', + 'lib.es2019.object.d.ts', + 'lib.es2019.string.d.ts', + 'lib.es2019.symbol.d.ts', + 'lib.es2020.bigint.d.ts', + 'lib.es2020.date.d.ts', + 'lib.es2020.d.ts', + 'lib.es2020.intl.d.ts', + 'lib.es2020.number.d.ts', + 'lib.es2020.promise.d.ts', + 'lib.es2020.sharedmemory.d.ts', + 'lib.es2020.string.d.ts', + 'lib.es2020.symbol.wellknown.d.ts', + 'lib.es2021.d.ts', + 'lib.es2021.intl.d.ts', + 'lib.es2021.promise.d.ts', + 'lib.es2021.string.d.ts', + 'lib.es2021.weakref.d.ts', + 'lib.es5.d.ts', +]; +const skipElements: string[] = [ + 'MapConstructor', + 'ReadonlyMap', + 'WeakMapConstructor', + 'SetConstructor', + 'ReadonlySet', + 'WeakSetConstructor', + 'Generator', + 'GeneratorFunction', + 'GeneratorFunctionConstructor', + 'IteratorYieldResult', + 'IteratorReturnResult', + 'IteratorResult', + 'Iterable', + 'IterableIterator', + 'ProxyHandler', + 'ProxyConstructor', + 'proxy', + 'revoke', + 'literal', + 'DateTimeFormatPartTypes', + 'DateTimeFormatPart', + 'SharedArrayBufferConstructor', + 'recur', + 'BigUint64ArrayConstructor', + 'ImportCallOptions', + 'ImportAssertions', + 'Awaited', + 'ESObject' +]; +const expectedFilePath = path.join(__dirname, '../../../../arkcompiler/ets_frontend/arkguard/src/configs/preset/es_reserved_properties_optimized.json'); +const directoryPath = path.join(__dirname, '../../lib'); +let fileCount: number = 0; +let resultSet: Set = new Set(); +let expectSet: Set = new Set(); + +runTest(scanFilesList, expectedFilePath, directoryPath); \ No newline at end of file