diff --git a/examples/napitutorials/entry/src/main/cpp/ncpp/ffmpegcase/render/plugin_render.cpp b/examples/napitutorials/entry/src/main/cpp/ncpp/ffmpegcase/render/plugin_render.cpp index a0ec39aa118bc4f6fbe417be4757f0721f5810a2..a9472c9283ce9a0904716da6f55918efc10ac238 100644 --- a/examples/napitutorials/entry/src/main/cpp/ncpp/ffmpegcase/render/plugin_render.cpp +++ b/examples/napitutorials/entry/src/main/cpp/ncpp/ffmpegcase/render/plugin_render.cpp @@ -24,13 +24,11 @@ #include "../manager/plugin_manager.h" #include "libavutil/pixdesc.h" #include "plugin_render.h" +#include "libavformat/avformat.h" +#include "libavcodec/avcodec.h" +#include "libavutil/timestamp.h" extern "C" { - #include "libavformat/avformat.h" - #include "libavcodec/avcodec.h" - #include "libavutil/timestamp.h" - #include "libavutil/pixdesc.h" - // 自定义 avio_read_packet 函数 int custom_avio_read_packet(void *opaque, uint8_t *buf, int bufSize) { diff --git a/src/cli/cmake2gn/src/main.js b/src/cli/cmake2gn/src/main.js index 9badda6f6bae62f9cfd59c184b0a18698da48164..943ace77b513737fcbd6443f6ff220f8a30a7068 100644 --- a/src/cli/cmake2gn/src/main.js +++ b/src/cli/cmake2gn/src/main.js @@ -12,15 +12,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const path = require("path"); -const stdio = require("stdio"); -const { AnalyzeCMake } = require("./src/analyze_cmake"); -const { AnalyzeMake } = require("./src/analyze_make"); -const { GenerateGn } = require("./src/generate_gn"); -const { Logger } = require("./src/logger"); -const { Tool } = require("./src/tool"); +const path = require('path'); +const stdio = require('stdio'); +const { AnalyzeCMake } = require('./src/analyze_cmake'); +const { AnalyzeMake } = require('./src/analyze_make'); +const { GenerateGn } = require('./src/generate_gn'); +const { Logger } = require('./src/logger'); +const { Tool } = require('./src/tool'); -if (process.execPath.endsWith("node") || process.execPath.endsWith("node.exe")) { +if (process.execPath.endsWith('node') || process.execPath.endsWith('node.exe')) { Tool.CURRENT_TOOL_PATH = __dirname;//工具目录,用来找到res内资源 } else { @@ -32,21 +32,21 @@ if (Tool.MOCK_TYPE === Tool.MOCK_ENUM.MOCK_RUN) { } let ops = stdio.getopt({ - 'type': { key: 't', args: 1, description: "", default: "cmake" }, + 'type': { key: 't', args: 1, description: '', default: 'cmake' }, 'filename': { key: 'f', args: 1, description: "The make file's relative path \ ( third_party/opencv/CMakeLists.txt , make file can be Makefile/CMakeLists.txt)" }, 'ohos_product_output': { - key: 'o', args: 1, description: "ohos product output relative path", - default: "out/rk3568" + key: 'o', args: 1, description: 'ohos product output relative path', + default: 'out/rk3568' }, - 'ohos_project_path': { key: 'p', args: 1, description: "ohos project path ( /home/xxx/ohos_project )" }, - 'cmake_args': { key: 'a', args: 1, description: "like: (-DABC,-DQWE)", default: "" }, - 'subsystem_name': { key: 's', args: 1, description: "subsystem", default: "test_subsystem" }, - 'part_name': { key: 'm', args: 1, description: "part", default: "test_part" }, - 'porting_to': { key: 'd', args: 1, description: "porting to", default: "" }, + 'ohos_project_path': { key: 'p', args: 1, description: 'ohos project path ( /home/xxx/ohos_project )' }, + 'cmake_args': { key: 'a', args: 1, description: 'like: (-DABC,-DQWE)', default: '' }, + 'subsystem_name': { key: 's', args: 1, description: 'subsystem', default: 'test_subsystem' }, + 'part_name': { key: 'm', args: 1, description: 'part', default: 'test_part' }, + 'porting_to': { key: 'd', args: 1, description: 'porting to', default: '' }, }); Tool.OHOS_PROJECT_PATH = ops.ohos_project_path; @@ -62,12 +62,12 @@ Tool.OHOS_PART_NAME = ops.part_name; let compileFile = path.parse(path.join(Tool.OHOS_PROJECT_PATH, ops.filename)); -if (ops.type === "cmake") {//cmake +if (ops.type == 'cmake') {//cmake AnalyzeCMake.analyze(compileFile, ops.cmake_args.substring(1, ops.cmake_args.length - 1)); } -else if (ops.type === "make") {//make +else if (ops.type == 'make') {//make AnalyzeMake.analyze(compileFile); } else { - Logger.err("not support " + ops.filename); + Logger.err('not support ' + ops.filename); } diff --git a/src/cli/cmake2gn/src/src/analyze_cmake.js b/src/cli/cmake2gn/src/src/analyze_cmake.js old mode 100644 new mode 100755 index bcc4ddc4f01d2f13a074d57684d61848ee8b985f..933b98c57d96ac0206a3abf0d91fbe33728eccdf --- a/src/cli/cmake2gn/src/src/analyze_cmake.js +++ b/src/cli/cmake2gn/src/src/analyze_cmake.js @@ -12,12 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const path = require("path"); -const { Logger } = require("./logger"); -const { Tool } = require("./tool"); -const childProcess = require("child_process"); -const fs = require("fs"); -const { AnalyzeMake } = require("./analyze_make"); +const path = require('path'); +const { Logger } = require('./logger'); +const { Tool } = require('./tool'); +const childProcess = require('child_process'); +const fs = require('fs'); +const { AnalyzeMake } = require('./analyze_make'); class AnalyzeCMake { constructor() { @@ -25,11 +25,11 @@ class AnalyzeCMake { } static mkdirBuildTemp(compileFile){ let buildTmp; - if(Tool.OHOS_PORTING_TO==""){ - buildTmp = path.join(compileFile.dir, "build_tmp");//cmake编译的临时目录 + if(Tool.OHOS_PORTING_TO==''){ + buildTmp = path.join(compileFile.dir, 'build_tmp');//cmake编译的临时目录 } else{ - buildTmp = path.join(Tool.OHOS_PROJECT_PATH,Tool.OHOS_PORTING_TO, "build_tmp");//cmake编译的临时目录 + buildTmp = path.join(Tool.OHOS_PROJECT_PATH,Tool.OHOS_PORTING_TO, 'build_tmp');//cmake编译的临时目录 } if (fs.existsSync(buildTmp)) { fs.rmSync(buildTmp, { recursive: true, force: true });//🌻 @@ -38,32 +38,32 @@ class AnalyzeCMake { } static analyze(compileFile, cmakeArgs) {//在工程目录创建一个buildTmp目录,执行cmake初始化工程,执行make得到命令行序列 - if (!fs.existsSync(path.join(Tool.OHOS_PROJECT_PATH, Tool.OHOS_PRODUCT_OUTPUT_PATH, "build.ninja"))) { - Logger.err("param ohos need to looks like out/rk3568"); + if (!fs.existsSync(path.join(Tool.OHOS_PROJECT_PATH, Tool.OHOS_PRODUCT_OUTPUT_PATH, 'build.ninja'))) { + Logger.err('param ohos need to looks like out/rk3568'); return; } let buildTmp = AnalyzeCMake.mkdirBuildTemp(compileFile); fs.mkdirSync(buildTmp); Tool.pushd(buildTmp); let ohosToolchainCmake = Tool.getCMakeToolchain(); - let ohosToolchainCmakeData = fs.readFileSync(ohosToolchainCmake, { encoding: "utf8" }); - while (ohosToolchainCmakeData.indexOf("CC_REPLACE_OHOS_ROOT") >= 0) { - ohosToolchainCmakeData = ohosToolchainCmakeData.replace("CC_REPLACE_OHOS_ROOT", + let ohosToolchainCmakeData = fs.readFileSync(ohosToolchainCmake, { encoding: 'utf8' }); + while (ohosToolchainCmakeData.indexOf('CC_REPLACE_OHOS_ROOT') >= 0) { + ohosToolchainCmakeData = ohosToolchainCmakeData.replace('CC_REPLACE_OHOS_ROOT', Tool.swapPath(Tool.OHOS_PROJECT_PATH, true)); } - while (ohosToolchainCmakeData.indexOf("CC_REPLACE_OHOS_TARGET") >= 0) { - ohosToolchainCmakeData = ohosToolchainCmakeData.replace("CC_REPLACE_OHOS_TARGET", + while (ohosToolchainCmakeData.indexOf('CC_REPLACE_OHOS_TARGET') >= 0) { + ohosToolchainCmakeData = ohosToolchainCmakeData.replace('CC_REPLACE_OHOS_TARGET', Tool.OHOS_PRODUCT_OUTPUT_PATH); } - ohosToolchainCmake = path.join(buildTmp, "ohos.toolchain.cmake"); + ohosToolchainCmake = path.join(buildTmp, 'ohos.toolchain.cmake'); fs.writeFileSync(ohosToolchainCmake, ohosToolchainCmakeData); ohosToolchainCmake=Tool.swapPath(ohosToolchainCmake); let args = [compileFile.dir, - "-DCMAKE_TOOLCHAIN_FILE=%s".format(ohosToolchainCmake),"-G","Unix Makefiles", - "-DCMAKE_MAKE_PROGRAM=%s".format(Tool.swapPath(Tool.getMakeRaw())), + '-DCMAKE_TOOLCHAIN_FILE=%s'.format(ohosToolchainCmake),'-G','Unix Makefiles', + '-DCMAKE_MAKE_PROGRAM=%s'.format(Tool.swapPath(Tool.getMakeRaw())), ]; if (cmakeArgs.length > 0) { - args.push(...cmakeArgs.split(",")); + args.push(...cmakeArgs.split(',')); } let ret = childProcess.spawn(Tool.swapPath(Tool.getCMake()), args); ret.stdout.on('data', (data) => { @@ -74,10 +74,10 @@ class AnalyzeCMake { }); ret.on('close', (code) => { if (code == 0) { - Logger.info("------------------------cmake ok"); - AnalyzeMake.analyze(path.join(buildTmp, "Makefile")); //调用make生成命令行 + Logger.info('------------------------cmake ok'); + AnalyzeMake.analyze(path.join(buildTmp, 'Makefile')); //调用make生成命令行 } - else Logger.err("cmake fail"); + else Logger.err('cmake fail'); }); } } diff --git a/src/cli/cmake2gn/src/src/analyze_command.js b/src/cli/cmake2gn/src/src/analyze_command.js index 703bafb3a8ae747c126a6d4a70e8968e5d2c7c35..f65ed65cca21486f4caffaab197db6ae72621f71 100644 --- a/src/cli/cmake2gn/src/src/analyze_command.js +++ b/src/cli/cmake2gn/src/src/analyze_command.js @@ -184,7 +184,7 @@ class AnalyzeCommand { let startp = -1; let isContinuChar = 0; for (let p = 0; p < s.length; p++) { - if (s[p] === '\'' && s[p-1] !== '\\') { + if (s[p] == '\"' && s[p-1] != '\\') { isContinuChar = 1 - isContinuChar; } if (startp >= 0) { @@ -531,7 +531,7 @@ class AnalyzeCommand { let datas = data.split(' '); let pp = ['.c', '.o', - '.o', + '.o"', '.a', '.S', '.so' @@ -548,8 +548,8 @@ class AnalyzeCommand { return false; } static analyzeCcClangxx(cmd) { - if (cmd.indexOf('\'')) { - cmd = cmd.replace(/\'/g, ''); + if (cmd.indexOf('\"')) { + cmd = cmd.replace(/\"/g, ''); } let local = { ret: AnalyzeCommand.resultTemplete(), diff --git a/src/cli/cmake2gn/src/src/logger.js b/src/cli/cmake2gn/src/src/logger.js index e432df78881397d6674daf6340f6a303584870c6..f0e5719c674a0524421440289810c6258775ae6a 100644 --- a/src/cli/cmake2gn/src/src/logger.js +++ b/src/cli/cmake2gn/src/src/logger.js @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { Tool } = require("./tool"); +const { Tool } = require('./tool'); class Logger { constructor() { @@ -23,7 +23,7 @@ class Logger { Tool.VSCODE_INST.window.showErrorMessage(msg); } - console.log("ERR :", msg); + console.log('ERR :', msg); if (dontexit) { return false; } @@ -36,7 +36,7 @@ class Logger { Tool.VSCODE_INST.window.showInformationMessage(msg); } - console.log("INFO (%d) %s".format(Logger.INFO_NUM++, msg)); + console.log('INFO (%d) %s'.format(Logger.INFO_NUM++, msg)); } } diff --git a/src/cli/cmake2gn/src/src/tool.js b/src/cli/cmake2gn/src/src/tool.js index 94f23c6f3e8db34b1f654d4d798b5bbc1dc1a085..935ec030dce3c55aee81e8ab2c3f33bfbdf7a0a4 100644 --- a/src/cli/cmake2gn/src/src/tool.js +++ b/src/cli/cmake2gn/src/src/tool.js @@ -13,18 +13,18 @@ * limitations under the License. */ const path = require('path'); -const fs = require("fs"); +const fs = require('fs'); class Tool { constructor() { } static CURRENT_TOOL_PATH = null;//生成工具或插件所在路径,用于找到res - static OHOS_PROJECT_PATH = "/home/xx/ohos"; - static OHOS_PORTING_TO = "third_party/opencv"; - static OHOS_PRODUCT_OUTPUT_PATH = "out/rk3568-khdvk";//输出目录 - static OHOS_SUBSYSTEM_NAME = "common"; - static OHOS_PART_NAME = "common"; + static OHOS_PROJECT_PATH = '/home/xx/ohos'; + static OHOS_PORTING_TO = 'third_party/opencv'; + static OHOS_PRODUCT_OUTPUT_PATH = 'out/rk3568-khdvk';//输出目录 + static OHOS_SUBSYSTEM_NAME = 'common'; + static OHOS_PART_NAME = 'common'; static globalJsonCfg = null; // cfg.json 配置文件 static allowedCxx = null; // cxx编译中允许处理的文件后缀列表 static allowedC = null; // c编译中允许处理的文件后缀列表 @@ -36,58 +36,58 @@ class Tool { static getCMakeToolchain() { switch (process.platform) { case 'win32': - return path.join(Tool.CURRENT_TOOL_PATH, "res/win/ohos.toolchain.cmake"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/win/ohos.toolchain.cmake'); case 'linux': - return path.join(Tool.CURRENT_TOOL_PATH, "res/linux/ohos.toolchain.cmake"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/linux/ohos.toolchain.cmake'); case 'darwin': - return path.join(Tool.CURRENT_TOOL_PATH, "res/mac/ohos.toolchain.cmake"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/mac/ohos.toolchain.cmake'); default: - Logger.err("不支持 %s 平台".format(process.platform)); - return ""; + Logger.err('不支持 %s 平台'.format(process.platform)); + return ''; } } static getMakeRaw() { switch (process.platform) { case 'win32': - return path.join(Tool.CURRENT_TOOL_PATH, "res/win/bin/make_raw.exe"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/win/bin/make_raw.exe'); case 'linux': - return path.join(Tool.CURRENT_TOOL_PATH, "res/linux/bin/make_raw"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/linux/bin/make_raw'); case 'darwin': - return path.join(Tool.CURRENT_TOOL_PATH, "res/mac/bin/make_raw"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/mac/bin/make_raw'); default: - Logger.err("不支持 %s 平台".format(process.platform)); - return ""; + Logger.err('不支持 %s 平台'.format(process.platform)); + return ''; } } static getMake() { switch (process.platform) { case 'win32': - return path.join(Tool.CURRENT_TOOL_PATH, "res/win/bin/make.exe"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/win/bin/make.exe'); case 'linux': - return path.join(Tool.CURRENT_TOOL_PATH, "res/linux/bin/make"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/linux/bin/make'); case 'darwin': - return path.join(Tool.CURRENT_TOOL_PATH, "res/mac/bin/make"); + return path.join(Tool.CURRENT_TOOL_PATH, 'res/mac/bin/make'); default: - Logger.err("不支持 %s 平台".format(process.platform)); - return ""; + Logger.err('不支持 %s 平台'.format(process.platform)); + return ''; } } static getCMake() { switch (process.platform) { case 'win32': - return path.join(Tool.OHOS_PROJECT_PATH, "prebuilts/cmake/windows-x86/bin/cmake.exe"); + return path.join(Tool.OHOS_PROJECT_PATH, 'prebuilts/cmake/windows-x86/bin/cmake.exe'); case 'linux': case 'darwin': - return path.join(Tool.OHOS_PROJECT_PATH, "prebuilts/cmake/linux-x86/bin/cmake"); + return path.join(Tool.OHOS_PROJECT_PATH, 'prebuilts/cmake/linux-x86/bin/cmake'); default: - Logger.err("不支持 %s 平台".format(process.platform)); - return ""; + Logger.err('不支持 %s 平台'.format(process.platform)); + return ''; } } static swapPath(p, swapd) { - while (p.indexOf("\\") >= 0) { - p = p.replace("\\", "/"); + while (p.indexOf('\\') >= 0) { + p = p.replace('\\', '/'); } return p; } @@ -138,7 +138,7 @@ class Tool { GenerateGn.generate(projectPath, analyzeResult); break; default: - Logger.err("generate target not support"); + Logger.err('generate target not support'); break; } } @@ -159,8 +159,8 @@ class Tool { let jsonFilePath = path.join(Tool.CURRENT_TOOL_PATH, "res/cfg.json"); let jsonFile = fs.readFileSync(jsonFilePath, { encoding: "utf8" }); this.globalJsonCfg = JSON.parse(jsonFile); - this.globalJsonCfg.fileSuffix = this.globalJsonCfg.fileSuffix ? "," + this.globalJsonCfg.fileSuffix : ""; - this.globalJsonCfg.compileflag = this.globalJsonCfg.compileflag ? "," + this.globalJsonCfg.compileflag : ""; + this.globalJsonCfg.fileSuffix = this.globalJsonCfg.fileSuffix ? ',' + this.globalJsonCfg.fileSuffix : ''; + this.globalJsonCfg.compileflag = this.globalJsonCfg.compileflag ? ',' + this.globalJsonCfg.compileflag : ''; } return this.globalJsonCfg; @@ -174,13 +174,13 @@ class Tool { if (this.allowedCxx === null || this.allowedCxx === undefined) { this.allowedCxx = {}; let jsonCfg = this.getJsonCfg(); - let allowedCxxSuffix = ".cpp, .cxx, .cc, .o, .z, .so, .a" + jsonCfg.fileSuffix; + let allowedCxxSuffix = '.cpp, .cxx, .cc, .o, .z, .so, .a' + jsonCfg.fileSuffix; this.allowedCxx.fileSuffix = - allowedCxxSuffix.split(",").map(item => item.trim()).filter(item => item !== ""); - let allowedFlag = "--target=, -march=, -mfloat-abi=, -mfpu=, -fsigned-char, -ffast-math, -rdynamic, " - + "-UNDEBUG, -fno-threadsafe-statics, -fno-common, -fno-strict-aliasing, -fcolor-diagnostics, " - + "-fstrict-aliasing, -fdiagnostics-show-option" + jsonCfg.compileflag; - this.allowedCxx.compileflag = allowedFlag.split(",").map(item => item.trim()).filter(item => item !== ""); + allowedCxxSuffix.split(',').map(item => item.trim()).filter(item => item != ''); + let allowedFlag = '--target=, -march=, -mfloat-abi=, -mfpu=, -fsigned-char, -ffast-math, -rdynamic, ' + + '-UNDEBUG, -fno-threadsafe-statics, -fno-common, -fno-strict-aliasing, -fcolor-diagnostics, ' + + '-fstrict-aliasing, -fdiagnostics-show-option' + jsonCfg.compileflag; + this.allowedCxx.compileflag = allowedFlag.split(',').map(item => item.trim()).filter(item => item != ''); } return this.allowedCxx; } @@ -194,12 +194,12 @@ class Tool { this.allowedC = {}; let jsonCfg = this.getJsonCfg(); let allowedCSuffix = '.c, .o, .o", .a, .S, .so' + jsonCfg.fileSuffix; - this.allowedC.fileSuffix = allowedCSuffix.split(",").map(item => item.trim()).filter(item => item !== ""); - let allowedFlag = "--target=, -march=, -mfloat-abi=, -mfpu=, -fno-common, -fcolor-diagnostics, -ggdb, " - + "-fno-strict-aliasing, -ldl, -flto, -fno-builtin, -fno-stack-protector, -fvisibility=default, " - + "-fsigned-char, -fstack-protector-strong, -fdiagnostics-show-option" + this.allowedC.fileSuffix = allowedCSuffix.split(',').map(item => item.trim()).filter(item => item != ''); + let allowedFlag = '--target=, -march=, -mfloat-abi=, -mfpu=, -fno-common, -fcolor-diagnostics, -ggdb, ' + + '-fno-strict-aliasing, -ldl, -flto, -fno-builtin, -fno-stack-protector, -fvisibility=default, ' + + '-fsigned-char, -fstack-protector-strong, -fdiagnostics-show-option' + jsonCfg.compileflag; - this.allowedC.compileflag = allowedFlag.split(",").map(item => item.trim()).filter(item => item !== ""); + this.allowedC.compileflag = allowedFlag.split(',').map(item => item.trim()).filter(item => item != ''); } return this.allowedC; } @@ -207,7 +207,7 @@ class Tool { String.prototype.format = function (...args) { var result = this; - let reg = new RegExp("%[sd]{1}"); + let reg = new RegExp('%[sd]{1}'); for (let i = 0; i < args.length; i++) { let p = result.search(reg); if (p < 0) break; diff --git a/src/cli/dts2cpp/src/gen/analyze/enum.js b/src/cli/dts2cpp/src/gen/analyze/enum.js index 92f2bfd8bb9138b5d0ddc5b915620628ea5493d1..61a5a408771033c3eb05e91266a1030ceed53aab 100644 --- a/src/cli/dts2cpp/src/gen/analyze/enum.js +++ b/src/cli/dts2cpp/src/gen/analyze/enum.js @@ -12,17 +12,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { NumberIncrease } = require("../tools/common"); -const re = require("../tools/re"); +const { NumberIncrease } = require('../tools/common'); +const re = require('../tools/re'); /** Enum解析 */ function analyzeEnum(data) { - let body = re.replaceAll(data, "\n", "").split(",") + let body = re.replaceAll(data, '\n', '').split(','); let result = { element: [], function: [], enumValueType: 0 // 0代表数字,1代表字符串 - } + }; for (let i in body) { let bodyContent = body[i] while (bodyContent.length > 0 && bodyContent[0] === ' ') { @@ -34,58 +34,58 @@ function analyzeEnum(data) { if (bodyContent === "") { break } - analyzeEnumResult(result, bodyContent, i) + analyzeEnumResult(result, bodyContent, i); } - return result + return result; } function analyzeEnumResult(result, bodyContent, index) { - let regString = re.match(" *([a-zA-Z0-9_]+) * = *\"([\x21-\x7e]+)*\"", bodyContent) - let regSingleQuotes = re.match(" *([a-zA-Z0-9_]+) * = *'([\x21-\x7e]+)*'", bodyContent) - let regNumber = re.match(" *([a-zA-Z0-9_]+) * = *([a-zA-Z_0-9<>-]+)", bodyContent) - let reg = re.match(" *([a-zA-Z0-9_]+) *", bodyContent) + let regString = re.match(' *([a-zA-Z0-9_]+) * = *\"([\x21-\x7e]+)*\"', bodyContent); + let regSingleQuotes = re.match(" *([a-zA-Z0-9_]+) * = *'([\x21-\x7e]+)*'", bodyContent); + let regNumber = re.match(" *([a-zA-Z0-9_]+) * = *([a-zA-Z_0-9<>-]+)", bodyContent); + let reg = re.match(' *([a-zA-Z0-9_]+) *', bodyContent); if (regString) { - let elementName = re.getReg(bodyContent, regString.regs[1]) - let elementValue = re.getReg(bodyContent, regString.regs[2]) + let elementName = re.getReg(bodyContent, regString.regs[1]); + let elementValue = re.getReg(bodyContent, regString.regs[2]); result.element.push({ name: elementName, value: elementValue, type: 'string' - }) - result.enumValueType = 1 + }); + result.enumValueType = 1; } else if (regSingleQuotes) { - let elementName = re.getReg(bodyContent, regSingleQuotes.regs[1]) - let elementValue = re.getReg(bodyContent, regSingleQuotes.regs[2]) + let elementName = re.getReg(bodyContent, regSingleQuotes.regs[1]); + let elementValue = re.getReg(bodyContent, regSingleQuotes.regs[2]); result.element.push({ name: elementName, value: elementValue, type: 'string' - }) - result.enumValueType = 1 + }); + result.enumValueType = 1; } else if (regNumber) { - let elementName = re.getReg(bodyContent, regNumber.regs[1]) - let elementValue = re.getReg(bodyContent, regNumber.regs[2]) - typeof (elementValue) + let elementName = re.getReg(bodyContent, regNumber.regs[1]); + let elementValue = re.getReg(bodyContent, regNumber.regs[2]); + typeof (elementValue); result.element.push({ name: elementName, value: elementValue, - type: "NUMBER_TYPE_" + NumberIncrease.getAndIncrease() - }) - result.enumValueType = 0 + type: 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease() + }); + result.enumValueType = 0; } else if (reg) { - let elementName = re.getReg(bodyContent, reg.regs[1]) - let elementValue = index + let elementName = re.getReg(bodyContent, reg.regs[1]); + let elementValue = index; result.element.push({ name: elementName, value: elementValue, - type: "NUMBER_TYPE_" + NumberIncrease.getAndIncrease() - }) - result.enumValueType = 0 + type: 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease() + }); + result.enumValueType = 0; } - return result + return result; } module.exports = { analyzeEnum, analyzeEnumResult -} \ No newline at end of file +}; \ No newline at end of file diff --git a/src/cli/dts2cpp/src/gen/analyze/function.js b/src/cli/dts2cpp/src/gen/analyze/function.js index 82fc133f1e9904fc1b975b00be12f285896dce0f..34a18e76baa639449fd6007ecde04dc32a77fe4e 100644 --- a/src/cli/dts2cpp/src/gen/analyze/function.js +++ b/src/cli/dts2cpp/src/gen/analyze/function.js @@ -29,11 +29,11 @@ function analyzeSubInterface(data) { parentNameList: [], childList: [], parentList: [] - } + }; for (let i in body) { - let t = body[i] + let t = body[i]; while (t.length > 0 && t[0] === ' ') // 去除前面的空格 - t = t.substring(1, t.length) + t = t.substring(1, t.length); while (t.length > 0 && t[-1] === ' ') // 去除后面的空格 t = t.substring(0, t.length - 1) if (t === '') break // 如果t为空直接返回 @@ -42,7 +42,7 @@ function analyzeSubInterface(data) { analyzeSubInterfaceVal(t, tt, result); } } - return result + return result; } function analyzeSubInterfaceVal(t, tt, result) { @@ -66,7 +66,7 @@ function getFuncParaType(v, interfaceName, data, results) { parameter = re.getReg(v.type, arrayType.regs[2]) } if (isEnum(parameter, data)) { - let index = enumIndex(parameter, data) + let index = enumIndex(parameter, data); if (data.enum[index].body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_NUMBER) { v.type = v.type.replace(parameter, 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()) } else if (data.enum[index].body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_STRING) { @@ -74,12 +74,12 @@ function getFuncParaType(v, interfaceName, data, results) { } else { NapiLog.logError('analyzeFunction getFuncParaType is not support this type %s.' .format(data.enum[index].body.enumValueType), getLogErrInfo); - return null + return null; } } // interface & class中的方法参数类型是enum的情况 else if (isEnum(parameter, results)) { - let index = enumIndex(parameter, results) + let index = enumIndex(parameter, results); if (results.enum[index].body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_NUMBER) { v.type = v.type.replace(parameter, 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()) v.realType = v.type @@ -88,111 +88,111 @@ function getFuncParaType(v, interfaceName, data, results) { } else { NapiLog.logError('analyzeFunction getFuncParaType is not support this type %s.' .format(results.enum[index].body.enumValueType), getLogErrInfo()); - return null + return null; } } - let interfaceType = re.match('{([A-Za-z0-9_]+:[A-Za-z0-9_,]+)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}$', v['type']) + let interfaceType = re.match('{([A-Za-z0-9_]+:[A-Za-z0-9_,]+)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}$', v['type']); if (interfaceType) { - v.type = interfaceName + v.type = interfaceName; } if (parameter.indexOf('number') >= 0) { - v.type = v.type.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()) - v.realType = v.type + v.type = v.type.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); + v.realType = v.type; } // type的处理 if (isType(parameter, data)) { - let index = typeIndex(parameter, data) + let index = typeIndex(parameter, data); if (data.type[index].isEnum) { - v.type = v.type.replace(parameter, 'string') + v.type = v.type.replace(parameter, 'string'); } } - return v + return v; } function analyzeFuncNoNameInterface(data, values, results) { - values = re.replaceAll(re.replaceAll(values, ' ', ''), '\n', '') - let interfaceName = '' + values = re.replaceAll(re.replaceAll(values, ' ', ''), '\n', ''); + let interfaceName = ''; let matchNoName = '([:{<}>,;a-zA-Z_0-9]*)\\?*(:[A-Za-z0-9_,;]*)?:((Async)*Callback<)?{(([A-Za-z0-9_]+:'+ - '[A-Za-z0-9_,;]+)*)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}(}|,|;|>)?$' - let matchs = re.match(matchNoName, values) + '[A-Za-z0-9_,;]+)*)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}(}|,|;|>)?$'; + let matchs = re.match(matchNoName, values); if (matchs) { - let st = values.lastIndexOf('{') - let end = values.indexOf('}') + let st = values.lastIndexOf('{'); + let end = values.indexOf('}'); let number = NumberIncrease.getAndIncrease(); - interfaceName = 'AUTO_INTERFACE_%s'.format(number) - let interfaceBody = values.substring(st+1, end) - let typeInterface = '{%s}'.format(interfaceBody) - values = re.replaceAll(values, typeInterface, interfaceName) - interfaceBody = re.replaceAll(interfaceBody, ',', ';') + interfaceName = 'AUTO_INTERFACE_%s'.format(number); + let interfaceBody = values.substring(st+1, end); + let typeInterface = '{%s}'.format(interfaceBody); + values = re.replaceAll(values, typeInterface, interfaceName); + interfaceBody = re.replaceAll(interfaceBody, ',', ';'); if (Object.prototype.hasOwnProperty.call(data, 'interface')) { data.interface.push({ name: interfaceName, body: analyzeSubInterface(interfaceBody) - }) + }); } else if (Object.prototype.hasOwnProperty.call(results, 'interface')) { results.interface.push({ name: interfaceName, body: analyzeSubInterface(interfaceBody) - }) + }); } } - matchs = re.match(matchNoName, values) + matchs = re.match(matchNoName, values); if(matchs) { - let resNoNameInter = analyzeFuncNoNameInterface(data, values) - values = resNoNameInter.values + let resNoNameInter = analyzeFuncNoNameInterface(data, values); + values = resNoNameInter.values; } let result = { interfaceName: interfaceName, values: values - } - return result + }; + return result; } function analyseSubReturn(ret, data, results) { // 匿名interface返回值 function fun4(input: string): { read: number; written: number }; - let tt = null + let tt = null; if (ret.indexOf(':') > 0) { - ret = re.replaceAll(re.replaceAll(ret, ' ', ''), '\n', '') - ret = re.replaceAll(ret, ',', ';') - ret = ret.substring(1, ret.length - 1) - tt = ret.split(';') + ret = re.replaceAll(re.replaceAll(ret, ' ', ''), '\n', ''); + ret = re.replaceAll(ret, ',', ';'); + ret = ret.substring(1, ret.length - 1); + tt = ret.split(';'); } if (tt) { - let len = tt.length - let res = '' - let interfaceName = '' + let len = tt.length; + let res = ''; + let interfaceName = ''; for (let i=0; i= 0) { - ret = ret.replaceAll('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()) + ret = ret.replaceAll('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); } - return ret + return ret; } function getObjCallFunc(results, onObjCbType, values, ret) { @@ -201,7 +201,7 @@ function getObjCallFunc(results, onObjCbType, values, ret) { 'name': onObjCbType, 'body': values, 'ret': ret - }) + }); } } function getFuncResult(name, funcType, values, ret, isStatic) { @@ -211,66 +211,66 @@ function getFuncResult(name, funcType, values, ret, isStatic) { value: values, ret: ret, isStatic: isStatic - } - return result + }; + return result; } function getArrowCallFunc(tmp, results) { - let callbackFunc = null + let callbackFunc = null; if (tmp[2][0] !== undefined) { - callbackFunc = tmp[2][0] // 当方法的参数是回调方法,并且回调方法写法为=>函数 + callbackFunc = tmp[2][0]; // 当方法的参数是回调方法,并且回调方法写法为=>函数 } if (results !== undefined && callbackFunc !== null) { - results.callFunction.push(callbackFunc) + results.callFunction.push(callbackFunc); } } /**函数解析 */ function analyzeFunction(data, isStatic, name, values, ret, results, interfaceName = '') { - let res = analyzeFuncNoNameInterface(data, values, results) - let tmp - let funcType + let res = analyzeFuncNoNameInterface(data, values, results); + let tmp; + let funcType; if (res) { - tmp = analyzeParams(name, res.values) + tmp = analyzeParams(name, res.values); if (tmp !== null) { - values = tmp[0] - funcType = tmp[1] - getArrowCallFunc(tmp, results) + values = tmp[0]; + funcType = tmp[1]; + getArrowCallFunc(tmp, results); } } - tmp = analyzeReturn(ret) - ret = tmp[0] + tmp = analyzeReturn(ret); + ret = tmp[0]; if (tmp[1]) { // 返回类型为 Promise, 解析成等价的AsyncCallback方法 - funcType = FuncType.ASYNC + funcType = FuncType.ASYNC; // 返回值是Promise的匿名interface let paramTypeVal = analyseSubReturn(ret.substring(8, ret.length - 1), data, results); // 将返回值Promise改为AsyncCallback,作为方法的入参 - let paramType = ret.replace('Promise', 'AsyncCallback') + let paramType = ret.replace('Promise', 'AsyncCallback'); if (paramTypeVal) { // 匿名interface处理 - let paramAsync = paramType.substring(14, paramType.length - 1) + let paramAsync = paramType.substring(14, paramType.length - 1); paramType = paramType.replace(paramAsync, paramTypeVal); } - values.push({name: 'promise', optional: false, type: paramType, realType: paramType}) - ret = 'void' // 返回值由Promise改为void,与AsyncCallback接口保持一致 + values.push({name: 'promise', optional: false, type: paramType, realType: paramType}); + ret = 'void'; // 返回值由Promise改为void,与AsyncCallback接口保持一致 } for (let j in values) { - let v = values[j] - v = getFuncParaType(v, res.interfaceName, data, results) + let v = values[j]; + v = getFuncParaType(v, res.interfaceName, data, results); if (v === null) { NapiLog.logError('analyzeFunction is not support this type %s.'.format(v), getLogErrInfo()); } } - ret = analyseSubReturn(ret, data, results) - let result = getFuncResult(name, funcType, values, ret, isStatic) + ret = analyseSubReturn(ret, data, results); + let result = getFuncResult(name, funcType, values, ret, isStatic); if (isOnObjCallback(name)) { - let onObjCbType = getOnObjCallbackType(name, interfaceName) - getObjCallFunc(results, onObjCbType, values, ret) + let onObjCbType = getOnObjCallbackType(name, interfaceName); + getObjCallFunc(results, onObjCbType, values, ret); } - return result + return result; } module.exports = { @@ -279,4 +279,4 @@ module.exports = { getFuncParaType, analyzeFuncNoNameInterface, analyseSubReturn -} \ No newline at end of file +}; \ No newline at end of file diff --git a/src/cli/dts2cpp/src/gen/analyze/interface.js b/src/cli/dts2cpp/src/gen/analyze/interface.js index 158a811441b707a37c16160c844534ca696568a4..16a1b4f09ab4462160183b7c6879e14e92540c1a 100644 --- a/src/cli/dts2cpp/src/gen/analyze/interface.js +++ b/src/cli/dts2cpp/src/gen/analyze/interface.js @@ -19,58 +19,58 @@ const { analyzeFunction } = require('./function'); /* 匿名interface */ function analyzeNoNameInterface(valueType, valueName, rsltInterface) { - valueType = re.replaceAll(valueType, ' ', '') - let matchs = re.match('{(([A-Za-z0-9_]+:[A-Za-z0-9_,;]+)*)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}$', valueType) + valueType = re.replaceAll(valueType, ' ', ''); + let matchs = re.match('{(([A-Za-z0-9_]+:[A-Za-z0-9_,;]+)*)([A-Za-z0-9_]+:[A-Za-z0-9_]+)}$', valueType); if (matchs) { let number = NumberIncrease.getAndIncrease(); - let interfaceTypeName = 'AUTO_INTERFACE_%s_%s'.format(valueName, number) - let interfaceBody = valueType.substring(1, valueType.length-1) - interfaceBody = re.replaceAll(interfaceBody, ',', ';\n') + let interfaceTypeName = 'AUTO_INTERFACE_%s_%s'.format(valueName, number); + let interfaceBody = valueType.substring(1, valueType.length-1); + interfaceBody = re.replaceAll(interfaceBody, ',', ';\n'); rsltInterface.push({ name: interfaceTypeName, body: analyzeInterface(interfaceBody, rsltInterface) - }) - valueType = interfaceTypeName + }); + valueType = interfaceTypeName; } - return valueType + return valueType; } /* 去除单行注释// */ function parseNotes(data) { let notes = data.indexOf('//') >= 0 ? data.substring(data.indexOf('//'), data.length) : ''; - while(notes !== '') { + while(notes != '') { notes = notes.substring(0, notes.indexOf('\n')); data = data.replace(notes, ''); - notes = '' + notes = ''; let st = data.indexOf('//'); if(st >= 0) { notes = data.substring(st, data.length); } } - return data + return data; } /**interface解析 */ function analyzeInterface(data, rsltInterface = null, results, interfaceName = '') { // same as class - let body = data - body = body.indexOf('//') < 0 ? body : parseNotes(body) - let arr = [...body.matchAll(/;\s*\n+/g)] + let body = data; + body = body.indexOf('//') < 0 ? body : parseNotes(body); + let arr = [...body.matchAll(/;\s*\n+/g)]; for (let i = 0; i < arr.length; i++) { - let result = arr[i] - body = re.replaceAll(body, result[0], ';\n') + let result = arr[i]; + body = re.replaceAll(body, result[0], ';\n'); } - body = body.split(';\n') + body = body.split(';\n'); let result = { value: [], function: [] - } + }; for (let i in body) { - let t = body[i] - t = re.replaceAll(t, '\n', '') - while (t.length > 0 && t[0] === ' ') t = t.substring(1, t.length) // 去除前面的空格 - while (t.length > 0 && t[-1] === ' ') t = t.substring(0, t.length - 1) // 去除后面的空格 - if (t === '') break // 如果t为空直接返回 - let tt = re.match(' *([a-zA-Z0-9_]+)(\\?*)*: *([a-zA-Z_0-9<>,:{}[\\]| ]+)', t) + let t = body[i]; + t = re.replaceAll(t, '\n', ''); + while (t.length > 0 && t[0] === ' ') t = t.substring(1, t.length); // 去除前面的空格 + while (t.length > 0 && t[-1] === ' ') t = t.substring(0, t.length - 1); // 去除后面的空格 + if (t === '') break; // 如果t为空直接返回 + let tt = re.match(' *([a-zA-Z0-9_]+)(\\?*)*: *([a-zA-Z_0-9<>,:{}[\\]| ]+)', t); if (tt && t.indexOf('=>') < 0) { // 接口成员变量, 但不包括带'=>'的成员,带'=>'的接口成员需要按函数处理 analyzeInterfaceVariable(t, tt, rsltInterface, result); } @@ -80,7 +80,7 @@ function analyzeInterface(data, rsltInterface = null, results, interfaceName = ' analyzeInterfaceFunction(t, tt, data, results, interfaceName, result); } } - return result + return result; } module.exports = { diff --git a/src/cli/dts2cpp/src/gen/analyze/namespace.js b/src/cli/dts2cpp/src/gen/analyze/namespace.js index 221fff1ae5586dc72872323bcb6730132d42efa2..112be802e4374a913f6b6440dd89842193a25ca5 100644 --- a/src/cli/dts2cpp/src/gen/analyze/namespace.js +++ b/src/cli/dts2cpp/src/gen/analyze/namespace.js @@ -12,27 +12,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const re = require("../tools/re"); -const { removeEmptyLine, checkOutBody, addUniqFunc2List } = require("../tools/tool"); -const { analyzeFunction } = require("./function"); -const { analyzeInterface, parseNotes } = require("./interface"); -const { analyzeEnum } = require("./enum"); -const { NapiLog } = require("../tools/NapiLog"); -const { analyzeType, analyzeType2, analyzeType2Result } = require("./type"); -const { NumberIncrease, EnumValueType, getLogErrInfo } = require("../tools/common"); +const re = require('../tools/re'); +const { removeEmptyLine, checkOutBody, addUniqFunc2List } = require('../tools/tool'); +const { analyzeFunction } = require('./function'); +const { analyzeInterface, parseNotes } = require('./interface'); +const { analyzeEnum } = require('./enum'); +const { NapiLog } = require('../tools/NapiLog'); +const { analyzeType, analyzeType2, analyzeType2Result } = require('./type'); +const { NumberIncrease, EnumValueType, getLogErrInfo } = require('../tools/common'); function preProcessData(data) { - data = data.indexOf("//") < 0 ? data : parseNotes(data); - data = re.replaceAll(data, "\n{", "{"); + data = data.indexOf('//') < 0 ? data : parseNotes(data); + data = re.replaceAll(data, '\n{', '{'); return data; } function getDataByResult(result) { - let data = null + let data = null; if (result !== null) { - data = result + data = result; } - return data + return data; } /**namespace解析 */ @@ -47,42 +47,42 @@ function analyzeNamespace(data) { class: [], namespace: [], callFunction: [], - } + }; while (data !== '\n') { - let oldData = data - data = removeEmptyLine(data) - let matchs = re.match(" *\n*", data) + let oldData = data; + data = removeEmptyLine(data); + let matchs = re.match(' *\n*', data); data = preProcessData(data); // 只剩下空格和回车时,解析完成 - if (matchs && matchs.regs[0][1] === data.length) break - let parseEnumResult = parseEnum(matchs, data, result) - data = getDataByResult(parseEnumResult) + if (matchs && matchs.regs[0][1] === data.length) break; + let parseEnumResult = parseEnum(matchs, data, result); + data = getDataByResult(parseEnumResult); result = parseEnumType(result); - let parseInterResult = parseInterface(matchs, data, result) - data = getDataByResult(parseInterResult) + let parseInterResult = parseInterface(matchs, data, result); + data = getDataByResult(parseInterResult); - let parseFunctionResult = parseFunction(matchs, data, result) - data = getDataByResult(parseFunctionResult) + let parseFunctionResult = parseFunction(matchs, data, result); + data = getDataByResult(parseFunctionResult); - let parseTypeResult = parseType(matchs, data, result) - data = getDataByResult(parseTypeResult) + let parseTypeResult = parseType(matchs, data, result); + data = getDataByResult(parseTypeResult); - let parseClassResult = parseClass(matchs, data, result) - data = getDataByResult(parseClassResult) + let parseClassResult = parseClass(matchs, data, result); + data = getDataByResult(parseClassResult); - let parseNamespaceResult = parseNamespace(matchs, data, result) - data = getDataByResult(parseNamespaceResult) + let parseNamespaceResult = parseNamespace(matchs, data, result); + data = getDataByResult(parseNamespaceResult); - data = removeReg(matchs, data, result) + data = removeReg(matchs, data, result); if (oldData === data) { - NapiLog.logError("解析Namespace失败"); - NapiLog.logError("[", data.substring(0, data.length > 128 ? 128 : data.length), "]"); + NapiLog.logError('解析Namespace失败'); + NapiLog.logError('[', data.substring(0, data.length > 128 ? 128 : data.length), ']'); break; } } - return result + return result; } function parseEnumType(result) { @@ -91,13 +91,13 @@ function parseEnumType(result) { } for (let i in result.enum) { - let enumm = result.enum[i] + let enumm = result.enum[i]; // interface 匹配 for (let i in result.interface) { - let interf = result.interface[i] + let interf = result.interface[i]; if(!isValidValue(interf)) { - NapiLog.logError("parseEnumType interf is null!"); + NapiLog.logError('parseEnumType interf is null!'); return null; } @@ -105,7 +105,7 @@ function parseEnumType(result) { for (let j in interf.body.function) { let func = interf.body.function[j]; if(!isValidValue(func)) { - NapiLog.logError("parseEnumType func is null!"); + NapiLog.logError('parseEnumType func is null!'); return null; } @@ -113,17 +113,17 @@ function parseEnumType(result) { for (let k in func.value) { let v = func.value[k]; if(!isValidValue(v)) { - NapiLog.logError("parseEnumType func.value is null!"); + NapiLog.logError('parseEnumType func.value is null!'); return null; } if (v.type === enumm.name) { if (enumm.body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_NUMBER) { - v.type = "NUMBER_TYPE_" + NumberIncrease.getAndIncrease(); + v.type = 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease(); } else if (enumm.body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_STRING) { - v.type = "string"; + v.type = 'string'; } else { - NapiLog.logError("parseEnumType for interface function value is not support this type %s." + NapiLog.logError('parseEnumType for interface function value is not support this type %s.' .format(enumm.body.enumValueType), getLogErrInfo()); return null; } @@ -133,64 +133,64 @@ function parseEnumType(result) { } } } - return result + return result; } function parseNamespace(matchs, data, result) { - matchs = re.match("(export )*namespace ([a-zA-Z0-9]+) ({)", data) + matchs = re.match('(export )*namespace ([a-zA-Z0-9]+) ({)', data); if (matchs) { - let namespaceName = re.getReg(data, matchs.regs[2]) - let namespaceBody = checkOutBody(data, matchs.regs[3][0], null, true) + let namespaceName = re.getReg(data, matchs.regs[2]); + let namespaceBody = checkOutBody(data, matchs.regs[3][0], null, true); result.namespace.push({ name: namespaceName, body: analyzeNamespace(namespaceBody) - }) - data = data.substring(matchs.regs[3][0] + namespaceBody.length + 2, data.length) + }); + data = data.substring(matchs.regs[3][0] + namespaceBody.length + 2, data.length); if (matchs.regs[1][0] !== -1) { - result.exports.push(namespaceName) + result.exports.push(namespaceName); } } - return data + return data; } function parseClass(matchs, data, result) { matchs = re.match( - "(export )*class ([A-Za-z_0-9]+)()* *(extends [a-zA-Z_0-9, ]+)* *(implements [a-zA-Z_0-9, ]+)* *({)" - , data) + '(export )*class ([A-Za-z_0-9]+)()* *(extends [a-zA-Z_0-9, ]+)* *(implements [a-zA-Z_0-9, ]+)* *({)' + , data); if (matchs) { // class类型也解析成interface结构,该结构在后面生成C++代码时会按napi_define_class处理成C++的class - return createInterfaceData(matchs, data, result) + return createInterfaceData(matchs, data, result); } - return data + return data; } function parseEnum(matchs, data, result) { - matchs = re.match("(export )*enum *([A-Za-z_0-9]+) *({)", data) + matchs = re.match('(export )*enum *([A-Za-z_0-9]+) *({)', data); if (matchs !== null) { let enumName = re.getReg(data, matchs.regs[2]); - let enumBody = checkOutBody(data, matchs.regs[3][0], null, null) + let enumBody = checkOutBody(data, matchs.regs[3][0], null, null); result.enum.push({ name: enumName, body: analyzeEnum(enumBody.substring(1, enumBody.length - 1)) - }) - data = data.substring(matchs.regs[3][0] + enumBody.length) + }); + data = data.substring(matchs.regs[3][0] + enumBody.length); if (matchs.regs[1][0] !== -1) { - result.exports.push(enumName) + result.exports.push(enumName); } } - matchs = re.match("(export )*const ([A-Za-z_0-9]+) *[:=]{1} ([A-Za-z_0-9]+);", data) + matchs = re.match('(export )*const ([A-Za-z_0-9]+) *[:=]{1} ([A-Za-z_0-9]+);', data); if (matchs) { - let constName = re.getReg(data, matchs.regs[1]) + let constName = re.getReg(data, matchs.regs[1]); result.const.push({ name: constName, body: re.getReg(data, matchs.regs[2]) - }) - data = re.removeReg(data, matchs.regs[0]) + }); + data = re.removeReg(data, matchs.regs[0]); if (matchs.regs[1][0] !== -1) { - result.exports.push(constName) + result.exports.push(constName); } } - return data + return data; } function isValidValue(value) { @@ -202,104 +202,104 @@ function isValidValue(value) { function getTypeInfo(result, typeName, typeType, isEnum) { if (!isValidValue(result) || !isValidValue(result.type)) { - NapiLog.logError("getTypeInfo: result or result.type is invalid!"); + NapiLog.logError('getTypeInfo: result or result.type is invalid!'); } result.type.push({ name: typeName, body: typeType, isEnum: isEnum - }) + }); } function parseType(matchs, data, result) { - matchs = re.match("(export )*type ([a-zA-Z]+) *= *([\\(\\):=a-zA-Z<> |]+);", data) + matchs = re.match('(export )*type ([a-zA-Z]+) *= *([\\(\\):=a-zA-Z<> |]+);', data); if (matchs) { let typeName = re.getReg(data, matchs.regs[2]); let typeType = re.getReg(data, matchs.regs[3]); - let index = typeType.indexOf("number") + let index = typeType.indexOf('number'); if (index !== -1) { - typeType = typeType.replace("number", "NUMBER_TYPE_" + NumberIncrease.getAndIncrease()) + typeType = typeType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); } getTypeInfo(result, typeName, typeType, false); - data = re.removeReg(data, matchs.regs[0]) + data = re.removeReg(data, matchs.regs[0]); if (matchs.regs[1][0] !== -1) { - result.exports.push(typeName) + result.exports.push(typeName); } } - matchs = re.match("(export )*type ([a-zA-Z]+) *= *([\\(\\):=a-zA-Z<> |\n']+);", data) + matchs = re.match("(export )*type ([a-zA-Z]+) *= *([\\(\\):=a-zA-Z<> |\n']+);", data); if (matchs) { let typeName = re.getReg(data, matchs.regs[2]); let typeBody = re.getReg(data, matchs.regs[3]); getTypeInfo(result, typeName, analyzeType2(typeBody.substring(1, typeBody.length - 1)), true); - data = re.removeReg(data, matchs.regs[0]) + data = re.removeReg(data, matchs.regs[0]); if (matchs.regs[1][0] !== -1) { - result.exports.push(typeName) + result.exports.push(typeName); } } - matchs = re.match("(export )*type ([a-zA-Z]+) *= *({)", data) + matchs = re.match('(export )*type ([a-zA-Z]+) *= *({)', data); if (matchs) { let typeName = re.getReg(data, matchs.regs[2]); - let typeBody = checkOutBody(data, matchs.regs[3][0], null, true) + let typeBody = checkOutBody(data, matchs.regs[3][0], null, true); if (typeBody === null) { - NapiLog.logError("ParseType typeBody is null!"); + NapiLog.logError('ParseType typeBody is null!'); } - let bodyObj = analyzeType(typeBody.substring(1, typeBody.length - 1), result.type) + let bodyObj = analyzeType(typeBody.substring(1, typeBody.length - 1), result.type); getTypeInfo(result, typeName, bodyObj, false); - data = data.substring(matchs.regs[3][0] + typeBody.length + 2, data.length) + data = data.substring(matchs.regs[3][0] + typeBody.length + 2, data.length); if (matchs.regs[1][0] !== -1) { - result.exports.push(typeName) + result.exports.push(typeName); } } - return data + return data; } function parseFunction(matchs, data, result) { - matchs = re.match("(export )*function (\\$*[A-Za-z0-9_]+) *(\\()", data) + matchs = re.match('(export )*function (\\$*[A-Za-z0-9_]+) *(\\()', data); if (null == matchs) { - matchs = re.match("(export )*function (static )*(\\$*[A-Za-z0-9_]+) *(\\()", data) + matchs = re.match('(export )*function (static )*(\\$*[A-Za-z0-9_]+) *(\\()', data); } if (null == matchs) { - matchs = re.match("(export )*function (static )*(register\\$*[A-Za-z0-9_]+) *(\\()", data) + matchs = re.match('(export )*function (static )*(register\\$*[A-Za-z0-9_]+) *(\\()', data); } if (matchs) { let funcName = re.getReg(data, - matchs.regs.length === 5 ? [matchs.regs[2][0], matchs.regs[3][1]] : matchs.regs[2]) + matchs.regs.length === 5 ? [matchs.regs[2][0], matchs.regs[3][1]] : matchs.regs[2]); let funcValue = checkOutBody(data, - matchs.regs.length === 5 ? matchs.regs[4][0] : matchs.regs[3][0], ["(", ")"], null) + matchs.regs.length === 5 ? matchs.regs[4][0] : matchs.regs[3][0], ['(', ')'], null); let funcRet = checkOutBody(data.substring(matchs.regs.length === 5 ? - matchs.regs[4][0] : matchs.regs[3][0] + funcValue.length), 0, ["", "\n"], null) + matchs.regs[4][0] : matchs.regs[3][0] + funcValue.length), 0, ['', '\n'], null); data = data.substring(matchs.regs.length === 5 ? - matchs.regs[4][0] : matchs.regs[3][0] + funcValue.length + funcRet.length) - let matchFunc = re.match(" *: *([A-Za-z0-9_<>{}\\[\\]:;, .=]+);*", funcRet) - let matchFuncArray = re.match(" *: *([A-Za-z0-9]+)(\\[]);*", funcRet) + matchs.regs[4][0] : matchs.regs[3][0] + funcValue.length + funcRet.length); + let matchFunc = re.match(' *: *([A-Za-z0-9_<>{}\\[\\]:;, .=]+);*', funcRet); + let matchFuncArray = re.match(' *: *([A-Za-z0-9]+)(\\[]);*', funcRet); if (matchFuncArray) { - funcRet = re.getReg(funcRet, [matchFuncArray.regs[1][0], matchFuncArray.regs[2][1]]) + funcRet = re.getReg(funcRet, [matchFuncArray.regs[1][0], matchFuncArray.regs[2][1]]); } else if (matchFunc) { - funcRet = re.getReg(funcRet, matchFunc.regs[1]) + funcRet = re.getReg(funcRet, matchFunc.regs[1]); } else { - funcRet = "void" + funcRet = 'void'; } - funcRet = re.replaceAll(re.replaceAll(funcRet, " ", ""), "\n", "") + funcRet = re.replaceAll(re.replaceAll(funcRet, ' ', ''), '\n', ''); - if(funcRet[funcRet.length-1] === ";"){ - funcRet = funcRet.substring(0, funcRet.length-1) + if(funcRet[funcRet.length-1] === ';'){ + funcRet = funcRet.substring(0, funcRet.length-1); } let funcDetail = analyzeFunction( - result, false, funcName, funcValue.substring(1, funcValue.length - 1), funcRet, result) + result, false, funcName, funcValue.substring(1, funcValue.length - 1), funcRet, result); if (funcDetail !== null) { // 完全一样的方法不重复添加 (如同名同参的AsyncCallback和Promise方法) - addUniqFunc2List(funcDetail, result.function) + addUniqFunc2List(funcDetail, result.function); } if (matchs.regs[1][0] !== -1) { - result.exports.push(funcName) + result.exports.push(funcName); } } - return data + return data; } /** @@ -311,27 +311,27 @@ function parseFunction(matchs, data, result) { */ function getParentNameList(firstKey, secondKey, parentStr) { if (parentStr === '') { - return [] + return []; } - let firstParents = '' - let secondParents = '' + let firstParents = ''; + let secondParents = ''; if (parentStr.indexOf(secondKey) > 0) { // 同时出现extends和implements关键字的情况 (如 extends xx1, xx2 implements yy1, yy2) - firstParents = parentStr.split(secondKey)[0].split(firstKey)[1] - secondParents = parentStr.split(secondKey)[1].trim() + firstParents = parentStr.split(secondKey)[0].split(firstKey)[1]; + secondParents = parentStr.split(secondKey)[1].trim(); } else { // 只有extends或implements一种关键字的情况 (如 extends xx1, xx2 或者 implements yy1, yy2) - firstParents = parentStr.split(firstKey)[1] + firstParents = parentStr.split(firstKey)[1]; } - let nameList = firstParents.split(",") + let nameList = firstParents.split(','); if (secondParents !== '') { - let secondList = secondParents.split(",") - nameList.push(...secondList) + let secondList = secondParents.split(','); + nameList.push(...secondList); } - return nameList + return nameList; } /** @@ -342,71 +342,71 @@ function getParentNameList(firstKey, secondKey, parentStr) { * @returns data 原始ts文件内容中剩余未解析的部分 */ function createInterfaceData (matchs, data, result) { - let interfaceName = re.getReg(data, matchs.regs[2]) - let interfaceBody = checkOutBody(data, matchs.regs[6][0], null, null) + let interfaceName = re.getReg(data, matchs.regs[2]); + let interfaceBody = checkOutBody(data, matchs.regs[6][0], null, null); let bodyObj = analyzeInterface(interfaceBody.substring(1, interfaceBody.length - 1), result.interface, - result, interfaceName) - let extendsParent = re.getReg(data, matchs.regs[4]) - let implementParent = re.getReg(data, matchs.regs[5]) - bodyObj.parentNameList = [] + result, interfaceName); + let extendsParent = re.getReg(data, matchs.regs[4]); + let implementParent = re.getReg(data, matchs.regs[5]); + bodyObj.parentNameList = []; if(extendsParent !== '') { - bodyObj.parentNameList = getParentNameList("extends", "implements", extendsParent) + bodyObj.parentNameList = getParentNameList('extends', 'implements', extendsParent); } if(implementParent !== '') { - bodyObj.parentNameList = getParentNameList("implements", "extends", implementParent) + bodyObj.parentNameList = getParentNameList('implements', 'extends', implementParent); } for (let i in bodyObj.parentNameList) { - bodyObj.parentNameList[i] = bodyObj.parentNameList[i].trim() + bodyObj.parentNameList[i] = bodyObj.parentNameList[i].trim(); if (bodyObj.parentNameList[i] === interfaceName) { // 接口不能自己继承自己 - NapiLog.logError("The interface [%s] can not extends with itself.".format(interfaceName)) - return data + NapiLog.logError('The interface [%s] can not extends with itself.'.format(interfaceName)); + return data; } } - bodyObj.parentList = [] // 该接口继承的父类型列表 - bodyObj.childList = [] // 继承自该接口的子类型列表 + bodyObj.parentList = []; // 该接口继承的父类型列表 + bodyObj.childList = []; // 继承自该接口的子类型列表 result.interface.push({ name: interfaceName, body: bodyObj - }) - let rr = matchs.regs[6][0] - rr = matchs.regs[6][0] + interfaceBody.length - let tmp = data[rr] - data = data.substring(matchs.regs[6][0] + interfaceBody.length, data.length) + }); + let rr = matchs.regs[6][0]; + rr = matchs.regs[6][0] + interfaceBody.length; + let tmp = data[rr]; + data = data.substring(matchs.regs[6][0] + interfaceBody.length, data.length); if (matchs.regs[1][0] !== -1) { - result.exports.push(interfaceName) + result.exports.push(interfaceName); } - return data + return data; } function parseInterface(matchs, data, result) { matchs = re.match( - "(export )*interface ([A-Za-z_0-9]+)()* *(extends [a-zA-Z_0-9, ]+)* *(implements [a-zA-Z_0-9, ]+)* *({)" - , data) + '(export )*interface ([A-Za-z_0-9]+)()* *(extends [a-zA-Z_0-9, ]+)* *(implements [a-zA-Z_0-9, ]+)* *({)' + , data); if (matchs) { - return createInterfaceData (matchs, data, result) + return createInterfaceData (matchs, data, result); } - return data + return data; } function removeReg(matchs, data, result) { - matchs = re.match("export { ([a-zA-Z]+) };", data) + matchs = re.match('export { ([a-zA-Z]+) };', data); if (matchs) { - let exportName = re.getReg(data, matchs.regs[1]) - result.exports.push(exportName) - data = re.removeReg(data, matchs.regs[0]) + let exportName = re.getReg(data, matchs.regs[1]); + result.exports.push(exportName); + data = re.removeReg(data, matchs.regs[0]); } - matchs = re.match("export import [a-zA-Z]+ = [a-zA-Z\\.]+;", data) + matchs = re.match('export import [a-zA-Z]+ = [a-zA-Z\\.]+;', data); if (matchs) { - data = re.removeReg(data, matchs.regs[0]) + data = re.removeReg(data, matchs.regs[0]); } - matchs = re.match("readonly [a-zA-Z]+: [a-z\\[\\]]+;*", data) + matchs = re.match('readonly [a-zA-Z]+: [a-z\\[\\]]+;*', data); if (matchs) { - data = re.removeReg(data, matchs.regs[0]) + data = re.removeReg(data, matchs.regs[0]); } - return data + return data; } module.exports = { analyzeNamespace, @@ -416,4 +416,4 @@ module.exports = { parseInterface, parseClass, parseType -} \ No newline at end of file +}; \ No newline at end of file diff --git a/src/cli/dts2cpp/src/gen/analyze/params.js b/src/cli/dts2cpp/src/gen/analyze/params.js index 4249855149bbf126a4a8ea3f62aa258b046ae958..77baa6796655cedcb273f94fdd4e0cdb30cc563e 100644 --- a/src/cli/dts2cpp/src/gen/analyze/params.js +++ b/src/cli/dts2cpp/src/gen/analyze/params.js @@ -12,14 +12,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const re = require("../tools/re"); -const { checkOutBody, print } = require("../tools/tool"); -const { FuncType, NumberIncrease,isFuncType, isArrowFunc,isRegisterFunc } = require("../tools/common"); -const { NapiLog } = require("../tools/NapiLog"); +const re = require('../tools/re'); +const { checkOutBody, print } = require('../tools/tool'); +const { FuncType, NumberIncrease,isFuncType, isArrowFunc,isRegisterFunc } = require('../tools/common'); +const { NapiLog } = require('../tools/NapiLog'); function isSyncFuncType(type, funcType) { let isSync = false; - if (funcType === FuncType.DIRECT && type.indexOf("Callback") >= 0 && type.indexOf("AsyncCallback") < 0 || + if (funcType === FuncType.DIRECT && type.indexOf('Callback') >= 0 && type.indexOf('AsyncCallback') < 0 || isFuncType(type) || isArrowFunc(type)) { isSync = true; } @@ -35,62 +35,62 @@ function isSyncFuncType(type, funcType) { function analyzeCallbackFunction(valueType, valueName, rsltCallFunction) { if (valueType.indexOf('=>') > 0) { - valueType = re.replaceAll(valueType, ' ', '') + valueType = re.replaceAll(valueType, ' ', ''); } - let matchs = re.match("\\(([a-zA-Z_0-9:,]+)*\\)=>([a-zA-Z_0-9]+)", valueType) + let matchs = re.match('\\(([a-zA-Z_0-9:,]+)*\\)=>([a-zA-Z_0-9]+)', valueType); if (matchs) { let number = NumberIncrease.getAndIncrease(); - let functionTypeName = 'AUTO_CALLFUNCTION_%s_%s'.format(valueName, number) + let functionTypeName = 'AUTO_CALLFUNCTION_%s_%s'.format(valueName, number); let functionRet = re.getReg(valueType, matchs.regs[2]); let functionBody = re.getReg(valueType, matchs.regs[1]); - let tmp = analyzeParams(functionTypeName, functionBody) - let bodyRes = tmp[0] + let tmp = analyzeParams(functionTypeName, functionBody); + let bodyRes = tmp[0]; for (let i in bodyRes) { - let hasProperty = Object.prototype.hasOwnProperty.call(bodyRes[i], "type") - if (hasProperty && bodyRes[i].type === "number") { - bodyRes[i].type = "NUMBER_TYPE_" + NumberIncrease.getAndIncrease(); + let hasProperty = Object.prototype.hasOwnProperty.call(bodyRes[i], 'type'); + if (hasProperty && bodyRes[i].type === 'number') { + bodyRes[i].type = 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease(); } } rsltCallFunction.push({ - "name": functionTypeName, - "body": bodyRes, - "ret": functionRet - }) - valueType = functionTypeName + 'name': functionTypeName, + 'body': bodyRes, + 'ret': functionRet + }); + valueType = functionTypeName; } - return valueType + return valueType; } /**函数参数解析 */ function analyzeParams(funcName, values) { - let result = [] - let rsltCallFunction = [] - let funcType = FuncType.DIRECT + let result = []; + let rsltCallFunction = []; + let funcType = FuncType.DIRECT; let optionalParamCount = 0; // 可选参数的个数 while (values.length > 0) { - let v = checkOutBody(values, 0, ["", ","]) + let v = checkOutBody(values, 0, ['', ',']); if (v === null) { - v = values + v = values; } - values = values.substring(v.length, values.length) - let matchs = re.match("([a-zA-Z_0-9\\.]+)(\\?*): *([a-zA-Z<,>|_0-9\\[\\]\\(\\):='{}]+)", v) - if (matchs === null && (funcName === "on" || funcName === "off")) { + values = values.substring(v.length, values.length); + let matchs = re.match("([a-zA-Z_0-9\\.]+)(\\?*): *([a-zA-Z<,>|_0-9\\[\\]\\(\\):='{}]+)", v); + if (matchs === null && (funcName === 'on' || funcName === 'off')) { // on和off的第一个参数的类型可以是一串字符 - matchs = re.match("([a-zA-Z_0-9\\.]+)(\\?*): *\"([a-zA-Z|_0-9\\[\\]\\(\\):='{}]+)\"", v) + matchs = re.match("([a-zA-Z_0-9\\.]+)(\\?*): *\"([a-zA-Z|_0-9\\[\\]\\(\\):='{}]+)\"", v); } if (matchs !== null) { - let type = re.getReg(v, matchs.regs[3]) - if (type.indexOf("Map") < 0 && !isArrowFunc(type)) { - type = type.replace(/,/g, "") + let type = re.getReg(v, matchs.regs[3]); + if (type.indexOf('Map') < 0 && !isArrowFunc(type)) { + type = type.replace(/,/g, ''); } - let valueName = re.getReg(v, matchs.regs[1]) - type = analyzeCallbackFunction(type, valueName, rsltCallFunction) + let valueName = re.getReg(v, matchs.regs[1]); + type = analyzeCallbackFunction(type, valueName, rsltCallFunction); let optionalFlag = re.getReg(v, matchs.regs[2]) === '?' ? true : false; let checkParamOk = true; @@ -98,28 +98,28 @@ function analyzeParams(funcName, values) { optionalParamCount++; } else if (optionalParamCount > 0) { // 可选参数之后不能再有必选参数,须是可选参数。 - NapiLog.logError("Invalid parameter [%s] of function [%s],".format(v, funcName) - + " the required parameter cannot follow an optional parameter."); + NapiLog.logError('Invalid parameter [%s] of function [%s],'.format(v, funcName) + + ' the required parameter cannot follow an optional parameter.'); checkParamOk = false; } if (checkParamOk) { - result.push({ "name": re.getReg(v, matchs.regs[1]), "type": type, "optional": optionalFlag, "realType": type}) - if (type.indexOf("AsyncCallback") >= 0) { - funcType = FuncType.ASYNC + result.push({ 'name': re.getReg(v, matchs.regs[1]), 'type': type, 'optional': optionalFlag, 'realType': type}); + if (type.indexOf('AsyncCallback') >= 0) { + funcType = FuncType.ASYNC; } if (isSyncFuncType(type, funcType)) { - funcType = FuncType.SYNC + funcType = FuncType.SYNC; } } } else { - NapiLog.logError("Failed to analyse parameter [%s] of function [%s].".format(v, funcName)); + NapiLog.logError('Failed to analyse parameter [%s] of function [%s].'.format(v, funcName)); } } - return [result, funcType, rsltCallFunction] + return [result, funcType, rsltCallFunction]; } module.exports = { analyzeParams -} +}; diff --git a/src/cli/dts2cpp/src/gen/analyze/return.js b/src/cli/dts2cpp/src/gen/analyze/return.js index 1fec3b3a35c89812bc23616ddb3391b79bf58497..138290b189749f1fcc16e9f4fee94b456be64177 100644 --- a/src/cli/dts2cpp/src/gen/analyze/return.js +++ b/src/cli/dts2cpp/src/gen/analyze/return.js @@ -12,17 +12,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const re = require("../tools/re"); +const re = require('../tools/re'); /**函数返回值解析 */ function analyzeReturn(ret) { - let isPromise = false - if (ret.indexOf("Promise") >= 0) { - isPromise = true + let isPromise = false; + if (ret.indexOf('Promise') >= 0) { + isPromise = true; } - return [ret, isPromise] + return [ret, isPromise]; } module.exports = { analyzeReturn -} \ No newline at end of file +}; \ No newline at end of file diff --git a/src/cli/dts2cpp/src/gen/analyze/type.js b/src/cli/dts2cpp/src/gen/analyze/type.js index 66c1eb4ab262f73dbc47a6ee0b8a5e878dde6740..91f5d5bd4c8993aac7d9dace384e2ad3a9c5d4c2 100644 --- a/src/cli/dts2cpp/src/gen/analyze/type.js +++ b/src/cli/dts2cpp/src/gen/analyze/type.js @@ -27,31 +27,31 @@ function parseNotes(data) { notes = data.substring(st, data.length); } } - return data + return data; } /**type解析 */ function analyzeType(data, rsltInterface = null) { // same as class - let body = data - body = body.indexOf('//') < 0 ? body : parseNotes(body) - body = re.replaceAll(body, '\n', '').split(';') + let body = data; + body = body.indexOf('//') < 0 ? body : parseNotes(body); + body = re.replaceAll(body, '\n', '').split(';'); let result = { value: [], // function: [] - } + }; for (let i in body) { - let t = body[i] + let t = body[i]; while (t.length > 0 && t[0] === ' ') // 去除前面的空格 - t = t.substring(1, t.length) + t = t.substring(1, t.length); while (t.length > 0 && t[-1] === ' ') // 去除后面的空格 - t = t.substring(0, t.length - 1) - if (t === '') break // 如果t为空直接返回 - let tt = re.match(' *([a-zA-Z0-9_]+)(\\?*)*: *([a-zA-Z_0-9<>,:{}[\\]| ]+)', t) + t = t.substring(0, t.length - 1); + if (t === '') break; // 如果t为空直接返回 + let tt = re.match(' *([a-zA-Z0-9_]+)(\\?*)*: *([a-zA-Z_0-9<>,:{}[\\]| ]+)', t); if (tt && t.indexOf('=>') < 0) { // 接口成员变量, 但不包括带'=>'的成员,带'=>'的接口成员需要按函数处理 analyzeTypeVariable(t, tt, result); } } - return result + return result; } function analyzeTypeVariable(t, tt, result) { @@ -71,42 +71,42 @@ function analyzeTypeVariable(t, tt, result) { } function analyzeType2(data) { - let body = re.replaceAll(data, ' ', '').split('"|"') + let body = re.replaceAll(data, ' ', '').split("'|'"); let result = { element: [], function: [], enumValueType: 0 // 0代表数字,1代表字符串 - } + }; for (let i in body) { - let bodyContent = body[i] - while (bodyContent.length > 0 && bodyContent[0] === ' ') { - bodyContent = bodyContent.substring(1, bodyContent.length) + let bodyContent = body[i]; + while (bodyContent.length > 0 && bodyContent[0] == ' ') { + bodyContent = bodyContent.substring(1, bodyContent.length); } - while (bodyContent.length > 0 && bodyContent[-1] === ' ') { - bodyContent = bodyContent.substring(0, bodyContent.length - 1) + while (bodyContent.length > 0 && bodyContent[-1] == ' ') { + bodyContent = bodyContent.substring(0, bodyContent.length - 1); } - if (bodyContent === '') { - break + if (bodyContent == '') { + break; } - analyzeType2Result(result, bodyContent, i) + analyzeType2Result(result, bodyContent, i); } - return result + return result; } function analyzeType2Result(result, bodyContent, index) { - let regString = re.match(' *([a-zA-Z0-9_]+) *', bodyContent) + let regString = re.match(' *([a-zA-Z0-9_]+) *', bodyContent); if (regString) { - let elementName = re.getReg(bodyContent, regString.regs[1]) + let elementName = re.getReg(bodyContent, regString.regs[1]); elementName = 'NAME_' + elementName.toUpperCase() - let elementValue = re.getReg(bodyContent, regString.regs[1]) + let elementValue = re.getReg(bodyContent, regString.regs[1]); result.element.push({ name: elementName, value: elementValue, type: 'string' - }) - result.enumValueType = 1 + }); + result.enumValueType = 1; } - return result + return result; } module.exports = { @@ -114,4 +114,4 @@ module.exports = { analyzeType2, analyzeType2Result, parseNotes -} \ No newline at end of file +}; \ No newline at end of file diff --git a/src/cli/dts2cpp/src/gen/cmd_gen.js b/src/cli/dts2cpp/src/gen/cmd_gen.js index 57002127fd4249fb6e86ecef76b664f452881ea5..8e8832ead8c95c508aceb57f6b22de9ce44fb328 100644 --- a/src/cli/dts2cpp/src/gen/cmd_gen.js +++ b/src/cli/dts2cpp/src/gen/cmd_gen.js @@ -12,25 +12,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const main = require("./main"); -const tsMain = require("../tsGen/tsMain"); -const re = require("./tools/re"); -const { checkFileError } = require("./tools/common"); -const { NapiLog } = require("./tools/NapiLog"); -const path = require("path"); -const stdio = require("stdio"); +const main = require('./main'); +const tsMain = require('../tsGen/tsMain'); +const re = require('./tools/re'); +const { checkFileError } = require('./tools/common'); +const { NapiLog } = require('./tools/NapiLog'); +const path = require('path'); +const stdio = require('stdio'); var fs = require('fs'); -const { print } = require("./tools/tool"); +const { print } = require('./tools/tool'); let ops = stdio.getopt({ - 'filename': { key: 'f', args: 1, description: ".d.ts file", default: "" }, - 'directory': { key: 'd', args: 1, description: ".d.ts directory", default: "" }, - 'imports': { key: 'i', args: 1, description: "enable or disable support imports self-define file", default: false }, - 'out': { key: 'o', args: 1, description: "output directory", default: "." }, - 'loglevel': { key: 'l', args: 1, description: "Log Level : 0~3", default: "1" }, + 'filename': { key: 'f', args: 1, description: '.d.ts file', default: '' }, + 'directory': { key: 'd', args: 1, description: '.d.ts directory', default: '' }, + 'imports': { key: 'i', args: 1, description: 'enable or disable support imports self-define file', default: false }, + 'out': { key: 'o', args: 1, description: 'output directory', default: '.' }, + 'loglevel': { key: 'l', args: 1, description: 'Log Level : 0~3', default: '1' }, // 新增控制number类型转C++类型参数 - 'numbertype':{key: 'n', args: 1, description: "optional elemtype: basic cpp elemtype", default: "uint32_t"}, - 'tsGen':{key: 't', args: 1, description: "enable or disable generate typescript file", default: false }, + 'numbertype':{key: 'n', args: 1, description: 'optional elemtype: basic cpp elemtype', default: 'uint32_t'}, + 'tsGen':{key: 't', args: 1, description: 'enable or disable generate typescript file', default: false }, /* 新增业务代码可配置参数:写在json文件里: * [{"includeName":"xxx.h", "cppName":"xxx.cpp","interfaceName": "functest", @@ -41,14 +41,14 @@ let ops = stdio.getopt({ }); -NapiLog.init(ops.loglevel, path.join("" + ops.out, "napi_gen.log")) +NapiLog.init(ops.loglevel, path.join("" + ops.out, "napi_gen.log")); let fileNames = ops.filename; var pathDir = ops.directory; var imports = ops.imports; if (fileNames == null && pathDir == null) { - NapiLog.logInfo("fileNames and pathDir both cannot be empty at the same time"); -} else if (pathDir !== '') { + NapiLog.logInfo('fileNames and pathDir both cannot be empty at the same time'); +} else if (pathDir != '') { readDirFiles(); } else if (fileNames !== '') { readFiles(); @@ -78,7 +78,7 @@ function handleDirFiles(files) { if (i === files.length) { return; } - let data = fs.statSync(path.join(pathDir + '', files[i])) + let data = fs.statSync(path.join(pathDir + '', files[i])); if (data.isFile()) { let fileName = files[i]; checkGenerate(pathDir + '/' + fileName); @@ -107,16 +107,16 @@ function getJsonCfg(currentPath) { let jsonCfg = null; // cfg.json 配置文件 currentPath = currentPath.replace(/(^\s*)|(\s*$)/g, ''); // trim before and after espace let jsonFilePath = path.join(currentPath); - let jsonFile = fs.readFileSync(jsonFilePath, { encoding: "utf8" }); + let jsonFile = fs.readFileSync(jsonFilePath, { encoding: 'utf8' }); jsonCfg = JSON.parse(jsonFile); return jsonCfg; } function checkGenerate(fileName) { - NapiLog.logInfo("check file []".format(fileName)) + NapiLog.logInfo('check file []'.format(fileName)); let suffix = fileName.split('.').pop().toLowerCase(); - if (ops.tsGen === 'true' && suffix === 'h') { - NapiLog.logInfo("convert .h file to .ts file...") + if (ops.tsGen == 'true' && suffix === 'h') { + NapiLog.logInfo('convert .h file to .ts file...'); tsMain.doGenerate(fileName, ops.out); return; } @@ -124,7 +124,7 @@ function checkGenerate(fileName) { let tt = re.match('(@ohos\.)*([.a-z_A-Z0-9]+).d.ts', fn); if (tt) { let result = checkFileError(fileName); - let jsonConfig + let jsonConfig; if (ops.serviceCode) { jsonConfig = getJsonCfg(ops.serviceCode); } diff --git a/src/cli/dts2cpp/src/gen/debug.js b/src/cli/dts2cpp/src/gen/debug.js index 5f51395d24b168b1cb3321464dede132c54edd91..9a38dd057b677c22865b48a67fcf69db5ac6362c 100644 --- a/src/cli/dts2cpp/src/gen/debug.js +++ b/src/cli/dts2cpp/src/gen/debug.js @@ -12,10 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const main = require("../../hdc/appCodeGen/src/main"); -const { getJsonCfg } = require("../../hdc/appCodeGen/src/app_code_gen"); -const { NapiLog } = require("./tools/NapiLog"); -const re = require("./tools/re"); +const main = require('../../hdc/appCodeGen/src/main'); +const { getJsonCfg } = require('../../hdc/appCodeGen/src/app_code_gen'); +const { NapiLog } = require('./tools/NapiLog'); +const re = require('./tools/re'); //let file_path = `./@ohos.napitest.d.ts` @@ -33,16 +33,16 @@ const re = require("./tools/re"); // let file_path = `D:\\DOC\\NAPI\\feature\\supported\\@ohos.napitestsupportSingle.d.ts` // let file_path = './test/storytest/test_type/@ohos.test.d.ts' -let file_path = 'D:\\Code\\debugAppCodeGen\\napi1109\\napi_generator_0824\\@ohos.napitest.d.ts' -let fn = re. getFileInPath(file_path) -let jsonCfg = `D:\\Code\\debugAppCodeGen\\napi1109\\napi_generator_0824\\funTestCfg.json` -NapiLog.init(NapiLog.LEV_INFO, "napi_gen.log") -NapiLog.logError("Begin to test."); -let funcConfig +let file_path = 'D:\\Code\\debugAppCodeGen\\napi1109\\napi_generator_0824\\@ohos.napitest.d.ts'; +let fn = re. getFileInPath(file_path); +let jsonCfg = `D:\\Code\\debugAppCodeGen\\napi1109\\napi_generator_0824\\funTestCfg.json`; +NapiLog.init(NapiLog.LEV_INFO, 'napi_gen.log'); +NapiLog.logError('Begin to test.'); +let funcConfig; if (jsonCfg) { funcConfig = getJsonCfg(jsonCfg); } -let tt = re.match("(@ohos\.)*([.a-z_A-Z0-9]+).d.ts", fn) // @ohos\.[a-zA-Z0-9]+\.d\.ts +let tt = re.match('(@ohos\.)*([.a-z_A-Z0-9]+).d.ts', fn); // @ohos\.[a-zA-Z0-9]+\.d\.ts if (tt) { - main.doGenerate(file_path, "D:\\Code\\debugAppCodeGen\\napi1109\\napi_generator_0824\\appOut", funcConfig) + main.doGenerate(file_path, 'D:\\Code\\debugAppCodeGen\\napi1109\\napi_generator_0824\\appOut', funcConfig); } diff --git a/src/cli/dts2cpp/src/gen/extend/binding_gyp.js b/src/cli/dts2cpp/src/gen/extend/binding_gyp.js index c8c2d4525b4d04c3ee3624cbdee6a53fa97d7fea..4bfec0938a9ca6febb6c88cc1f5b2f6c4192e5f8 100644 --- a/src/cli/dts2cpp/src/gen/extend/binding_gyp.js +++ b/src/cli/dts2cpp/src/gen/extend/binding_gyp.js @@ -29,12 +29,12 @@ let gypTemplete = ` } ] } -` +`; /**创建nodejs编译文件,用于在ubuntu测试 */ function generateGYP(destDir, implName, license, bindingCpp) { - let ss = gypTemplete.replaceAll('[implName]', implName) - ss = ss.replaceAll('[businessCodeCpp]', bindingCpp) + let ss = gypTemplete.replaceAll('[implName]', implName); + ss = ss.replaceAll('[businessCodeCpp]', bindingCpp); if (license) { let s2 = license.substring(2, license.length - 2).split('\n'); license = ''; @@ -64,4 +64,4 @@ function getLicense(s2, i, license) { module.exports = { generateGYP -} \ No newline at end of file +} diff --git a/src/cli/dts2cpp/src/gen/extend/build_gn.js b/src/cli/dts2cpp/src/gen/extend/build_gn.js index b12245320069e763b8c453d3f2e13c70792045b4..986ee44e42dd488d985c65c9b125a95f6588eaa9 100644 --- a/src/cli/dts2cpp/src/gen/extend/build_gn.js +++ b/src/cli/dts2cpp/src/gen/extend/build_gn.js @@ -46,13 +46,13 @@ ohos_shared_library("[implName]") part_name = "[partName]" subsystem_name = "[subsystemName]" } -` +`; /**创建nodejs编译文件,用于在ubuntu测试 */ function generateGN(destDir, implName, license, partName, buildCpp) { let subsystemName = implName; let gnFile = gnTemplete.replaceAll('[implName]', implName); - gnFile = gnFile.replaceAll('[businessCodeCpp]', buildCpp) + gnFile = gnFile.replaceAll('[businessCodeCpp]', buildCpp); gnFile = gnFile.replaceAll('[subsystemName]', subsystemName); gnFile = gnFile.replaceAll('[partName]', partName); if (license) { @@ -81,4 +81,4 @@ function getGnLicense(license) { module.exports = { generateGN -} \ No newline at end of file +} diff --git a/src/cli/dts2cpp/src/gen/extend/tool_utility.js b/src/cli/dts2cpp/src/gen/extend/tool_utility.js index 21cae6f0a8bdcb49c740cf3b4dd149071d9c4ca1..735ad6bd008f11e48ee23d2d36cdc54c18a49919 100644 --- a/src/cli/dts2cpp/src/gen/extend/tool_utility.js +++ b/src/cli/dts2cpp/src/gen/extend/tool_utility.js @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { writeFile } = require("../tools/FileRW"); -const re = require("../tools/re"); +const { writeFile } = require('../tools/FileRW'); +const re = require('../tools/re'); let xNapiToolH = `\ #ifndef CC_TOOL_H @@ -254,7 +254,7 @@ private: }; #endif -` +`; let xNapiToolCpp = ` @@ -1777,13 +1777,13 @@ void XNapiTool::CallThreadSafeFunc(std::string eventName) { return; } } -` +`; function generateBase(destDir, license) { - writeFile(re.pathJoin(destDir, "tool_utility.h"), null != license ? (license + "\n" + xNapiToolH) : xNapiToolH) - writeFile(re.pathJoin(destDir, "tool_utility.cpp"), null != license ? (license + "\n" + xNapiToolCpp):xNapiToolCpp) + writeFile(re.pathJoin(destDir, 'tool_utility.h'), null != license ? (license + '\n' + xNapiToolH) : xNapiToolH); + writeFile(re.pathJoin(destDir, 'tool_utility.cpp'), null != license ? (license + '\n' + xNapiToolCpp):xNapiToolCpp); } module.exports = { generateBase -} \ No newline at end of file +}; \ No newline at end of file diff --git a/src/cli/dts2cpp/src/gen/generate.js b/src/cli/dts2cpp/src/gen/generate.js index daa4c63d33d9e6012a1e9c2da190fe48a3319d36..5b07f354008d11649dbcf6c304c18dbdcac103f7 100644 --- a/src/cli/dts2cpp/src/gen/generate.js +++ b/src/cli/dts2cpp/src/gen/generate.js @@ -14,17 +14,17 @@ */ // 生成BUILD.gn // 生成tool_utility.h,生成tool_utility.cpp -const { replaceAll } = require("./tools/tool"); -const { generateNamespace } = require("./generate/namespace"); -const { writeFile } = require("./tools/FileRW"); -const re = require("./tools/re"); -const { generateGYP } = require("./extend/binding_gyp"); -const { generateGN } = require("./extend/build_gn"); -const { generateBase } = require("./extend/tool_utility"); -const { NumberIncrease, jsonCfgList } = require("./tools/common"); -const os = require("os"); -const path = require('path') -const { NapiLog } = require("./tools/NapiLog"); +const { replaceAll } = require('./tools/tool'); +const { generateNamespace } = require('./generate/namespace'); +const { writeFile } = require('./tools/FileRW'); +const re = require('./tools/re'); +const { generateGYP } = require('./extend/binding_gyp'); +const { generateGN } = require('./extend/build_gn'); +const { generateBase } = require('./extend/tool_utility'); +const { NumberIncrease, jsonCfgList } = require('./tools/common'); +const os = require('os'); +const path = require('path'); +const { NapiLog } = require('./tools/NapiLog'); var fs = require('fs'); let moduleHTemplete = `\ @@ -43,7 +43,7 @@ let moduleHTemplete = `\ [implH_detail] #endif // IMPL_[impl_name_upper]_H -` +`; let moduleCppTmplete = `\ #include @@ -129,7 +129,7 @@ extern "C" __attribute__((constructor)) void Register_[implName]_Module(void) { napi_module_register(&g_[implName]_Module); } -` +`; let implHTemplete = `\ #ifndef IMPL_[impl_name_upper]_H @@ -146,86 +146,86 @@ let implHTemplete = `\ [numberUsing] [implH_detail] #endif // IMPL_[impl_name_upper]_H -` +`; let implCppTemplete = `\ #include "[implName].h" #include "[implName]_middle.h" [include_configure_hCode] [implCpp_detail] -` -var genFileList = [] +`; +var genFileList = []; function deleteFolder(folderPath) { if (fs.existsSync(folderPath)) { - fs.rmSync(folderPath, {"recursive": true}) + fs.rmSync(folderPath, {'recursive': true}); } } function createFolder(folderPath) { if (!fs.existsSync(folderPath)) { - fs.mkdirSync(folderPath) + fs.mkdirSync(folderPath); } } function formatCode(destDir) { - let sysInfo = os.platform() - let clangFmtName = sysInfo === 'win32' ? "clang-format.exe" : "clang-format" + let sysInfo = os.platform(); + let clangFmtName = sysInfo === 'win32' ? 'clang-format.exe' : 'clang-format'; let callPath = NapiLog.getCallPath(); - callPath = callPath.substring(callPath.indexOf("[") + 1, callPath.indexOf("src")); - let dumyClangFmtFile = path.join(callPath, clangFmtName) - let dumyFmtCfgFile = path.join(callPath, ".clang-format") + callPath = callPath.substring(callPath.indexOf('[') + 1, callPath.indexOf('src')); + let dumyClangFmtFile = path.join(callPath, clangFmtName); + let dumyFmtCfgFile = path.join(callPath, '.clang-format'); if(!fs.existsSync(dumyClangFmtFile)) { - NapiLog.logInfo("Warning: clang-format does not exist, can not format cpp file."); - return + NapiLog.logInfo('Warning: clang-format does not exist, can not format cpp file.'); + return; } // 使用pkg打包的napi_generator工具,其中的clang-format程序在运行时是解压到一个名为snapshot的虚拟目录中的,如C:\snapshot\napi_generator\ // 虚拟目录中的clang-format程序不能直接运行,必须先将它拷贝到本地硬盘的真实目录下。 - createFolder(path.resolve("./tmpLocal")) - let localClangFmtFile = path.resolve("./tmpLocal/" + clangFmtName) // clang-format可执行程序 - let localFmtCfgFile = path.resolve("./tmpLocal/.clang-format") // clang-format格式化配置文件 - fs.copyFileSync(dumyClangFmtFile, localClangFmtFile) - fs.copyFileSync(dumyFmtCfgFile, localFmtCfgFile) - - let execSync = require("child_process").execSync - if (sysInfo !== 'win32') { + createFolder(path.resolve('./tmpLocal')); + let localClangFmtFile = path.resolve('./tmpLocal/' + clangFmtName); // clang-format可执行程序 + let localFmtCfgFile = path.resolve('./tmpLocal/.clang-format'); // clang-format格式化配置文件 + fs.copyFileSync(dumyClangFmtFile, localClangFmtFile); + fs.copyFileSync(dumyFmtCfgFile, localFmtCfgFile); + + let execSync = require('child_process').execSync; + if (sysInfo != 'win32') { // linux系统下需要为临时复制的clang-format程序增加可执行权限 - execSync("chmod +x " + "\"" + localClangFmtFile + "\"") + execSync('chmod +x ' + '\"' + localClangFmtFile + '\"'); } for (let i = 0; i < genFileList.length; ++i) { // 文件路径前后要用引号包含,防止因为路径中存在空格而导致命令执行失败 (windows的文件夹允许有空格) - let cmd = "\"" + localClangFmtFile + "\" -style=file -i \"" + path.resolve(path.join(destDir, genFileList[i])) - + "\"" + let cmd = '\"' + localClangFmtFile + '\" -style=file -i \"' + path.resolve(path.join(destDir, genFileList[i])) + + '\"'; try { - execSync(cmd) // C++文件格式化 + execSync(cmd); // C++文件格式化 } catch (err) { - NapiLog.logError("Failed to format code, exception: " + err.stderr) + NapiLog.logError('Failed to format code, exception: ' + err.stderr); } } // 格式化结束后,删除临时目录文件 - deleteFolder(path.resolve("./tmpLocal")) + deleteFolder(path.resolve('./tmpLocal')); } function analyzeJsonCfg(jsonCfg) { let len = jsonCfg.length; - let jsonConfig = [] + let jsonConfig = []; // 将json文件的数据存入jsonCfgList中 for (let i = 0; i < len; i++) { - let interfaceBody = null - if (jsonCfg[i].interfaceName.indexOf("::") > 0) { - let tt = jsonCfg[i].interfaceName.split("::") + let interfaceBody = null; + if (jsonCfg[i].interfaceName.indexOf('::') > 0) { + let tt = jsonCfg[i].interfaceName.split('::'); interfaceBody = { className: tt[0], funcName: tt[1], - } + }; } else { interfaceBody = { - className: "", + className: '', funcName: jsonCfg[i].interfaceName, - } + }; } jsonConfig.push({ @@ -233,9 +233,9 @@ function analyzeJsonCfg(jsonCfg) { cppName: jsonCfg[i].cppName, interfaceName: interfaceBody, serviceCode: jsonCfg[i].serviceCode.replaceAll('\\n', '\n'), - }) + }); } - jsonCfgList.push(jsonConfig) + jsonCfgList.push(jsonConfig); } function generateAll(structOfTs, destDir, moduleName, numberType, jsonCfg) { @@ -250,9 +250,9 @@ function generateAll(structOfTs, destDir, moduleName, numberType, jsonCfg) { analyzeJsonCfg(jsonCfg); } - let result = generateNamespace(ns0.name, ns0.body) + let result = generateNamespace(ns0.name, ns0.body); - jsonCfgList.pop() + jsonCfgList.pop(); let numberUsing = "" var numbertype = "uint32_t"; @@ -260,17 +260,17 @@ function generateAll(structOfTs, destDir, moduleName, numberType, jsonCfg) { numbertype = numberType; } for (let i = 1; i < NumberIncrease.get(); i++) { - numberUsing += "using NUMBER_TYPE_%d = ".format(i) + numbertype + ";\n" + numberUsing += 'using NUMBER_TYPE_%d = '.format(i) + numbertype + ';\n'; } generateMiddleH(ns0, result, destDir, license); generateMiddleCpp(result, ns0, moduleName, destDir, license); generateImplH(ns0, numberUsing, result, structOfTs, destDir, license); - let implCpp = implCppTemplete.replaceAll("[implName]", ns0.name) - let bindingCpp = '' - let buildCpp = '' - let includeH = '' + let implCpp = implCppTemplete.replaceAll('[implName]', ns0.name); + let bindingCpp = ''; + let buildCpp = ''; + let includeH = ''; if (jsonCfg) { let includeHCppRes = includeHCppFunc(jsonCfg, includeH, bindingCpp, buildCpp); bindingCpp = includeHCppRes[0]; @@ -293,9 +293,9 @@ function generateAll(structOfTs, destDir, moduleName, numberType, jsonCfg) { } function generateImplH(ns0, numberUsing, result, structOfTs, destDir, license) { - let implH = replaceAll(implHTemplete, "[impl_name_upper]", ns0.name.toUpperCase()); - implH = implH.replaceAll("[numberUsing]", numberUsing); - implH = replaceAll(implH, "[implH_detail]", result.implH); + let implH = replaceAll(implHTemplete, '[impl_name_upper]', ns0.name.toUpperCase()); + implH = implH.replaceAll('[numberUsing]', numberUsing); + implH = replaceAll(implH, '[implH_detail]', result.implH); let imports = ''; for (let i = 0; i < structOfTs.imports.length; i++) { imports += structOfTs.imports[i]; @@ -307,10 +307,10 @@ function generateImplH(ns0, numberUsing, result, structOfTs, destDir, license) { } function generateMiddleCpp(result, ns0, moduleName, destDir, license) { - let middleCpp = replaceAll(moduleCppTmplete, "[body_replace]", result.middleBody); - middleCpp = replaceAll(middleCpp, "[init_replace]", result.middleInit); - middleCpp = replaceAll(middleCpp, "[implName]", ns0.name); - middleCpp = replaceAll(middleCpp, "[modulename]", moduleName); + let middleCpp = replaceAll(moduleCppTmplete, '[body_replace]', result.middleBody); + middleCpp = replaceAll(middleCpp, '[init_replace]', result.middleInit); + middleCpp = replaceAll(middleCpp, '[implName]', ns0.name); + middleCpp = replaceAll(middleCpp, '[modulename]', moduleName); genFileList.splice(0, genFileList.length); writeFile(re.pathJoin(destDir, "%s_middle.cpp".format(ns0.name)), (null !== license && undefined !== license) ? (license + "\n" + middleCpp) : middleCpp); @@ -320,14 +320,14 @@ function generateMiddleCpp(result, ns0, moduleName, destDir, license) { // 将业务代码的头文件导入,若重复则跳过 function includeHCppFunc(jsonCfg, includeH, bindingCpp, buildCpp) {; for (let i = 0; i < jsonCfg.length; i++) { - if (jsonCfg[i].includeName !== "") { + if (jsonCfg[i].includeName !== '') { let includeNamePath = jsonCfg[i].includeName; let tmp = '#include "%s"\n'.format(includeNamePath); if (includeH.indexOf(tmp) < 0) { includeH += tmp; } } - if (jsonCfg[i].cppName !== "") { + if (jsonCfg[i].cppName !== '') { let cppNamePath = jsonCfg[i].cppName; let tmpCpp = '\n "%s",'.format(cppNamePath); let tmpBuildCpp = '\n "%s",'.format(cppNamePath); @@ -352,4 +352,4 @@ function generateMiddleH(ns0, result, destDir, license) { module.exports = { generateAll -} +}; \ No newline at end of file diff --git a/src/cli/dts2cpp/src/gen/generate/class.js b/src/cli/dts2cpp/src/gen/generate/class.js index 159a8585855bbb0492570a607d2b87523bc3ad19..60921f3481197ae93987b22355f3d0049d3e1d37 100644 --- a/src/cli/dts2cpp/src/gen/generate/class.js +++ b/src/cli/dts2cpp/src/gen/generate/class.js @@ -12,14 +12,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { generateFunctionDirect } = require("./function_direct"); -const { generateFunctionSync } = require("./function_sync"); -const { generateFunctionAsync } = require("./function_async"); -const { FuncType, InterfaceList, getArrayType } = require("../tools/common"); -const { jsToC } = require("./param_generate"); -const { cToJs } = require("./return_generate"); -const re = require("../tools/re"); -const { NapiLog } = require("../tools/NapiLog"); +const { generateFunctionDirect } = require('./function_direct'); +const { generateFunctionSync } = require('./function_sync'); +const { generateFunctionAsync } = require('./function_async'); +const { FuncType, InterfaceList, getArrayType } = require('../tools/common'); +const { jsToC } = require('./param_generate'); +const { cToJs } = require('./return_generate'); +const re = require('../tools/re'); +const { NapiLog } = require('../tools/NapiLog'); let middleBodyTmplete = ` class [className]_middle { @@ -38,21 +38,21 @@ public: delete p2; } [static_funcs] -};` +};`; function generateVariable(name, type, variable, className) { - if (type === "string") variable.hDefine += "\n std::string %s;".format(name) - else if (type.substring(0, 12) === "NUMBER_TYPE_") variable.hDefine += "\n %s %s;".format(type, name) - else if (InterfaceList.getValue(type)) variable.hDefine += "\n %s %s;".format(type, name) - else if (type.indexOf("Array<") === 0) { - let type2 = getArrayType(type) - if (type2 === "string") type2 = "std::string" - if (type2 === "boolean") type2 = "bool" - variable.hDefine += "\n std::vector<%s> %s;".format(type2, name) - } else if (type === "boolean") { - variable.hDefine += "\n bool %s;".format(name) - } else if (type.indexOf("[]") === 0) { - variable.hDefine += "\n std::vector<%s> %s;".format(type, name) + if (type == 'string') variable.hDefine += '\n std::string %s;'.format(name); + else if (type.substring(0, 12) == 'NUMBER_TYPE_') variable.hDefine += '\n %s %s;'.format(type, name); + else if (InterfaceList.getValue(type)) variable.hDefine += '\n %s %s;'.format(type, name); + else if (type.indexOf('Array<') == 0) { + let type2 = getArrayType(type); + if (type2 == 'string') type2 = 'std::string'; + if (type2 == 'boolean') type2 = 'bool'; + variable.hDefine += '\n std::vector<%s> %s;'.format(type2, name); + } else if (type == 'boolean') { + variable.hDefine += '\n bool %s;'.format(name); + } else if (type.indexOf('[]') == 0) { + variable.hDefine += '\n std::vector<%s> %s;'.format(type, name); } else NapiLog.logError(` @@ -65,7 +65,7 @@ function generateVariable(name, type, variable, className) { void *instPtr = pxt->UnWarpInstance(); %s *p = static_cast<%s *>(instPtr); napi_value result = nullptr; - `.format(name, className, className) + cToJs("p->" + name, type, "result") + ` + `.format(name, className, className) + cToJs('p->' + name, type, 'result') + ` delete pxt; return result; } @@ -74,113 +74,113 @@ function generateVariable(name, type, variable, className) { std::shared_ptr pxt = std::make_shared(env, info); void *instPtr = pxt->UnWarpInstance(); %s *p = static_cast<%s *>(instPtr); - `.format(name, className, className) + jsToC("p->" + name, "pxt->GetArgv(XNapiTool::ZERO)", type) + ` + `.format(name, className, className) + jsToC('p->' + name, 'pxt->GetArgv(XNapiTool::ZERO)', type) + ` return nullptr; } -` +`; } function generateClass(name, data, inNamespace, functiontType) { - let resultConnect = connectResult(data, inNamespace, name) - let middleFunc = resultConnect[0] - let implH = functiontType === "static" ? "\n" + "static " + - resultConnect[1].substring(1, resultConnect[1].length) : resultConnect[1] - let implCpp = resultConnect[2] - let middleInit = resultConnect[3] - let middleH = resultConnect[4] - let selfNs = "" + let resultConnect = connectResult(data, inNamespace, name); + let middleFunc = resultConnect[0]; + let implH = functiontType == 'static' ? '\n' + 'static ' + + resultConnect[1].substring(1, resultConnect[1].length) : resultConnect[1]; + let implCpp = resultConnect[2]; + let middleInit = resultConnect[3]; + let middleH = resultConnect[4]; + let selfNs = ''; if (inNamespace.length > 0) { - let nsl = inNamespace.split("::") - nsl.pop() + let nsl = inNamespace.split('::'); + nsl.pop(); if (nsl.length >= 2) { - selfNs = ", " + nsl[nsl.length - 1] + selfNs = ', ' + nsl[nsl.length - 1]; } } - let toolNamespace = getToolNamespace(inNamespace) + let toolNamespace = getToolNamespace(inNamespace); middleInit += `\n pxt->DefineClass("%s", %s%s%s_middle::constructor, valueList, funcList%s);\n}\n` - .format(name, inNamespace, toolNamespace, name, selfNs) + .format(name, inNamespace, toolNamespace, name, selfNs); let result = { implH: ` class %s { public:%s };`.format(name, implH), implCpp: implCpp, - middleBody: middleBodyTmplete.replaceAll("[className]", name).replaceAll("[static_funcs]", middleFunc), + middleBody: middleBodyTmplete.replaceAll('[className]', name).replaceAll('[static_funcs]', middleFunc), middleInit: middleInit, declarationH: ` class %s;\r`.format(name), middleH: middleH - } - return result + }; + return result; } function connectResult(data, inNamespace, name) { - let implH = "" - let implCpp = "" - let middleFunc = "" - let middleInit = "" - let middleH = "" + let implH = ''; + let implCpp = ''; + let middleFunc = ''; + let middleInit = ''; + let middleH = ''; let variable = { - hDefine: "", - middleValue: "", - } - let toolNamespace = getToolNamespace(inNamespace) - middleInit = `{\n std::map> valueList;` + hDefine: '', + middleValue: '', + }; + let toolNamespace = getToolNamespace(inNamespace); + middleInit = `{\n std::map> valueList;`; for (let i in data.value) { - let v = data.value[i] - generateVariable(v.name, v.type, variable, name) + let v = data.value[i]; + generateVariable(v.name, v.type, variable, name); middleInit += ` valueList["%s"]["getvalue"] = %s%s%s_middle::getvalue_%s; valueList["%s"]["setvalue"] = %s%s%s_middle::setvalue_%s;` - .format(v.name, inNamespace, toolNamespace, name, v.name, v.name, inNamespace, toolNamespace, name, v.name) + .format(v.name, inNamespace, toolNamespace, name, v.name, v.name, inNamespace, toolNamespace, name, v.name); } - implH += variable.hDefine - middleFunc += variable.middleValue - middleInit += `\n std::map funcList;` + implH += variable.hDefine; + middleFunc += variable.middleValue; + middleInit += `\n std::map funcList;`; for (let i in data.function) { - let func = data.function[i] + let func = data.function[i]; let tmp; switch (func.type) { case FuncType.DIRECT: - tmp = generateFunctionDirect(func, '', name) + tmp = generateFunctionDirect(func, '', name); break; case FuncType.SYNC: - tmp = generateFunctionSync(func, '', name) - break + tmp = generateFunctionSync(func, '', name); + break; case FuncType.ASYNC: case FuncType.PROMISE: - tmp = generateFunctionAsync(func, '', name) - break + tmp = generateFunctionAsync(func, '', name); + break; default: - return + return; } - middleFunc += tmp[0] - implH += tmp[1] - implCpp += tmp[2] - middleH += tmp[3] + middleFunc += tmp[0]; + implH += tmp[1]; + implCpp += tmp[2]; + middleH += tmp[3]; middleInit += `\n funcList["%s"] = %s%s%s_middle::%s_middle;` - .format(func.name, inNamespace, toolNamespace, name, func.name) + .format(func.name, inNamespace, toolNamespace, name, func.name); } - return [middleFunc, implH, implCpp, middleInit, middleH] + return [middleFunc, implH, implCpp, middleInit, middleH]; } function getToolNamespace(inNamespace) { - let index = inNamespace.lastIndexOf("::"); + let index = inNamespace.lastIndexOf('::'); let toolNamespace; if (index > 0) { - let bodyTmp = inNamespace.substring(0, index) - let index2 = bodyTmp.lastIndexOf('::') + let bodyTmp = inNamespace.substring(0, index); + let index2 = bodyTmp.lastIndexOf('::'); if (index2 > 0 && index2 < index) { - toolNamespace = inNamespace.substring(index2 + 2, index) + '_interface::' + toolNamespace = inNamespace.substring(index2 + 2, index) + '_interface::'; } else { - toolNamespace = bodyTmp + "_interface::"; + toolNamespace = bodyTmp + '_interface::'; } } else { - toolNamespace = inNamespace + "_interface::"; + toolNamespace = inNamespace + '_interface::'; } return toolNamespace; } module.exports = { generateClass -} \ No newline at end of file +}; \ No newline at end of file diff --git a/src/cli/dts2cpp/src/gen/generate/enum.js b/src/cli/dts2cpp/src/gen/generate/enum.js index 5a64aaa3e546cb03772bdded3d8f40a9f1fc1bc9..3b29cdd2d31445e4d667dd66505b3a91eaf3e31a 100644 --- a/src/cli/dts2cpp/src/gen/generate/enum.js +++ b/src/cli/dts2cpp/src/gen/generate/enum.js @@ -12,51 +12,51 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const re = require("../tools/re"); -const { EnumValueType, getLogErrInfo } = require("../tools/common"); -const { NapiLog } = require("../tools/NapiLog"); +const re = require('../tools/re'); +const { EnumValueType, getLogErrInfo } = require('../tools/common'); +const { NapiLog } = require('../tools/NapiLog'); function generateEnum(name, data, inNamespace, nameSpaceName, toolNamespace) { - let implH = "" - let implCpp = "" - let midInitEnum = "" - let midInitEnumDefine = "" + let implH = ''; + let implCpp = ''; + let midInitEnum = ''; + let midInitEnumDefine = ''; - if (data.enumValueType === EnumValueType.ENUM_VALUE_TYPE_STRING) { - implH = `\nclass %s {\npublic:\n`.format(name, implH) - } else if (data.enumValueType === EnumValueType.ENUM_VALUE_TYPE_NUMBER){ - implH = `\nenum class %s {\n`.format(name, implH) + if (data.enumValueType == EnumValueType.ENUM_VALUE_TYPE_STRING) { + implH = `\nclass %s {\npublic:\n`.format(name, implH); + } else if (data.enumValueType == EnumValueType.ENUM_VALUE_TYPE_NUMBER){ + implH = `\nenum class %s {\n`.format(name, implH); } else { NapiLog.logError(`The enum type[%s] is not support.`.format(data.enumValueType), getLogErrInfo()); - return {implH: "", implCpp: ""} + return {implH: '', implCpp: ''}; } for (let i in data.element) { - let v = data.element[i] - if(midInitEnumDefine === "") { - midInitEnumDefine += 'std::map enumMap%s;\n'.format(name) + let v = data.element[i]; + if(midInitEnumDefine == '') { + midInitEnumDefine += 'std::map enumMap%s;\n'.format(name); } - if (data.enumValueType === EnumValueType.ENUM_VALUE_TYPE_STRING) { - implH += ` static const std::string %s;\n`.format(v.name) - implCpp += `\nconst std::string %s::%s = "%s";\n`.format(name, v.name, v.value) - midInitEnum += ' %s%s::%senumMap%s["%s"] = "%s";\n'.format(inNamespace, nameSpaceName, toolNamespace, name, v.name, v.value) + if (data.enumValueType == EnumValueType.ENUM_VALUE_TYPE_STRING) { + implH += ` static const std::string %s;\n`.format(v.name); + implCpp += `\nconst std::string %s::%s = "%s";\n`.format(name, v.name, v.value); + midInitEnum += ' %s%s::%senumMap%s["%s"] = "%s";\n'.format(inNamespace, nameSpaceName, toolNamespace, name, v.name, v.value); } else { - if (v.value === '') { - v.value = 0 + if (v.value == '') { + v.value = 0; } - implH += ` %s = %s,\n`.format(v.name, v.value) - midInitEnum += ' %s%s::%senumMap%s["%s"] = %s;\n'.format(inNamespace, nameSpaceName, toolNamespace, name, v.name, v.value) + implH += ` %s = %s,\n`.format(v.name, v.value); + midInitEnum += ' %s%s::%senumMap%s["%s"] = %s;\n'.format(inNamespace, nameSpaceName, toolNamespace, name, v.name, v.value); } } - midInitEnum += ' pxt->CreateEnumObject("%s", %s%s::%senumMap%s);\n'.format(name, inNamespace, nameSpaceName, toolNamespace, name) - implH += `};\n` + midInitEnum += ' pxt->CreateEnumObject("%s", %s%s::%senumMap%s);\n'.format(name, inNamespace, nameSpaceName, toolNamespace, name); + implH += `};\n`; let result = { implH: implH, implCpp: implCpp, midInitEnum: midInitEnum, midInitEnumDefine: midInitEnumDefine - } - return result + }; + return result; } module.exports = { generateEnum -} \ No newline at end of file +}; \ No newline at end of file diff --git a/src/cli/dts2cpp/src/gen/generate/function_async.js b/src/cli/dts2cpp/src/gen/generate/function_async.js index 4235906a902c6c288158f91bdfe5c46babb350a4..0a76ce42154b879c26791527f47a59b89abc6e4a 100644 --- a/src/cli/dts2cpp/src/gen/generate/function_async.js +++ b/src/cli/dts2cpp/src/gen/generate/function_async.js @@ -12,10 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { replaceAll, getPrefix, getConstNum } = require("../tools/tool"); -const { paramGenerate } = require("./param_generate"); -const { returnGenerate } = require("./return_generate"); -const { jsonCfgList, InterfaceList }= require("../tools/common"); +const { replaceAll, getPrefix, getConstNum } = require('../tools/tool'); +const { paramGenerate } = require('./param_generate'); +const { returnGenerate } = require('./return_generate'); +const { jsonCfgList, InterfaceList }= require('../tools/common'); /** * 结果异步返回Async|Promise @@ -28,7 +28,7 @@ struct [funcName]_value_struct {[valueIn] [static_define]void [funcName]_execute(XNapiTool *pxt, DataPtr data); [static_define]void [funcName]_complete(XNapiTool *pxt, DataPtr data); [static_define]napi_value [funcName]_middle(napi_env env, napi_callback_info info); -` +`; let funcAsyncTemplete = ` void [middleClassName][funcName]_execute(XNapiTool *pxt, DataPtr data) @@ -69,7 +69,7 @@ napi_value [middleClassName][funcName]_middle(napi_env env, napi_callback_info i struct [funcName]_value_struct *vio = new [funcName]_value_struct(); [valueCheckout][optionalCallbackInit][start_async] return result; -}` +}`; let cppTemplate = ` bool %s%s(%s) @@ -77,7 +77,7 @@ bool %s%s(%s) %s[replace_valueOut] return true; } -` +`; let cppCbResultTemplate = ` [replace_outDefine] @@ -86,96 +86,96 @@ void %s%sSetCbValue(%s) %s return; } -` +`; function removeEndlineEnter(value) { for (var i = value.length; i > 0; i--) { - let len = value.length - if (value.substring(len - 1, len) === "\n" || value.substring(len - 1, len) === ' ') { - value = value.substring(0, len - 1) + let len = value.length; + if (value.substring(len - 1, len) == '\n' || value.substring(len - 1, len) == ' ') { + value = value.substring(0, len - 1); } else { - value = ' ' + value + "\n" - break + value = ' ' + value + '\n'; + break; } } - return value + return value; } function getOptionalCallbackInit(param) { if (!param.callback.optional) { - return "" + return ''; } - let cType = param.valueOut.substr(0, param.valueOut.indexOf("*")) - return "vio->out = new %s;".format(cType) + let cType = param.valueOut.substr(0, param.valueOut.indexOf('*')); + return 'vio->out = new %s;'.format(cType); } function replaceBasicInfo(middleFunc, middleH, className) { - if (className === null || className === undefined) { - middleH = middleH.replaceAll("[static_define]", "") - middleFunc = middleFunc.replaceAll("[unwarp_instance]", "") - middleFunc = middleFunc.replaceAll("[checkout_async_instance]", "") - middleFunc = middleFunc.replaceAll("[middleClassName]", "") + if (className == null) { + middleH = middleH.replaceAll('[static_define]', ''); + middleFunc = middleFunc.replaceAll('[unwarp_instance]', ''); + middleFunc = middleFunc.replaceAll('[checkout_async_instance]', ''); + middleFunc = middleFunc.replaceAll('[middleClassName]', ''); } else { - middleH = middleH.replaceAll("[static_define]", "static ") - middleFunc = middleFunc.replaceAll("[unwarp_instance]", - `pxt->SetAsyncInstance(pxt->UnWarpInstance());`) - middleFunc = middleFunc.replaceAll("[checkout_async_instance]", - "%s *pInstance = (%s *)pxt->GetAsyncInstance();".format(className, className)) - middleFunc = middleFunc.replaceAll("[middleClassName]", className + "_middle" + "::") + middleH = middleH.replaceAll('[static_define]', 'static '); + middleFunc = middleFunc.replaceAll('[unwarp_instance]', + `pxt->SetAsyncInstance(pxt->UnWarpInstance());`); + middleFunc = middleFunc.replaceAll('[checkout_async_instance]', + '%s *pInstance = (%s *)pxt->GetAsyncInstance();'.format(className, className)); + middleFunc = middleFunc.replaceAll('[middleClassName]', className + '_middle' + '::'); } - return [middleFunc, middleH] + return [middleFunc, middleH]; } function generateFunctionAsync(func, data, className, implHCbVariable) { - let middleFunc = replaceAll(funcAsyncTemplete, "[funcName]", func.name) - let middleH = "" - if (func.name !== "constructor") { - middleH = replaceAll(funcAsyncMiddleHTemplete, "[funcName]", func.name) + let middleFunc = replaceAll(funcAsyncTemplete, '[funcName]', func.name); + let middleH = ''; + if (func.name != 'constructor') { + middleH = replaceAll(funcAsyncMiddleHTemplete, '[funcName]', func.name); } - let basicInfoRes = replaceBasicInfo(middleFunc, middleH, className) - middleFunc = basicInfoRes[0] - middleH = basicInfoRes[1] + let basicInfoRes = replaceBasicInfo(middleFunc, middleH, className); + middleFunc = basicInfoRes[0]; + middleH = basicInfoRes[1]; // 定义输入,定义输出,解析,填充到函数内,输出参数打包,impl参数定义,可选参数内存释放 - let param = { valueIn: "", valueOut: "", valueCheckout: "", valueFill: "", - valuePackage: "", valueDefine: "", optionalParamDestory: "" } + let param = { valueIn: '', valueOut: '', valueCheckout: '', valueFill: '', + valuePackage: '', valueDefine: '', optionalParamDestory: '' }; for (let i in func.value) { - paramGenerate(i, func.value[i], param, data) + paramGenerate(i, func.value[i], param, data); } - returnGenerate(param.callback, param, data) + returnGenerate(param.callback, param, data); middleH = replaceValueOut(middleH, param); middleFunc = getMiddleFunc(param, middleFunc); - middleFunc = replaceAll(middleFunc, "[start_async]", ` + middleFunc = replaceAll(middleFunc, '[start_async]', ` napi_value result = pxt->StartAsync(%s_execute, reinterpret_cast(vio), %s_complete, pxt->GetArgc() == %s? pxt->GetArgv(%d) : nullptr);` .format(func.name, func.name, getConstNum(parseInt(param.callback.offset) + 1), getConstNum(param.callback.offset))) // 注册异步调用 let callFunc = "%s%s(%s);".format((className === null || className === undefined) ? "" : "pInstance->", func.name, param.valueFill) - middleFunc = replaceAll(middleFunc, "[callFunc]", callFunc) // 执行 - middleFunc = replaceAll(middleFunc, "[valuePackage]", param.valuePackage) // 输出参数打包 - middleFunc = replaceAll(middleFunc, "[optionalParamDestory]", param.optionalParamDestory) // 可选参数内存释放 + middleFunc = replaceAll(middleFunc, "[callFunc]", callFunc); // 执行 + middleFunc = replaceAll(middleFunc, "[valuePackage]", param.valuePackage); // 输出参数打包 + middleFunc = replaceAll(middleFunc, "[optionalParamDestory]", param.optionalParamDestory); // 可选参数内存释放 - let prefixArr = getPrefix(data, func) - let implH = "" - let implCpp = "" + let prefixArr = getPrefix(data, func); + let implH = ""; + let implCpp = ""; if (!func.isParentMember) { // 只有类/接口自己的成员方法需要在.h.cpp中生成,父类/父接口不需要 implH = "\n%s%s%sbool %s(%s)%s;".format( - prefixArr[0], prefixArr[1], prefixArr[2], func.name, param.valueDefine, prefixArr[3]) + prefixArr[0], prefixArr[1], prefixArr[2], func.name, param.valueDefine, prefixArr[3]); let callStatement = jsonCfgList.getValue((className === null || className === undefined)? "": className, func.name); implCpp = cppTemplate.format((className === null || className === undefined) ? "" : className + "::", func.name, param.valueDefine, - (callStatement === null || callStatement === undefined)? "": callStatement) + (callStatement === null || callStatement === undefined)? "": callStatement); - let outResult = generateCbInterfaceOutFunc(param, className, prefixArr, implHCbVariable, implCpp, implH) - implCpp = outResult[0] - implH = outResult[1] + let outResult = generateCbInterfaceOutFunc(param, className, prefixArr, implHCbVariable, implCpp, implH); + implCpp = outResult[0]; + implH = outResult[1]; } - return [middleFunc, implH, implCpp, middleH] + return [middleFunc, implH, implCpp, middleH]; } function getMiddleFunc(param, middleFunc) { @@ -195,8 +195,8 @@ function getMiddleFunc(param, middleFunc) { } function generateCbInterfaceOutFunc(param, className, prefixArr, implHCbVariable, implCpp, implH) { - let cbInterfaceRes = ""; - let outInterfaceDefine = param.valueDefine.substring(param.valueDefine.lastIndexOf(",") + 1, + let cbInterfaceRes = ''; + let outInterfaceDefine = param.valueDefine.substring(param.valueDefine.lastIndexOf(',') + 1, param.valueDefine.length); outInterfaceDefine = replaceAll(outInterfaceDefine, ' ', ''); let index = outInterfaceDefine.indexOf('&'); @@ -223,24 +223,24 @@ function generateCbInterfaceOutFunc(param, className, prefixArr, implHCbVariable if (className !== null && className !== undefined) { cbInterfaceRes = replaceAll(cbInterfaceRes, '[replace_outDefine]', cbOutDefine) } else { - cbInterfaceRes = replaceAll(cbInterfaceRes, '[replace_outDefine]', '') + cbInterfaceRes = replaceAll(cbInterfaceRes, '[replace_outDefine]', ''); } // 多次使用interface(非匿名)作为Promise回调只需生成一次cbResult接口 - let outResDefine = "\n%s%s%sstatic %s %sOutRes;".format( + let outResDefine = '\n%s%s%sstatic %s %sOutRes;'.format( prefixArr[0], prefixArr[1], prefixArr[2], outInterfaceName, outInterfaceName.toLocaleLowerCase()); let replaceOut = "\n out = %s%sOutRes;".format((className === null || className === undefined) ? "" : className + "::", outInterfaceName.toLocaleLowerCase()); - implCpp = replaceAll(implCpp, "[replace_valueOut]", replaceOut); + implCpp = replaceAll(implCpp, '[replace_valueOut]', replaceOut); if (implHCbVariable.indexOf(outResDefine) < 0) { implH += outResDefine; - implH += "\n%s%s%svoid %sSetCbValue(%s);".format( + implH += '\n%s%s%svoid %sSetCbValue(%s);'.format( prefixArr[0], prefixArr[1], prefixArr[2], outInterfaceName.toLocaleLowerCase(), defineParams); implCpp += cbInterfaceRes; } } else { - implCpp = replaceAll(implCpp, "[replace_valueOut]", ''); + implCpp = replaceAll(implCpp, '[replace_valueOut]', ''); } return [implCpp, implH]; } @@ -250,11 +250,11 @@ function replaceValueOut(middleH, param) { if (param.valueOut === "") { middleH = replaceAll(middleH, "[valueOut]", param.valueOut); // # 输出参数定义 } else { - middleH = replaceAll(middleH, "[valueOut]", "\n " + param.valueOut); // # 输出参数定义 + middleH = replaceAll(middleH, '[valueOut]', '\n ' + param.valueOut); // # 输出参数定义 } return middleH; } module.exports = { generateFunctionAsync -} \ No newline at end of file +}; \ No newline at end of file