From 7e3f31e39ea755059b3fe06565ff985390cf9c0c Mon Sep 17 00:00:00 2001 From: jinzhao Date: Wed, 22 Jan 2025 10:25:37 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E4=BB=A3=E7=A0=81=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: jinzhao --- src/vscode_plugin/src/datatype.ts | 12 ++- src/vscode_plugin/src/extension.ts | 102 ++++++++++-------- src/vscode_plugin/src/gencpp.ts | 9 +- src/vscode_plugin/src/gendts.ts | 3 +- src/vscode_plugin/src/gendtscpp.ts | 9 +- src/vscode_plugin/src/genhdf.ts | 9 +- src/vscode_plugin/src/gensa.ts | 66 ++++++++---- src/vscode_plugin/src/ohcrosscompile.ts | 60 ++++------- src/vscode_plugin/src/parsec.ts | 51 ++++++--- src/vscode_plugin/src/parsets.ts | 21 ++-- .../src/template/functypemap_template.ts | 3 +- 11 files changed, 202 insertions(+), 143 deletions(-) diff --git a/src/vscode_plugin/src/datatype.ts b/src/vscode_plugin/src/datatype.ts index eb346d58..bccf4136 100644 --- a/src/vscode_plugin/src/datatype.ts +++ b/src/vscode_plugin/src/datatype.ts @@ -88,9 +88,11 @@ export interface ServiceRootInfo { } export interface HdfRootInfo { - driverName: string; // driverName即为文件名字 + // driverName即为文件名字 + driverName: string; funcs: FuncObj[]; - versionTag: string; // 默认4.1 + // 默认4.1 + versionTag: string; } export interface FuncTransferMap { @@ -121,8 +123,10 @@ export interface FuncInfo { // 保存 typedefine int cJSON_bool export interface TypeList { - typeName: string; // cJSON_bool - typeBody: string; // int + // cJSON_bool + typeName: string; + // int + typeBody: string; } export interface InterfaceBody { diff --git a/src/vscode_plugin/src/extension.ts b/src/vscode_plugin/src/extension.ts index 8dc58823..c9adac73 100644 --- a/src/vscode_plugin/src/extension.ts +++ b/src/vscode_plugin/src/extension.ts @@ -29,7 +29,7 @@ import { genDtsFile } from './gendts'; import { genHdfFile } from './genhdf'; import { genDtsCppFile, genCppFile } from './gendtscpp'; -// ȡػַ +// 获取本地化字符串 const SELECTED_DIR = vscode.l10n.t('You selected a directory:'); const SELECTE_DIR = vscode.l10n.t('Please select a directory.'); const NO_RES_SELECTED = vscode.l10n.t('No resource selected.'); @@ -101,16 +101,17 @@ export function activate(context: vscode.ExtensionContext) { } const canCmake = fs.existsSync(thirdPartyPath.concat("/CMakeLists.txt")); const canMake = fs.existsSync(thirdPartyPath.concat("/GNUmakefile")) || fs.existsSync(thirdPartyPath.concat("/Makefile")) || fs.existsSync(thirdPartyPath.concat("/makefile")); - if (canCmake || canMake) { //⵽CMakeLists.txtmakefileԼ - - - // ûвļСװļУ򴴽ԶȡװĿ¼ + + + // 如果检测到CMakeLists.txt或makefile,则可以继续 + if (canCmake || canMake) { + // 若没有插件文件夹、安装文件夹,则创建。可自动获取到安装目录 const ohCrossCompilePath = thirdPartyPath.concat("/ohCrossCompile"); if (!fs.existsSync(ohCrossCompilePath)) { fs.mkdirSync(ohCrossCompilePath); } - // ûļĬôļ + // 若没有配置文件,则以默认配置创建配置文件 const configPath = ohCrossCompilePath.concat("/config.json") if (!fs.existsSync(configPath)) { const defaultConfig = { @@ -140,11 +141,11 @@ export function activate(context: vscode.ExtensionContext) { fs.writeFileSync(configPath, JSON.stringify(defaultConfig, null, 4), 'utf8'); } - // ȡ뷽ʽmakecmake - if (configContent.settings.compileTool !== undefined && (configContent.settings.compileTool === "make" || configContent.settings.compileTool === "cmake")) { //ļѾ洢뷽ʽ + // 获取编译方式是make还是cmake + if (configContent.settings.compileTool !== undefined && (configContent.settings.compileTool === "make" || configContent.settings.compileTool === "cmake")) { //如果配置文件中已经存储编译方式,则获得 compileTool = configContent.settings.compileTool; - } else if (canCmake && canMake) { //Զжϳmakecmakeʹãѯû洢 - + } else if (canCmake && canMake) { + // 若自动判断出make与cmake均可使用,则询问用户,并存储结果 const toolPickItems = [ { label: "make", @@ -171,19 +172,22 @@ export function activate(context: vscode.ExtensionContext) { vscode.window.showInformationMessage(COMPILATION_METHOD_LOST); return; } - } else if (canCmake) { //Զжϳֻʹcmake + } else if (canCmake) { + // 若自动判断出只可以使用cmake compileTool = "cmake"; configContent.settings.compileTool = "cmake"; fs.writeFileSync(configPath, JSON.stringify(configContent, null, 4), 'utf8'); - } else { //Զжϳֻʹmake + } else { + // 若自动判断出只可以使用make compileTool = "make"; configContent.settings.compileTool = "make"; fs.writeFileSync(configPath, JSON.stringify(configContent, null, 4), 'utf8'); } - // ȷҪCPUܹװļ򴴽 - if (configContent.settings.ohArchitecture === undefined || configContent.settings.ohArchitecture.length === 0) { //ļ޷ȷCPUܹѯû + // 确认要编译的CPU架构。安装文件夹若不存在则创建 + if (configContent.settings.ohArchitecture === undefined || configContent.settings.ohArchitecture.length === 0) { + // 若根据配置文件无法确定CPU架构参数,则询问用户 const archPickItems = [ { label: "arm64-v8a", @@ -201,7 +205,8 @@ export function activate(context: vscode.ExtensionContext) { title: OH_CROSS_COMPILE_TITLE }; const archPick = await vscode.window.showQuickPick(archPickItems, archPickOptions) - if (archPick && Array.isArray(archPick) && archPick.length > 0) { //ûѡϢļ + if (archPick && Array.isArray(archPick) && archPick.length > 0) { + // 获得用户选择的信息,并存入配置文件 for (let item of archPick) { let arch = item.label; ohArchitecture.push(arch); @@ -240,10 +245,10 @@ export function activate(context: vscode.ExtensionContext) { } - // ȷsdknativeߵ· - if (configContent.settings.nativePath === undefined || configContent.settings.nativePath === "") { //ѯû + // 确认sdk中native工具的路径 + if (configContent.settings.nativePath === undefined || configContent.settings.nativePath === "") { - // ȷsdkԴDZػ + // 询问用户。确认sdk来源是本地还是下载 const sourcePickItems = [ { label: LOCAL, @@ -263,7 +268,8 @@ export function activate(context: vscode.ExtensionContext) { const sourcePick = await vscode.window.showQuickPick(sourcePickItems, sourcePickOptions); if (sourcePick) { - if (sourcePick.label === LOCAL) { //sdkԴΪأѯûnativeڵľ·ǷϷ + // 若sdk来源为本地,则询问用户native所在的具体路径,并检查是否合法 + if (sourcePick.label === LOCAL) { const folderUri = await vscode.window.showOpenDialog({ canSelectMany: false, canSelectFolders: true, @@ -279,7 +285,7 @@ export function activate(context: vscode.ExtensionContext) { configContent.settings.nativePath = folderPath; fs.writeFileSync(configPath, JSON.stringify(configContent, null, 4), 'utf8'); - // ִб + // 执行编译命令 crossCompile(platform, undefined, configPath, thirdPartyPath, compileTool, ohArchitecture, nativePath, ohCrossCompilePath); } else { vscode.window.showInformationMessage(NATIVE_CHECK_FAILED); @@ -289,8 +295,9 @@ export function activate(context: vscode.ExtensionContext) { vscode.window.showInformationMessage(FOLDER_LOST); return; } - } else if (sourcePick.label === DOWNLOAD) { //sdkԴΪ磬ѯذ汾·زѹsdk - // ȡذ汾Ӷ + } else if (sourcePick.label === DOWNLOAD) { + // 若sdk来源为网络,则询问下载版本与下载路径,下载并解压sdk + // 获取下载版本,从而获得下载链接 const versionPickItems = [ { label: API9_LABEL, @@ -338,7 +345,7 @@ export function activate(context: vscode.ExtensionContext) { break; } - // ѯ· + // 询问下载路径 const folderUri = await vscode.window.showOpenDialog({ canSelectMany: false, canSelectFolders: true, @@ -351,7 +358,7 @@ export function activate(context: vscode.ExtensionContext) { } let filePath = folderPath.concat("/ohos-sdk-windows_linux-public.tar.gz"); - // زѹsdkеnative + // 下载并解压sdk中的native await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: DOWNLOADING_TITLE, @@ -362,23 +369,27 @@ export function activate(context: vscode.ExtensionContext) { vscode.window.showInformationMessage(vscode.l10n.t('SDK downloaded to: {0}', filePath)); // vscode.window.showInformationMessage(`SDK downloaded to: ${filePath}`); - // ѹsdkеnativeƴװnativePath + // 解压sdk中的native,并拼装nativePath progress.report({ increment: 10, message: DOWNLOADING_COMPLETE }); await extractTarGz(filePath, folderPath); progress.report({ increment: 100, message: SDK_INSTALLED }); nativePath = folderPath; - if (apiVersion !== API12_LABEL) { //api12汾·ûohos-sdk9-11汾 + if (apiVersion !== API12_LABEL) { + // api12版本路径中没有ohos-sdk;9-11版本则有 nativePath = nativePath.concat("/ohos-sdk"); } if (platform === "win32") { - nativePath = nativePath.concat("/windows"); //windowsϵͳµnativePath· + // windows系统下的nativePath路径 + nativePath = nativePath.concat("/windows"); } else { - nativePath = nativePath.concat("/linux"); //linuxϵͳµnativePath· + // linux系统下的nativePath路径 + nativePath = nativePath.concat("/linux"); } for (const file of await fs.promises.readdir(nativePath)) { if (file.startsWith("native")) { - filePath = nativePath.concat("/" + file); //ȡnativeѹļ· + // 获取native压缩包的文件路径 + filePath = nativePath.concat("/" + file); } } console.log(filePath); @@ -389,7 +400,7 @@ export function activate(context: vscode.ExtensionContext) { configContent.settings.nativePath = nativePath; fs.writeFileSync(configPath, JSON.stringify(configContent, null, 4), 'utf8'); - // ִб + // 执行编译命令 crossCompile(platform, terminal, configPath, thirdPartyPath, compileTool, ohArchitecture, nativePath, ohCrossCompilePath); }); } else { @@ -405,19 +416,21 @@ export function activate(context: vscode.ExtensionContext) { vscode.window.showInformationMessage(SDK_SOURCE_LOST); return; } - } else { //ļnativePathǿգļлȡ + } else { //配置文件中nativePath非空,则从配置文件中获取 if (checkNative(platform, configContent.settings.nativePath)) { nativePath = configContent.settings.nativePath; - // ִб + // 执行编译命令 crossCompile(platform, undefined, configPath, thirdPartyPath, compileTool, ohArchitecture, nativePath, ohCrossCompilePath); - } else { //ļлȡnativePathǷãʾ + } else { + // 从配置文件中获取的nativePath非法,则重置,并提示 configContent.settings.nativePath = ""; fs.writeFileSync(configPath, JSON.stringify(configContent, null, 4), 'utf8'); vscode.window.showInformationMessage(NATIVE_CHECK_FAILED); return; } } - } else { //ûѡļвCMakeLists.extMakefile + } else { + // 用户所选文件夹不含CMakeLists.ext和Makefile vscode.window.showErrorMessage(CMAKE_MAKE_LOST); } } @@ -439,7 +452,7 @@ export function activate(context: vscode.ExtensionContext) { } const serviceId = await vscode.window.showInputBox({ placeHolder: INPUT_SERVICEID, - value: "19000", // Ĭֵ + value: "19000", // 设置默认值 validateInput: (input) => { if (!input) { return INPUT_NO_EMPTY; @@ -533,7 +546,7 @@ export function activate(context: vscode.ExtensionContext) { }); context.subscriptions.push(dts2cpp); - // ӭ˵ҳ + // 欢迎菜单页面 const ohGenerator = vscode.commands.registerCommand('extension.ohGenerator', async () => { // The code you place here will be executed every time your command is executed let hPath = path.join(__dirname, '../test/test.h'); @@ -551,7 +564,7 @@ export function activate(context: vscode.ExtensionContext) { } }); if (value === HDF_FRAMEWORK) { - // 汾 + // 输入版本 let versionTag = '4.1'; const version = await vscode.window.showQuickPick(['OpenHarmony 4.1 release'], { placeHolder: SELECT_VERSION }) if (version === 'OpenHarmony 4.1 release') { @@ -559,7 +572,7 @@ export function activate(context: vscode.ExtensionContext) { } generateHdf(hdfInputPath, versionTag); } else if (value === SA_FRAMEWORK) { - // 汾 + // 输入版本 let versionTag = '3.2'; const version = await vscode.window.showQuickPick(['OpenHarmony 3.2 release', 'OpenHarmony 4.1 release'], { placeHolder: SELECT_VERSION }) if (version === 'OpenHarmony 4.1 release') { @@ -609,10 +622,10 @@ async function generateHdf(hdfInputPath: string, versionTag: string) { genHdfFile(rootInfo, out); progress.report({ increment: 100, message: GEN_COMPLETE + out}); }); - // ʾ· + // 显示出生成路径 const choice = await vscode.window.showInformationMessage('outPath:', path.dirname(hdfInputPath), OPEN_IN_EXPLORER); if (choice === OPEN_IN_EXPLORER) { - // ļڵĿ¼ + // 打开文件所在的目录 vscode.commands.executeCommand('revealFileInOS', vscode.Uri.file(hdfInputPath)); } } @@ -642,10 +655,10 @@ async function generateSa(hPath: string, versionTag: string, serviceId: string) genServiceFile(rootInfo, out); progress.report({ increment: 100, message: GEN_COMPLETE + out }); }); - // ʾ· + // 显示出生成路径 const choice = await vscode.window.showInformationMessage('outPath:', path.dirname(hPath), OPEN_IN_EXPLORER); if (choice === OPEN_IN_EXPLORER) { - // ļڵĿ¼ + // 打开文件所在的目录 vscode.commands.executeCommand('revealFileInOS', vscode.Uri.file(hPath)); } } @@ -675,11 +688,12 @@ async function generateDtscpp(hFilePath: string) { genDtsCppFile(rootInfo, out); progress.report({ increment: 100, message: GEN_COMPLETE + out }); }); - // ʾ· + // 显示出生成路径 const choice = await vscode.window.showInformationMessage('outPath:', path.dirname(hFilePath), OPEN_IN_EXPLORER); if (choice === OPEN_IN_EXPLORER) { - // ļڵĿ¼ + // 打开文件所在的目录 vscode.commands.executeCommand('revealFileInOS', vscode.Uri.file(hFilePath)); } } + diff --git a/src/vscode_plugin/src/gencpp.ts b/src/vscode_plugin/src/gencpp.ts index d0d08a19..b5cce120 100644 --- a/src/vscode_plugin/src/gencpp.ts +++ b/src/vscode_plugin/src/gencpp.ts @@ -134,7 +134,8 @@ function getParamJs2C(funcInfo: FuncInfo, i: number, paramGenResult: string, typ } else if (paramType === 'std::string' || paramType.indexOf('char') >= 0) { paramGen = getParamGenCon(stringIn, i, paramName, paramGen); paramGenResult += paramGen; - } else if (getTypeBody(paramType, typeList)) { // typedefs + } else if (getTypeBody(paramType, typeList)) { + // typedefs funcInfo.params[i].type = getTypeBody(paramType, typeList) as string; paramGenResult = getParamJs2C(funcInfo, i, paramGenResult, typeList); } @@ -166,7 +167,8 @@ function returnTypeC2Js(returnName: string, retType: string, retGenResult: strin } else if (retType === 'std::string' || retType.substring(0, 10) === 'const char' || retType === 'char') { retGenResult = getRetTypeContent(stringRet, returnName, retGenResult, retObjInfo, objectTosetRet); - } else if (getInterfaceBody(retType, interfaceList)) { // 返回值是对象 + } else if (getInterfaceBody(retType, interfaceList)) { + // 返回值是对象 if (!retObjInfo.flag) { retGenResult += replaceAll(objectRet, '[return_name_replace]', returnName); retObjInfo.flag = true; @@ -181,7 +183,8 @@ function returnTypeC2Js(returnName: string, retType: string, retGenResult: strin } else { retGenResult = getObjRetGenResult(retObjInfo, retGenResult, returnName); } - } else if (getTypeBody(retType, typeList)) { // typedefs + } else if (getTypeBody(retType, typeList)) { + // typedefs let funcRetType = getTypeBody(retType, typeList) as string; retGenResult = returnTypeC2Js(returnName, funcRetType, retGenResult, retObjInfo,typeList, interfaceList); } diff --git a/src/vscode_plugin/src/gendts.ts b/src/vscode_plugin/src/gendts.ts index a06659c0..0b247681 100644 --- a/src/vscode_plugin/src/gendts.ts +++ b/src/vscode_plugin/src/gendts.ts @@ -362,7 +362,8 @@ export function genDtsInterface(path: string, typeList: TypeList[], interfaceLis if (basicTypeMatch) { for (let index = 0; index < basicTypeMatch.length; index++) { - console.log('Basic type typedef match:', basicTypeMatch[0]); // 输出匹配的基本类型定义 + // 输出匹配的基本类型定义 + console.log('Basic type typedef match:', basicTypeMatch[0]); let matchs = basicTypeMatch[index].split(' '); let rawType = getJsTypeFromC(matchs[1].trim()); let defineType = matchs[2].split(';') diff --git a/src/vscode_plugin/src/gendtscpp.ts b/src/vscode_plugin/src/gendtscpp.ts index bf2b45ab..dd8d6b7b 100644 --- a/src/vscode_plugin/src/gendtscpp.ts +++ b/src/vscode_plugin/src/gendtscpp.ts @@ -26,9 +26,12 @@ import { generateFuncTestCase } from "./gentest"; import { tsTransferType } from "./template/functypemap_template"; interface GenResult { - dtsContent: string; // dts文件中的内容 - testContet: string; // abilitytest文件中的内容 - napiHContent: string; // h文件中的内容 + // dts文件中的内容 + dtsContent: string; + // abilitytest文件中的内容 + testContet: string; + // h文件中的内容 + napiHContent: string; napiInitContent: string, napiCppContent: string } diff --git a/src/vscode_plugin/src/genhdf.ts b/src/vscode_plugin/src/genhdf.ts index 1a4de873..24ecc1c6 100644 --- a/src/vscode_plugin/src/genhdf.ts +++ b/src/vscode_plugin/src/genhdf.ts @@ -31,9 +31,12 @@ const TYPE_DEF_MAP = new Map( ]); interface GenResult { - idlFuncDefine: string, // idl文件中方法的定义 - hdiServiceFuncH: string, // xxx_interface_service.h文件中方法的定义 - hdiServiceFuncCpp: string, // xxx_interface_service.cpp中方法的实现 + // idl文件中方法的定义 + idlFuncDefine: string, + // xxx_interface_service.h文件中方法的定义 + hdiServiceFuncH: string, + // xxx_interface_service.cpp中方法的实现 + hdiServiceFuncCpp: string, } let nameObj = { diff --git a/src/vscode_plugin/src/gensa.ts b/src/vscode_plugin/src/gensa.ts index 8dcca228..3fe98435 100644 --- a/src/vscode_plugin/src/gensa.ts +++ b/src/vscode_plugin/src/gensa.ts @@ -44,14 +44,22 @@ interface DestObj { interface GenResult { funcEnumStr: string, - iServiceFuncH: string, //i_service.h 方法定义 - proxyFuncH: string, //proxy.h 方法定义 - stubInnerFuncH: string, // stub.h 的inner方法定义 - proxyFuncCpp: string, //proxy.cpp 方法实现 - stubInnerFuncMap: string, // stub.cpp 的inner方法映射表 - stubInnerFuncCpp: string, // stub.cpp 的inner方法实现 - serviceFuncCpp: string, // service.cpp的方法实现: 参数初始化 - clientFuncCpp: string, // client.cpp 的inner方法定义 + // i_service.h 方法定义 + iServiceFuncH: string, + // proxy.h 方法定义 + proxyFuncH: string, + // stub.h 的inner方法定义 + stubInnerFuncH: string, + // proxy.cpp 方法实现 + proxyFuncCpp: string, + // stub.cpp 的inner方法映射表 + stubInnerFuncMap: string, + // stub.cpp 的inner方法实现 + stubInnerFuncCpp: string, + // service.cpp的方法实现: 参数初始化 + serviceFuncCpp: string, + // client.cpp 的inner方法定义 + clientFuncCpp: string, }; function getParcelType(srcType: string) { @@ -162,9 +170,11 @@ function genStubInnerFunc(funcInfo: FuncObj, className: string) { innerFunc = replaceAll(innerFunc, '[funcName]', funcInfo.name); // 入参处理 - let readDataStr = ''; // 生成服务端读取客户端传参的代码段 + // 生成服务端读取客户端传参的代码段 + let readDataStr = ''; let tab = getTab(1); - let innerParamStr = ''; // 调用业务方法时传入的入参列表 + // 调用业务方法时传入的入参列表 + let innerParamStr = ''; for (let i = 0; i < funcInfo.parameters.length; ++i) { let param = funcInfo.parameters[i]; let innerParamName = param.name + 'Val'; @@ -174,7 +184,8 @@ function genStubInnerFunc(funcInfo: FuncObj, className: string) { } //将remote请求中的参数值读取到内部参数变量中 - readDataStr += format('%s %s;', param.type, innerParamName); // 定义内部参数变量 + // 定义内部参数变量 + readDataStr += format('%s %s;', param.type, innerParamName); let destObj = { 'name': param.name + 'Val', 'type': param.type @@ -185,7 +196,8 @@ function genStubInnerFunc(funcInfo: FuncObj, className: string) { innerFunc = replaceAll(innerFunc, '[readData]', readDataStr); // 调用service的实际业务逻辑实现方法 - let writeReplyStr = ''; // 生成调用服务端实现并返回结果的代码段 + // 生成调用服务端实现并返回结果的代码段 + let writeReplyStr = ''; if (funcInfo.returns === 'void') { writeReplyStr += format('%s(%s); // call business implementation', funcInfo.name, innerParamStr); writeReplyStr += '\n' + tab + 'reply.WriteInt32(retCode);'; @@ -215,7 +227,8 @@ function genServiceFunc(funcInfo: FuncObj, className: string, paramStr: string) initRetvalue = ''; } else { // 对于其他类型,这里可以根据需要进行处理 - initRetvalue = 'nullptr'; // 假设是指针类型或其他复杂类型 + // 假设是指针类型或其他复杂类型 + initRetvalue = 'nullptr'; }8 serviceFunc = replaceAll(serviceFunc, '[initRetvalue]', initRetvalue); serviceFunc = replaceAll(serviceFunc, '[serviceName]', className); @@ -228,20 +241,29 @@ function generateFunctionCode(rootInfo: ServiceRootInfo) { let funcList: FuncObj[] = rootInfo.funcs; let genResult: GenResult = { funcEnumStr:'', - iServiceFuncH: '', // i_service.h 方法定义 - proxyFuncH: '', // proxy.h 方法定义 - stubInnerFuncH: '', // stub.h 的inner方法定义 - proxyFuncCpp: '', // proxy.cpp 方法实现 - stubInnerFuncMap: '', // stub.cpp 的inner方法映射表 - stubInnerFuncCpp: '', // stub.cpp 的inner方法实现 - serviceFuncCpp: '', // service.cpp的方法实现: 参数初始化 - clientFuncCpp: '', // client.cpp 的inner方法定义 + // i_service.h 方法定义 + iServiceFuncH: '', + // proxy.h 方法定义 + proxyFuncH: '', + // stub.h 的inner方法定义 + stubInnerFuncH: '', + // proxy.cpp 方法实现 + proxyFuncCpp: '', + // stub.cpp 的inner方法映射表 + stubInnerFuncMap: '', + // stub.cpp 的inner方法实现 + stubInnerFuncCpp: '', + // service.cpp的方法实现: 参数初始化 + serviceFuncCpp: '', + // client.cpp 的inner方法定义 + clientFuncCpp: '', }; let enumTab = getTab(2); let funcTab = getTab(1); for (let i = 0; i < funcList.length; ++i) { - let funcEnum = funcList[i].name.toUpperCase(); // remote方法的枚举值 + // remote方法的枚举值 + let funcEnum = funcList[i].name.toUpperCase(); // 生成proxy端的方法 let paramStr = getFuncParamStr(funcList[i].parameters); // proxy.h中的方法定义 diff --git a/src/vscode_plugin/src/ohcrosscompile.ts b/src/vscode_plugin/src/ohcrosscompile.ts index e65a065c..bb4abcb9 100644 --- a/src/vscode_plugin/src/ohcrosscompile.ts +++ b/src/vscode_plugin/src/ohcrosscompile.ts @@ -44,35 +44,32 @@ export function checkNative(platform: string, nativePath: string): boolean { // 下载url所指示的sdk文件,到destination所指示的文件中 export function downloadSdk(url: string, destination: string, progress: vscode.Progress<{ increment: number, message?: string }>): Promise { return new Promise((resolve, reject) => { - const file = fs.createWriteStream(destination); //创建写入文件流 + // 创建写入文件流 + const file = fs.createWriteStream(destination); https.get(url, (response) => { if (response.statusCode === 200) { - const totalSize = parseInt(String(response.headers['content-length'])); //单位Byte + const totalSize = parseInt(String(response.headers['content-length'])); console.log(`totalSize: ${totalSize}`); let downloadedSize = 0; - response.on('data', (chunk) => { //设置response的data事件,当每接收一个数据块时,计算下载进度并报告 + response.on('data', (chunk) => { + // 设置response的data事件,当每接收一个数据块时,计算下载进度并报告 downloadedSize += chunk.length; const percentage = (downloadedSize / totalSize) * 100; - - // increment是一个累加量,应每次累加当前数据块大小占总大小的比例 - // progress.report({ increment: ((chunk.length / totalSize) * 100 * 0.8), message: `Downloading SDK ... ${percentage.toFixed(2)}%` }); progress.report({ increment: ((chunk.length / totalSize) * 100 * 0.8), message: vscode.l10n.t('Downloading SDK ... {0}%', percentage.toFixed(2)) }); }); - response.pipe(file); //根据https请求返回的数据写入文件 - file.on('finish', () => { //当所有数据已被写入时,触发finish事件,关闭文件并用resolve更新Promise状态为完成 + response.pipe(file); + file.on('finish', () => { file.close(); resolve(); }); } else { - // vscode.window.showErrorMessage(`Connection failed! Statuscode: ${response.statusCode}`); - // reject(new Error(`Failed to get '${url}' (${response.statusCode})`)); if (response.statusCode) { vscode.window.showErrorMessage(vscode.l10n.t('Connection failed! Statuscode: {0}', response.statusCode)); reject(new Error(vscode.l10n.t('Failed to get \'{0}\' ({1})', url, response.statusCode))); } } - }).on('error', (err) => { //若https请求错误,则使用fs提供的unlink方法删除目标路径的文件,在unlink方法的回调函数中,用reject更新Promise状态为出错,并传递错误信息err + }).on('error', (err) => { fs.unlink(destination, () => reject(err)); }); }); @@ -82,30 +79,16 @@ export function downloadSdk(url: string, destination: string, progress: vscode.P export function extractTarGz(filePath: string, destination: string): Promise { return new Promise((resolve, reject) => { fs.createReadStream(filePath) - .pipe(zlib.createGunzip()) // 解压 .gz - .pipe(tar.extract({ // 解压 .tar 内容 - cwd: destination // 解压到指定文件夹 + .pipe(zlib.createGunzip()) + .pipe(tar.extract({ + cwd: destination })) .on('finish', () => resolve()) .on('error', (err) => reject(err)); }); } -// 提取filePath所指示的.zip文件,到destination所指示的文件夹中 -// export function extractZip(filePath: string, destination: string): Promise { -// return new Promise((resolve, reject) => { -// fs.createReadStream(filePath) -// .pipe(unzipper.Extract({ path: destination })) // 解压 .zip -// .on('close', () => { -// resolve(); -// }) -// .on('error', (err) => reject(err)); -// }); -// } - // 利用终端命令,提取filePath所指示的.zip文件,到destination所指示的文件夹中 -// filePath: d:\Music\11\ohos-sdk\linux\native-linux-x64-4.1.7.5-Release.zip -// destination: d:\Music\11\ohos-sdk\linux export function extractZip(platform: string, terminal: vscode.Terminal, filePath: string, destination: string): Promise { return new Promise((resolve, reject) => { if (platform === "win32") { @@ -115,7 +98,6 @@ export function extractZip(platform: string, terminal: vscode.Terminal, filePath resolve(); }, (err) => { - // vscode.window.showErrorMessage(`Error extracting file: ${err}`); vscode.window.showErrorMessage(vscode.l10n.t('Error extracting file: {0}', err)); reject(err); } @@ -141,13 +123,15 @@ function crossCompile_win32(terminal: vscode.Terminal | undefined, thirdPartyPat return new Promise((resolve, reject) => { vscode.window.showInformationMessage(WINDOWS_START); - if (terminal === undefined) { //若使用本地的sdk,不进行解压操作,则terminal为undefined,在编译前进行创建 + if (terminal === undefined) { + // 若使用本地的sdk,不进行解压操作,则terminal为undefined,在编译前进行创建 terminal = terminal = vscode.window.createTerminal({ name: TERMINAL_TITLE, }); terminal.show(); - } else { //若使用下载的sdk,解压完要切换到三方库目录所在的驱动器盘符,以便进行后续编译操作 - const driveLetter = thirdPartyPath.split('/')[0]; //获取三方库目录所在的驱动器盘符,如d: + } else { + // 若使用下载的sdk,解压完要切换到三方库目录所在的驱动器盘符,以便进行后续编译操作 + const driveLetter = thirdPartyPath.split('/')[0]; terminal.sendText(`if ($?) {${driveLetter}}`); } @@ -156,7 +140,8 @@ function crossCompile_win32(terminal: vscode.Terminal | undefined, thirdPartyPat // 若配置文件中actions为空,则根据settings设置actions if (configContent.actions === undefined || configContent.actions.length === 0) { let actions = new Array(); - for (let arch of ohArchitecture) { //对每个目标系统架构,先组装出commands为空的action + for (let arch of ohArchitecture) { + // 对每个目标系统架构,先组装出commands为空的action let action = { compileTool: compileTool, ohArchitecture: arch, @@ -178,7 +163,6 @@ function crossCompile_win32(terminal: vscode.Terminal | undefined, thirdPartyPat // 对配置文件中每个action,若其commands为空,则组装出默认命令 for (let action of configContent.actions) { - // vscode.window.showInformationMessage(`Compiled files of ${action.ohArchitecture} system will be installed at ${action.installPath}. `); vscode.window.showInformationMessage(vscode.l10n.t('Compiled files of {0} system will be installed at {1}. ', action.ohArchitecture, action.installPath)); if (action.commands === undefined || action.commands.length === 0) { let commands = new Array(); @@ -262,7 +246,6 @@ function crossCompile_win32(terminal: vscode.Terminal | undefined, thirdPartyPat resolve(); }, (err) => { - // vscode.window.showErrorMessage(`Error occured while compiling. Error: ${err}`); vscode.window.showErrorMessage(vscode.l10n.t('Error occured while compiling. Error: {0}', err)); reject(err); } @@ -274,10 +257,10 @@ function crossCompile_win32(terminal: vscode.Terminal | undefined, thirdPartyPat function crossCompile_linux(terminal: vscode.Terminal | undefined, thirdPartyPath: string, configPath: string, compileTool: string, ohArchitecture: string[], nativePath: string, ohCrossCompilePath: string): Promise { return new Promise((resolve, reject) => { vscode.window.showInformationMessage(LINUX_START); - if (terminal === undefined) { //若使用本地的sdk,不进行解压操作,则terminal为undefined,在编译前进行创建 + if (terminal === undefined) { + // 若使用本地的sdk,不进行解压操作,则terminal为undefined,在编译前进行创建 terminal = terminal = vscode.window.createTerminal({ name: TERMINAL_TITLE, - // cwd: thirdPartyPath }); terminal.show(); } @@ -286,7 +269,8 @@ function crossCompile_linux(terminal: vscode.Terminal | undefined, thirdPartyPat // 若配置文件中actions为空,则根据settings设置actions if (configContent.actions === undefined || configContent.actions.length === 0) { let actions = new Array(); - for (let arch of ohArchitecture) { //对每个目标系统架构,先组装出commands为空的action + for (let arch of ohArchitecture) { + // 对每个目标系统架构,先组装出commands为空的action let action = { compileTool: compileTool, ohArchitecture: arch, diff --git a/src/vscode_plugin/src/parsec.ts b/src/vscode_plugin/src/parsec.ts index 1995d15f..9341ceb9 100644 --- a/src/vscode_plugin/src/parsec.ts +++ b/src/vscode_plugin/src/parsec.ts @@ -49,9 +49,11 @@ function parseUnion(data: string) { const unions: UnionObj[] = []; let match; while ((match = unionRegex.exec(data)) !== null) { - const unionName = match[1] || match[3] || match[4]; // 获取结构体名字 + // 获取结构体名字 + const unionName = match[1] || match[3] || match[4]; const aliasName = match[3]; - const membersString = match[2] || match[5]; // 获取成员声明 + // 获取成员声明 + const membersString = match[2] || match[5]; const members = membersString.split(';') .map(member => member.trim().replace(/[\n\r]/g, '')) .filter(member => member.length > 0); @@ -67,9 +69,12 @@ function parseUnion(data: string) { // const match = declaration.match(/(\w+)\s+(\w+)(\[(\d+)\])?/); const match = declaration.match(/(\w[\w\s\*]+)\s+(\w+)\s*/); if (match) { - const type = match[1]; // 类型 - const variable = match[2]; // 变量名 - const arrayLength = match[4] ? parseInt(match[4], 10) : -1; // 解析数组长度 + // 类型 + const type = match[1]; + // 变量名 + const variable = match[2]; + // 解析数组长度 + const arrayLength = match[4] ? parseInt(match[4], 10) : -1; // console.log(`Type: ${type}, Variable:${variable}, Size:${arrayLength}`); let paramItem: ParamObj = { "type": type, @@ -95,9 +100,11 @@ function parseStruct(data: string) { const structs: StructObj[] = []; let match; while ((match = structRegex.exec(data)) !== null) { - const structName = match[1] ||match[3] || match[4]; // 获取结构体名字 + // 获取结构体名字 + const structName = match[1] ||match[3] || match[4]; const alias = match[3]; - const membersString = match[2] || match[5]; // 获取成员声明 + // 获取成员声明 + const membersString = match[2] || match[5]; const members = membersString.split(';') .map(member => member.trim().replace(/[\n\r]/g, '')) @@ -146,7 +153,8 @@ function parseParameters(members: string[]): ParamObj[] { return { type, name, arraySize }; } return {}; - }).filter((m): m is ParamObj => m !== null); // 类型保护 + // 类型保护 + }).filter((m): m is ParamObj => m !== null); } function parseMembers(members: string[]): ParamObj[] { @@ -162,24 +170,30 @@ function parseMembers(members: string[]): ParamObj[] { return { type, name, arraySize }; } return {}; - }).filter((m): m is ParamObj => m !== null); // 类型保护 + // 类型保护 + }).filter((m): m is ParamObj => m !== null); } function parseMethods(functions: string[]): FuncObj[] { const functionRegex = /^(\w[\w\s]*\*?)\s+(\w+)\((.*?)\)$/; - // const functionRegex = /(\w+)\s+(\w+)\(([^)]*)\)/; // 正则表达式匹配返回值、函数名和参数 + // 正则表达式匹配返回值、函数名和参数 + // const functionRegex = /(\w+)\s+(\w+)\(([^)]*)\)/; return functions.map(func => { const match = func.trim().match(functionRegex); if (match) { - const returns = match[1]; // 返回值类型 - const name = match[2]; // 方法名 - const parameterstr = match[3].split(',').map(param => param.trim()).filter(Boolean); // 分割参数并去除空值 + // 返回值类型 + const returns = match[1]; + // 方法名 + const name = match[2]; + // 分割参数并去除空值 + const parameterstr = match[3].split(',').map(param => param.trim()).filter(Boolean); const parameters = parseParameters(parameterstr); return { returns, name, parameters }; } return {}; - }).filter((f): f is FuncObj => f !== null); // 类型保护 + // 类型保护 + }).filter((f): f is FuncObj => f !== null); } function parseClass(data: string) { @@ -319,9 +333,12 @@ function parseFunction(data: string): FuncObj[] { let match; while ((match = funcRegex.exec(data)) !== null) { // console.log(`func match: ${JSON.stringify(match)}`) - const returnType = match[1] ? match[1].trim() : match[6].trim(); //match[3].trim(); - const name = match[2] ? match[2].trim() : match[7].trim(); //match[4].trim(); - const params = (match[3] ? match[3] : match[8] || "").split(',').map(param => param.trim()).filter(param => param); //match[5].split(',').map(param => param.trim()).filter(param => param); + // match[3].trim(); + const returnType = match[1] ? match[1].trim() : match[6].trim(); + // match[4].trim(); + const name = match[2] ? match[2].trim() : match[7].trim(); + // match[5].split(',').map(param => param.trim()).filter(param => param); + const params = (match[3] ? match[3] : match[8] || "").split(',').map(param => param.trim()).filter(param => param); let isInterface = match[0].includes('typedef'); let funcItem: FuncObj = { "type": isInterface ? "typedef" : "function", diff --git a/src/vscode_plugin/src/parsets.ts b/src/vscode_plugin/src/parsets.ts index 867fc7d9..ebcea090 100644 --- a/src/vscode_plugin/src/parsets.ts +++ b/src/vscode_plugin/src/parsets.ts @@ -94,11 +94,15 @@ function getParamType(paramType: any) { if (paramType === undefined) { return 'void'; } - let paramText = paramType.kind === NUMBER_TYPE ? 'number' : // 类型为 number - paramType.kind === STRING_TYPE ? 'string' : // 类型为 string - paramType.kind === BOOLEAN_TYPE ? 'boolean' : // 类型为 boolean + // 类型为 number + let paramText = paramType.kind === NUMBER_TYPE ? 'number' : + // 类型为 string + paramType.kind === STRING_TYPE ? 'string' : + // 类型为 boolean + paramType.kind === BOOLEAN_TYPE ? 'boolean' : paramType.kind === VOID_TYPE ? 'void' : - 'any'; // 默认any类型 + // 默认any类型 + 'any'; if (paramType.kind === OBJECT_TYPE) { const type = paramType.typeName.escapedText; if (paramType.typeArguments) { @@ -205,7 +209,8 @@ export function parseTsFile(filePath: string): ParseObj { parameters: paramResList, type: '', }); - } else if (ts.isPropertyDeclaration(member) || ts.isPropertyAssignment(member)) { // 判断是否是类的成员变量 + } else if (ts.isPropertyDeclaration(member) || ts.isPropertyAssignment(member)) { + // 判断是否是类的成员变量 if ('type' in member && 'text' in member.name) { let paramTypeText = getParamType(member.type); let parameter: ParamObj = { @@ -258,9 +263,11 @@ export function parseTsFile(filePath: string): ParseObj { parameters.forEach(param => { let paramName = ''; if ('text' in param.name) { - paramName = param.name.text; // 参数名称,如 "v1" + // 参数名称,如 "v1" + paramName = param.name.text; } - const paramType = param.type; // 参数类型节点 + // 参数类型节点 + const paramType = param.type; let paramText = getParamType(paramType); console.log(` ${paramName}: ${paramText}`); diff --git a/src/vscode_plugin/src/template/functypemap_template.ts b/src/vscode_plugin/src/template/functypemap_template.ts index 38be3c96..d10aef9b 100644 --- a/src/vscode_plugin/src/template/functypemap_template.ts +++ b/src/vscode_plugin/src/template/functypemap_template.ts @@ -18,7 +18,8 @@ import { FuncTransferMap } from "../datatype"; export let transferMap: FuncTransferMap[] = [ { fromType: 'bool', - tranferContent: ['WriteBoolUnaligned', 'ReadBoolUnaligned'] // 分离出array , vector, map等 + // 分离出array , vector, map等 + tranferContent: ['WriteBoolUnaligned', 'ReadBoolUnaligned'] }, { fromType: 'int8_t', -- Gitee