From 1b36019a8312c73b4a12e80ec3db1fab8c430636 Mon Sep 17 00:00:00 2001 From: LiYuxi Date: Thu, 11 Jul 2024 10:21:07 +0800 Subject: [PATCH 01/12] modify return_generate.js Signed-off-by: LiYuxi --- .../src/gen/generate/return_generate.js | 822 +++++++++--------- 1 file changed, 413 insertions(+), 409 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/generate/return_generate.js b/src/cli/dts2cpp/src/gen/generate/return_generate.js index 7053f287..b94045b3 100644 --- a/src/cli/dts2cpp/src/gen/generate/return_generate.js +++ b/src/cli/dts2cpp/src/gen/generate/return_generate.js @@ -12,14 +12,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { isMappedTypeNode } = require("typescript"); +const { isMappedTypeNode } = require('typescript'); const { InterfaceList, getArrayType, NumberIncrease, enumIndex, isEnum, EnumValueType, getArrayTypeTwo, getMapType, EnumList, - jsType2CType, getUnionType, TypeList, isArrowFunc, getLogErrInfo } = require("../tools/common"); -const { NapiLog } = require("../tools/NapiLog"); -const { print } = require("../tools/tool"); + jsType2CType, getUnionType, TypeList, isArrowFunc, getLogErrInfo } = require('../tools/common'); +const { NapiLog } = require('../tools/NapiLog'); +const { print } = require('../tools/tool'); -const specialPrefixArr = ["p->", "vio->out."]; +const specialPrefixArr = ['p->', 'vio->out.']; /** * Get the real value name by deleting prefix like "p->", "vio->out.", e.g. @@ -27,7 +27,7 @@ const specialPrefixArr = ["p->", "vio->out."]; * @returns the real value without prefix, example: xxx, yyy */ function delPrefix(valueName) { - for ( var i in specialPrefixArr) { + for (var i in specialPrefixArr) { if (valueName.indexOf(specialPrefixArr[i]) === 0) { // Find special prefix and delete it. return valueName.substring(specialPrefixArr[i].length, valueName.length); @@ -38,84 +38,84 @@ function delPrefix(valueName) { } function cToJsForType(value, type, dest, deep) { - let lt = deep - let result = "" - let ifl = TypeList.getValue(type) - if (typeof(ifl) === 'object') { - for (let i in ifl) { - let name2 = ifl[i].name - let type2 = ifl[i].type - let optional2 = ifl[i].optional - let isSubEnum = EnumList.getValue(type2) ? true : false; - let subDest = isSubEnum ? dest : "tnv%d".format(lt) - let typeType = null - let ifOptional = '' // 如果是可选参数则需要增加可选参数是否有值的判断 - if (optional2) { - ifOptional = 'if (%s.%s.has_value())\n'.format(value, name2) - typeType = cToJs("%s.%s".format(value, "%s.value()".format(name2)), type2, subDest, deep + 1) - } else { - typeType = cToJs("%s.%s".format(value, name2), type2, subDest, deep + 1) - } - if (isSubEnum) { - result += typeType - } else { - result += "%s{\nnapi_value tnv%d = nullptr;\n".format(ifOptional, lt) + - typeType + `\npxt->SetValueProperty(%s, "%s", tnv%d);\n}\n` - .format(dest, name2, lt) - } - } - } else { - result += cToJs(value, ifl, dest, deep) - } - return result + let lt = deep; + let result = ''; + let ifl = TypeList.getValue(type) + if (typeof (ifl) === 'object') { + for (let i in ifl) { + let name2 = ifl[i].name; + let type2 = ifl[i].type; + let optional2 = ifl[i].optional; + let isSubEnum = EnumList.getValue(type2) ? true : false; + let subDest = isSubEnum ? dest : 'tnv%d'.format(lt); + let typeType = null; + let ifOptional = ''; // 如果是可选参数则需要增加可选参数是否有值的判断 + if (optional2) { + ifOptional = 'if (%s.%s.has_value())\n'.format(value, name2); + typeType = cToJs('%s.%s'.format(value, '%s.value()'.format(name2)), type2, subDest, deep + 1); + } else { + typeType = cToJs('%s.%s'.format(value, name2), type2, subDest, deep + 1); + } + if (isSubEnum) { + result += typeType + } else { + result += '%s{\nnapi_value tnv%d = nullptr;\n'.format(ifOptional, lt) + + typeType + `\npxt->SetValueProperty(%s, "%s", tnv%d);\n}\n` + .format(dest, name2, lt); + } + } + } else { + result += cToJs(value, ifl, dest, deep); + } + return result; } function cToJsForInterface(value, type, dest, deep) { let lt = deep; - let result = ""; - let ifl = InterfaceList.getValue(type) + let result = ''; + let ifl = InterfaceList.getValue(type); for (let i in ifl) { - let name2 = ifl[i].name - let type2 = ifl[i].type - let optional2 = ifl[i].optional + let name2 = ifl[i].name; + let type2 = ifl[i].type; + let optional2 = ifl[i].optional; let isSubEnum = EnumList.getValue(type2) ? true : false; - let subDest = isSubEnum ? dest : "tnv%d".format(lt) + let subDest = isSubEnum ? dest : 'tnv%d'.format(lt); let interfaceType = null; - let ifOptional = '' + let ifOptional = ''; if (optional2) { - ifOptional = 'if (%s.%s.has_value())\n'.format(value, name2) - interfaceType = cToJs("%s.%s".format(value, "%s.value()".format(name2)), type2, subDest, deep + 1) + ifOptional = 'if (%s.%s.has_value())\n'.format(value, name2); + interfaceType = cToJs('%s.%s'.format(value, '%s.value()'.format(name2)), type2, subDest, deep + 1); } else { - interfaceType = cToJs("%s.%s".format(value, name2), type2, subDest, deep + 1) + interfaceType = cToJs('%s.%s'.format(value, name2), type2, subDest, deep + 1); } - + if (isSubEnum) { // interface include enum properties - result += interfaceType + result += interfaceType } else { - result += "%s{\nnapi_value tnv%d = nullptr;\n".format(ifOptional, lt) + - interfaceType + `\npxt->SetValueProperty(%s, "%s", tnv%d);\n}\n` - .format(dest, name2, lt) + result += '%s{\nnapi_value tnv%d = nullptr;\n'.format(ifOptional, lt) + + interfaceType + `\npxt->SetValueProperty(%s, "%s", tnv%d);\n}\n` + .format(dest, name2, lt); } } - return result + return result; } function c2JsForEnum(deep, type, value, dest, propertyName) { - let lt = deep - let result = "" - let ifl = EnumList.getValue(type) - let type2 = "" + let lt = deep; + let result = ''; + let ifl = EnumList.getValue(type); + let type2 = ''; if (ifl && ifl.length > 0) { - type2 = ifl[0].type + type2 = ifl[0].type; } - let enumCtoJsStr = cToJs("enumC2Js%d".format(lt), type2, dest, deep) + let enumCtoJsStr = cToJs('enumC2Js%d'.format(lt), type2, dest, deep); if (type2 === 'string') { - // string型枚举的getvalue函数 - result += "{\nstd::string enumC2Js%d = %s;\n".format(lt, value) + enumCtoJsStr + "}\n" + // string型枚举的getvalue函数 + result += '{\nstd::string enumC2Js%d = %s;\n'.format(lt, value) + enumCtoJsStr + '}\n'; } else { - // number型枚举的getvalue函数 - result += ` + // number型枚举的getvalue函数 + result += ` std::underlying_type<%s>::type enumType; if (typeid(enumType) == typeid(uint32_t)) { uint32_t enumC2Js%d = static_cast(%s); @@ -130,53 +130,56 @@ function c2JsForEnum(deep, type, value, dest, propertyName) { double_t enumC2Js%d = static_cast(%s); %s }`.format(type, lt, value, enumCtoJsStr, lt, value, enumCtoJsStr, lt, value, enumCtoJsStr, - lt, value, enumCtoJsStr,) + lt, value, enumCtoJsStr,); } - return result + return result; } function cToJs(value, type, dest, deep = 1, optional, enumType = 0) { var propertyName = delPrefix(value); if (checkRetIsUndefined(type)) { - NapiLog.logError("type is invalid!") - return + NapiLog.logError('type is invalid!'); + return; } - if (type.indexOf("|") >= 0) { + if (type.indexOf('|') >= 0) { return unionTempleteFunc(value, type, dest, optional); - } else if (type === "void") - return "%s = pxt->UndefinedValue();\n".format(dest); - else if (type === "boolean") - return "%s = pxt->SwapC2JsBool(%s);\n".format(dest, value.replace("[replace]", deep - 2)); - else if (type === "string") - return `%s = pxt->SwapC2JsUtf8(%s.c_str());\n`.format(dest, value.replace("[replace]", deep - 2)) + } else if (type === 'void') { + return '%s = pxt->UndefinedValue();\n'.format(dest); + } + else if (type === 'boolean') { + return '%s = pxt->SwapC2JsBool(%s);\n'.format(dest, value.replace('[replace]', deep - 2)); + } + else if (type === 'string') { + return `%s = pxt->SwapC2JsUtf8(%s.c_str());\n`.format(dest, value.replace('[replace]', deep - 2)); + } else if (InterfaceList.getValue(type)) { return cToJsForInterface(value, type, dest, deep); } else if (TypeList.getValue(type)) { return cToJsForType(value, type, dest, deep); } - else if(EnumList.getValue(type)){ + else if (EnumList.getValue(type)) { return c2JsForEnum(deep, type, value, dest, propertyName); } else if (checkRetIsArray(type)) { - let arrayType = checkArrayParamType(type) - return arrayTempleteFunc(arrayType, deep, dest, value) + let arrayType = checkArrayParamType(type); + return arrayTempleteFunc(arrayType, deep, dest, value); } else if (checkRetIsMap(type)) { - return mapTempleteFunc(type, deep, dest, value) + return mapTempleteFunc(type, deep, dest, value); } - else if (type.substring(0, 12) === "NUMBER_TYPE_") { + else if (type.substring(0, 12) === 'NUMBER_TYPE_') { if (enumType) { return c2JsForRetEnum(enumType, value, deep, dest); } else { - return `%s = NUMBER_C_2_JS(pxt, %s);\n`.format(dest, value.replace("[replace]", deep - 2)) - } - } - else if (type === "any") { - return anyTempleteFunc(value) + return `%s = NUMBER_C_2_JS(pxt, %s);\n`.format(dest, value.replace('[replace]', deep - 2)); + } + } + else if (type === 'any') { + return anyTempleteFunc(value); } - else if (checkRetIsObject(type)) { - return objectTempleteFuncReturn(value) + else if (checkRetIsObject(type)) { + return objectTempleteFuncReturn(value); } else { NapiLog.logError(`\n---- This type do not generate cToJs %s,%s,%s ----\n. ` @@ -185,19 +188,19 @@ function cToJs(value, type, dest, deep = 1, optional, enumType = 0) { } function checkRetIsUndefined(type) { - return type === null || type === undefined; + return type === null || type === undefined; } function checkRetIsObject(type) { - return type === 'Object' || type === 'object'; + return type === 'Object' || type === 'object'; } function checkRetIsArray(type) { - return type.substring(0, 6) === 'Array<' || type.substring(type.length - 2) === '[]'; + return type.substring(0, 6) === 'Array<' || type.substring(type.length - 2) === '[]'; } function checkRetIsMap(type) { - return type.substring(0, 4) === 'Map<' || type.indexOf('{[key:') === 0; + return type.substring(0, 4) === 'Map<' || type.indexOf('{[key:') === 0; } function c2JsForRetEnum(enumType, value, deep, dest) { @@ -217,319 +220,320 @@ function c2JsForRetEnum(enumType, value, deep, dest) { } else { napi_throw_error(env, nullptr, "enum return value is wrong!"); return nullptr; - }`.format(enumType, value.replace("[replace]", deep - 2), dest, value.replace("[replace]", deep - 2), dest, - value.replace("[replace]", deep - 2), dest, value.replace("[replace]", deep - 2), dest); + }`.format(enumType, value.replace('[replace]', deep - 2), dest, value.replace('[replace]', deep - 2), dest, + value.replace('[replace]', deep - 2), dest, value.replace('[replace]', deep - 2), dest); return retEnum; } function objectTempleteFuncReturn(value) { let objectTemplete = `pxt->GetObjectValue(result, %s);` - .format(value) - return objectTemplete + .format(value); + return objectTemplete; } -function unionTempleteFunc(value, type, dest, optional){ - let unionType = getUnionType(type) - let unionTypeString = '' - let typeStr = 'type' - let valueTmp = value + '.value()' +function unionTempleteFunc(value, type, dest, optional) { + let unionType = getUnionType(type); + let unionTypeString = ''; + let typeStr = 'type'; + let valueTmp = value + '.value()'; if (optional) { - typeStr = 'type.value()' + typeStr = 'type.value()'; } - let value2 = optional? valueTmp: value + let value2 = optional ? valueTmp : value; for (let i = 0; i < unionType.length; i++) { - if (unionType[i] === "string") { + if (unionType[i] === 'string') { unionTypeString += `if (%s_%s == "string") { %s %s - }\n`.format(value, typeStr, "std::string union_string = std::any_cast("+value2+");", - cToJs("union_string", unionType[i], dest)) - } else if (unionType[i].substring(0, 12) === "NUMBER_TYPE_") { + }\n`.format(value, typeStr, 'std::string union_string = std::any_cast(' + value2 + ');', + cToJs('union_string', unionType[i], dest)); + } else if (unionType[i].substring(0, 12) === 'NUMBER_TYPE_') { unionTypeString += `if (%s_%s == "number") { %s %s - }\n`.format(value, typeStr, "std::uint32_t union_number = std::any_cast("+value2+");", - cToJs("union_number", unionType[i], dest)) - } else if (unionType[i] === "boolean") { + }\n`.format(value, typeStr, 'std::uint32_t union_number = std::any_cast(' + value2 + ');', + cToJs('union_number', unionType[i], dest)); + } else if (unionType[i] === 'boolean') { unionTypeString += `if (%s_%s == "boolean") { %s %s - }\n`.format(value, typeStr, "bool union_boolean = std::any_cast("+value2+");", - cToJs("union_boolean", unionType[i], dest)) + }\n`.format(value, typeStr, 'bool union_boolean = std::any_cast(' + value2 + ');', + cToJs('union_boolean', unionType[i], dest)); } } if (optional) { let result = - `if (%s.has_value()) { + `if (%s.has_value()) { %s - }\n`.format(value, unionTypeString) - return result + }\n`.format(value, unionTypeString); + return result; } else { - return unionTypeString + return unionTypeString; } } function checkArrayParamType(type) { - let arrayType - if (type.substring(type.length - 2) === "[]") { - arrayType = getArrayTypeTwo(type) + let arrayType; + if (type.substring(type.length - 2) === '[]') { + arrayType = getArrayTypeTwo(type); } else { - arrayType = getArrayType(type) + arrayType = getArrayType(type); } - return arrayType + return arrayType; } function arrayTempleteFunc(arrayType, deep, dest, value) { - let lt = deep - let tnv = dest + let lt = deep; + let tnv = dest; let tnvdef = `pxt->CreateArray(%s); uint32_t outLen%d = %s.size(); for (uint32_t i%d = 0; i%d < outLen%d; i%d++) { napi_value tnv%d = nullptr; [calc_out] pxt->SetArrayElement(%s, i%d, tnv%d); - }`.format(tnv, lt, value.replace("[replace]",lt -2), lt, lt, lt, lt, lt, tnv, lt, lt) - let ret = "" - if (arrayType.substring(0, 12) === "NUMBER_TYPE_") { - ret = tnvdef.replaceAll("[calc_out]", `tnv%d = NUMBER_C_2_JS(pxt, %s[i%d]);` - .format(lt, value.replace("[replace]",lt), lt)) + }`.format(tnv, lt, value.replace('[replace]', lt - 2), lt, lt, lt, lt, lt, tnv, lt, lt); + let ret = ''; + if (arrayType.substring(0, 12) === 'NUMBER_TYPE_') { + ret = tnvdef.replaceAll('[calc_out]', `tnv%d = NUMBER_C_2_JS(pxt, %s[i%d]);` + .format(lt, value.replace('[replace]', lt), lt)); } - else if (arrayType === "string") { - ret = tnvdef.replaceAll("[calc_out]", `tnv%d = pxt->SwapC2JsUtf8(%s[i%d].c_str());` - .format(lt, value.replace("[replace]",lt), lt)) + else if (arrayType === 'string') { + ret = tnvdef.replaceAll('[calc_out]', `tnv%d = pxt->SwapC2JsUtf8(%s[i%d].c_str());` + .format(lt, value.replace('[replace]', lt), lt)); } - else if (arrayType === "boolean") { - ret = tnvdef.replaceAll("[calc_out]", `tnv%d = pxt->SwapC2JsBool(%s[i%d]);` - .format(lt, value.replace("[replace]",lt), lt)) + else if (arrayType === 'boolean') { + ret = tnvdef.replaceAll('[calc_out]', `tnv%d = pxt->SwapC2JsBool(%s[i%d]);` + .format(lt, value.replace('[replace]', lt), lt)); } - else if (arrayType === "any") { - return anyArrayTempleteFuncReturn(value.replace("[replace]",lt)) + else if (arrayType === 'any') { + return anyArrayTempleteFuncReturn(value.replace('[replace]', lt)); } else if (InterfaceList.getValue(arrayType)) { - ret = tnvdef.replaceAll("[calc_out]", cToJs(value + "[i[replace]]", arrayType, "tnv" + lt, deep + 1)) + ret = tnvdef.replaceAll('[calc_out]', cToJs(value + '[i[replace]]', arrayType, 'tnv' + lt, deep + 1)); } - return ret + return ret; } function mapTempleteFunc(type, deep, dest, value) { - let mapType = getMapType(type) - let lt = deep - let tnv = dest + let mapType = getMapType(type); + let lt = deep; + let tnv = dest; let tnvdef = `result = nullptr; for (auto i = %s.begin(); i != %s.end(); i++) { const char * tnv%d; napi_value tnv%d = nullptr; [calc_out] pxt->SetMapElement(%s, tnv%d, tnv%d); - }`.format(value, value, lt, lt + 1, tnv, lt, lt + 1) - let ret = "" + }`.format(value, value, lt, lt + 1, tnv, lt, lt + 1); + let ret = ''; if (mapType[1] !== undefined && mapType[2] === undefined) { - ret = mapTempleteValue(mapType, tnvdef, lt, value, tnv) + ret = mapTempleteValue(mapType, tnvdef, lt, value, tnv); } else if (mapType[2] !== undefined) { - ret = mapTempleteMap(mapType, tnvdef, lt) + ret = mapTempleteMap(mapType, tnvdef, lt); } else if (mapType[3] !== undefined) { - ret = mapTempleteArray(mapType, tnvdef, lt) + ret = mapTempleteArray(mapType, tnvdef, lt); } - return ret + return ret; } function anyTempleteFunc(value) { let anyTemplete = `pxt->GetAnyValue(%s_type, result, %s);` - .format(value, value) - - return anyTemplete + .format(value, value); + + return anyTemplete; } function anyArrayTempleteFuncReturn(value) { let anyTemplete = `pxt->GetAnyValue(%s_type, result, %s);` - .format(value, value) - - return anyTemplete + .format(value, value); + + return anyTemplete; } function mapInterface(value, lt, tnv, mapType) { - let ret + let ret; let tnvdefInterface = `result = nullptr; for (auto i = %s.begin(); i != %s.end(); i++) { const char *tnv%d; [calc_out] - }`.format(value, value, lt, lt + 1, tnv, lt, lt + 1) - let interfaceValue = InterfaceList.getValue(mapType[1]) - let interfaceVarName = "" - let interfaceVar = "" - let interfaceFun = "" + }`.format(value, value, lt, lt + 1, tnv, lt, lt + 1); + let interfaceValue = InterfaceList.getValue(mapType[1]); + let interfaceVarName = ''; + let interfaceVar = ''; + let interfaceFun = ''; for (let i = 0; i < interfaceValue.length; i++) { if (interfaceValue[i].type === 'string') { interfaceVarName += `const char *tnv_%s_name; - napi_value tnv_%s = nullptr;\n`.format(interfaceValue[i].name, interfaceValue[i].name) + napi_value tnv_%s = nullptr;\n`.format(interfaceValue[i].name, interfaceValue[i].name); interfaceVar += `tnv_%s_name = "%s"; tnv_%s = pxt->SwapC2JsUtf8(i->second.%s.c_str());\n` - .format(interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name) + .format(interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name); interfaceFun += `pxt->SetMapElement(result_obj, tnv_%s_name, tnv_%s);\n` - .format(interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name) + .format(interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name); } - else if (interfaceValue[i].type.substring(0, 12) === "NUMBER_TYPE_") { + else if (interfaceValue[i].type.substring(0, 12) === 'NUMBER_TYPE_') { interfaceVarName += `const char *tnv_%s_name; - napi_value tnv_%s = nullptr;\n`.format(interfaceValue[i].name, interfaceValue[i].name) + napi_value tnv_%s = nullptr;\n`.format(interfaceValue[i].name, interfaceValue[i].name); interfaceVar += `tnv_%s_name = "%s"; tnv_%s = NUMBER_C_2_JS(pxt, i->second.%s);\n` - .format(interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name) + .format(interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name); interfaceFun += `pxt->SetMapElement(result_obj, tnv_%s_name, tnv_%s);\n` - .format(interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name) + .format(interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name); } else if (interfaceValue[i].type === 'boolean') { interfaceVarName += `const char *tnv_%s_name; - napi_value tnv_%s = nullptr;\n`.format(interfaceValue[i].name, interfaceValue[i].name) + napi_value tnv_%s = nullptr;\n`.format(interfaceValue[i].name, interfaceValue[i].name); interfaceVar += `tnv_%s_name = "%s"; tnv_%s = pxt->SwapC2JsBool(i->second.%s);\n` - .format(interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name) + .format(interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name); interfaceFun += `pxt->SetMapElement(result_obj, tnv_%s_name, tnv_%s);\n` - .format(interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name) + .format(interfaceValue[i].name, interfaceValue[i].name, interfaceValue[i].name); } } - ret = tnvdefInterface.replaceAll("[calc_out]", `tnv%d = (i -> first).c_str(); + ret = tnvdefInterface.replaceAll('[calc_out]', `tnv%d = (i -> first).c_str(); napi_value result_obj = nullptr; %s %s %s pxt->SetMapElement(result, tnv%d, result_obj);` - .format(lt, interfaceVarName, interfaceVar, interfaceFun, lt)) - return ret + .format(lt, interfaceVarName, interfaceVar, interfaceFun, lt)); + return ret; } function mapTempleteValue(mapType, tnvdef, lt, value, tnv) { - let ret - if (mapType[1] === "string") { - ret = tnvdef.replaceAll("[calc_out]", `tnv%d = (i -> first).c_str(); - tnv%d = pxt->SwapC2JsUtf8(i->second.c_str());`.format(lt, lt + 1)) - } else if (mapType[1] === "boolean") { - ret = tnvdef.replaceAll("[calc_out]", `tnv%d = (i -> first).c_str(); - tnv%d = pxt->SwapC2JsBool(i->second);`.format(lt, lt + 1)) - } else if (mapType[1].substring(0, 12) === "NUMBER_TYPE_") { - ret = tnvdef.replaceAll("[calc_out]", `tnv%d = (i -> first).c_str(); - tnv%d = NUMBER_C_2_JS(pxt, i->second);`.format(lt, lt + 1)) - } else if (mapType[1] === "any") { - ret = tnvdef.replaceAll("[calc_out]", `tnv%d = (i -> first).c_str(); - pxt->GetAnyValue(%s_type, tnv%d, i->second);`.format(lt, value, lt + 1)) + let ret; + if (mapType[1] === 'string') { + ret = tnvdef.replaceAll('[calc_out]', `tnv%d = (i -> first).c_str(); + tnv%d = pxt->SwapC2JsUtf8(i->second.c_str());`.format(lt, lt + 1)); + } else if (mapType[1] === 'boolean') { + ret = tnvdef.replaceAll('[calc_out]', `tnv%d = (i -> first).c_str(); + tnv%d = pxt->SwapC2JsBool(i->second);`.format(lt, lt + 1)); + } else if (mapType[1].substring(0, 12) === 'NUMBER_TYPE_') { + ret = tnvdef.replaceAll('[calc_out]', `tnv%d = (i -> first).c_str(); + tnv%d = NUMBER_C_2_JS(pxt, i->second);`.format(lt, lt + 1)); + } else if (mapType[1] === 'any') { + ret = tnvdef.replaceAll('[calc_out]', `tnv%d = (i -> first).c_str(); + pxt->GetAnyValue(%s_type, tnv%d, i->second);`.format(lt, value, lt + 1)); } else if (InterfaceList.getValue(mapType[1])) { - ret = mapInterface(value, lt, tnv, mapType) + ret = mapInterface(value, lt, tnv, mapType); } - else + else { NapiLog.logError(`This type do not generate cToJs %s,%s,%s` .format(value, type, dest), getLogErrInfo()); - return ret + } + return ret; } function mapTempleteMap(mapType, tnvdef, lt) { - let ret - if (mapType[2] === "string") { - ret = tnvdef.replaceAll("[calc_out]", `tnv%d = i->first.c_str(); + let ret; + if (mapType[2] === 'string') { + ret = tnvdef.replaceAll('[calc_out]', `tnv%d = i->first.c_str(); for (auto j = i->second.begin(); j != i->second.end(); j++) { const char *tt%d; napi_value tt%d; tt%d = j->first.c_str(); tt%d = pxt->SwapC2JsUtf8(j->second.c_str()); pxt->SetMapElement(tnv%d, tt%d, tt%d); - }`.format(lt, lt + 2, lt + 3, lt + 2, lt + 3, lt + 1, lt + 2, lt + 3)) + }`.format(lt, lt + 2, lt + 3, lt + 2, lt + 3, lt + 1, lt + 2, lt + 3)); } - else if (mapType[2] === "boolean") { - ret = tnvdef.replaceAll("[calc_out]", `tnv%d = i->first.c_str(); + else if (mapType[2] === 'boolean') { + ret = tnvdef.replaceAll('[calc_out]', `tnv%d = i->first.c_str(); for (auto j = i->second.begin(); j != i->second.end(); j++) { const char *tt%d; napi_value tt%d; tt%d = j->first.c_str(); tt%d = pxt->SwapC2JsBool(j->second); pxt->SetMapElement(tnv%d, tt%d, tt%d); - }`.format(lt, lt + 2, lt + 3, lt + 2, lt + 3, lt + 1, lt + 2, lt + 3)) + }`.format(lt, lt + 2, lt + 3, lt + 2, lt + 3, lt + 1, lt + 2, lt + 3)); } - if (mapType[2].substring(0, 12) === "NUMBER_TYPE_") { - ret = tnvdef.replaceAll("[calc_out]", `tnv%d = i->first.c_str(); + if (mapType[2].substring(0, 12) === 'NUMBER_TYPE_') { + ret = tnvdef.replaceAll('[calc_out]', `tnv%d = i->first.c_str(); for (auto j = i->second.begin(); j != i->second.end(); j++) { const char *tt%d; napi_value tt%d; tt%d = j->first.c_str(); tt%d = NUMBER_C_2_JS(pxt, j->second); pxt->SetMapElement(tnv%d, tt%d, tt%d); - }`.format(lt, lt + 2, lt + 3, lt + 2, lt + 3, lt + 1, lt + 2, lt + 3)) + }`.format(lt, lt + 2, lt + 3, lt + 2, lt + 3, lt + 1, lt + 2, lt + 3)); } - return ret + return ret; } function mapTempleteArray(mapType, tnvdef, lt) { - let ret - if (mapType[3] === "string") { - ret = tnvdef.replaceAll("[calc_out]", `napi_value tnv%d = nullptr; + let ret; + if (mapType[3] === 'string') { + ret = tnvdef.replaceAll('[calc_out]', `napi_value tnv%d = nullptr; pxt->CreateArray(tnv%d); tnv%d = (i -> first).c_str(); uint32_t len%d = i->second.size(); for (uint32_t j = 0; j < len%d; j++) { tnv%d = pxt->SwapC2JsUtf8(i->second[j].c_str()); pxt->SetArrayElement(tnv%d, j, tnv%d); - }`.format(lt + 2, lt + 2, lt, lt, lt, lt + 2, lt + 1, lt + 2)) - } else if (mapType[3] === "boolean") { - ret = tnvdef.replaceAll("[calc_out]", `napi_value tnv%d = nullptr; + }`.format(lt + 2, lt + 2, lt, lt, lt, lt + 2, lt + 1, lt + 2)); + } else if (mapType[3] === 'boolean') { + ret = tnvdef.replaceAll('[calc_out]', `napi_value tnv%d = nullptr; pxt->CreateArray(tnv%d); tnv%d = (i -> first).c_str(); uint32_t len%d = i->second.size(); for (uint32_t j = 0; j < len%d; j++) { tnv%d = pxt->SwapC2JsBool(i->second[j]); pxt->SetArrayElement(tnv%d, j, tnv%d); - }`.format(lt + 2, lt + 2, lt, lt, lt, lt + 2, lt + 1, lt + 2)) - } else if (mapType[3].substring(0, 12) === "NUMBER_TYPE_") { - ret = tnvdef.replaceAll("[calc_out]", `napi_value tnv%d = nullptr; + }`.format(lt + 2, lt + 2, lt, lt, lt, lt + 2, lt + 1, lt + 2)); + } else if (mapType[3].substring(0, 12) === 'NUMBER_TYPE_') { + ret = tnvdef.replaceAll('[calc_out]', `napi_value tnv%d = nullptr; pxt->CreateArray(tnv%d); tnv%d = (i -> first).c_str(); uint32_t len%d = i->second.size(); for (uint32_t j = 0; j < len%d; j++) { tnv%d = NUMBER_C_2_JS(pxt, i->second[j]); pxt->SetArrayElement(tnv%d, j, tnv%d); - }`.format(lt + 2, lt + 2, lt, lt, lt, lt + 2, lt + 1, lt + 2)) + }`.format(lt + 2, lt + 2, lt, lt, lt, lt + 2, lt + 1, lt + 2)); } return ret } function returnGenerateMap(returnInfo, param) { - let type = returnInfo.type - let mapType = getMapType(type) - let mapTypeString + let type = returnInfo.type; + let mapType = getMapType(type); + let mapTypeString; if (mapType[1] !== undefined && mapType[2] === undefined) { - if (mapType[1] === "string") { mapTypeString = "std::string" } - else if (mapType[1].substring(0, 12) === "NUMBER_TYPE_") { mapTypeString = mapType[1] } - else if (mapType[1] === "boolean") { mapTypeString = "bool" } - else if (mapType[1] === "any") { mapTypeString = "std::any" } + if (mapType[1] === 'string') { mapTypeString = 'std::string' } + else if (mapType[1].substring(0, 12) === 'NUMBER_TYPE_') { mapTypeString = mapType[1] } + else if (mapType[1] === 'boolean') { mapTypeString = 'bool' } + else if (mapType[1] === 'any') { mapTypeString = 'std::any' } else { mapTypeString = mapType[1] } } else if (mapType[2] !== undefined) { - if (mapType[2] === "string") { mapTypeString = "std::map" } - else if (mapType[2].substring(0, 12) === "NUMBER_TYPE_") { "std::map" } - else if (mapType[2] === "boolean") { mapTypeString = "std::map" } + if (mapType[2] === 'string') { mapTypeString = 'std::map' } + else if (mapType[2].substring(0, 12) === 'NUMBER_TYPE_') { 'std::map' } + else if (mapType[2] === 'boolean') { mapTypeString = 'std::map' } } else if (mapType[3] !== undefined) { - if (mapType[3] === "string") { mapTypeString = "std::vector" } - else if (mapType[3].substring(0, 12) === "NUMBER_TYPE_") { mapTypeString = "std::vector<"+mapType[3]+">" } - else if (mapType[3] === "boolean") { mapTypeString = "std::vector" } + if (mapType[3] === 'string') { mapTypeString = 'std::vector' } + else if (mapType[3].substring(0, 12) === 'NUMBER_TYPE_') { mapTypeString = 'std::vector<' + mapType[3] + '>' } + else if (mapType[3] === 'boolean') { mapTypeString = 'std::vector' } } - let modifiers = returnInfo.optional ? "*" : "&" - param.valueOut = returnInfo.optional ? "std::map* out = nullptr;".format(mapTypeString) - : "std::map out;".format(mapTypeString) - param.valueDefine += "%sstd::map%s out" - .format(param.valueDefine.length > 0 ? ", " : "", mapTypeString, modifiers) + let modifiers = returnInfo.optional ? '*' : '&'; + param.valueOut = returnInfo.optional ? 'std::map* out = nullptr;'.format(mapTypeString) + : 'std::map out;'.format(mapTypeString); + param.valueDefine += '%sstd::map%s out' + .format(param.valueDefine.length > 0 ? ', ' : '', mapTypeString, modifiers); } -function returnGenerateUnion (param) { +function returnGenerateUnion(param) { param.valueOut = `std::any out; - std::string out_type;\n` - param.valueDefine += "%sstd::any &out".format(param.valueDefine.length > 0 ? ", " : "") + std::string out_type;\n`; + param.valueDefine += '%sstd::any &out'.format(param.valueDefine.length > 0 ? ', ' : ''); } function returnGenerateObject(returnInfo, param, data) { - param.valueOut = `std::map out;\n` - param.valueDefine += "%sstd::map &out".format(param.valueDefine.length > 0 ? ", " : "") - + param.valueOut = `std::map out;\n`; + param.valueDefine += '%sstd::map &out'.format(param.valueDefine.length > 0 ? ', ' : ''); + } /** @@ -539,8 +543,8 @@ function returnGenerateObject(returnInfo, param, data) { * @returns 返回参数的填充代码123 返回测试的值 */ function getReturnFill(returnInfo, param) { - let type = returnInfo.type - let valueFillStr = "" + let type = returnInfo.type; + let valueFillStr = ''; if (isArrowFunc(type)) { return valueFillStr; } @@ -548,192 +552,192 @@ function getReturnFill(returnInfo, param) { if (param.callback) { // callback方法的返回参数处理 if (param.callback.isAsync) { // 异步callback方法返回的是一个结构体,包含errcode和data两部分, 详见basic.d.ts中AsyncCallback的定义 - valueFillStr = "vio->outErrCode" - param.valueDefine += "%suint32_t& outErrCode".format(param.valueDefine.length > 0 ? ", " : "") + valueFillStr = 'vio->outErrCode'; + param.valueDefine += '%suint32_t& outErrCode'.format(param.valueDefine.length > 0 ? ', ' : ''); } - if (type !== "void") { + if (type !== 'void') { // callback 中的xxx不是void时,生成的cpp代码才需要用户填充out参数 if (param.callback.isArrowFuncFlag) { - valueFillStr += "%svio->%s".format(valueFillStr.length > 0 ? ", " : "", returnInfo.name) + valueFillStr += '%svio->%s'.format(valueFillStr.length > 0 ? ', ' : '', returnInfo.name); } else { - valueFillStr += "%svio->out".format(valueFillStr.length > 0 ? ", " : "") - } + valueFillStr += '%svio->out'.format(valueFillStr.length > 0 ? ', ' : ''); + } } } else { // 普通方法的返回参数处理 - valueFillStr = "vio->out" + valueFillStr = 'vio->out'; } - return valueFillStr + return valueFillStr; } function isObjectType(type) { - if(type === "Object" || type === "object") { + if (type === 'Object' || type === 'object') { return true; } return false; } -function generateOptionalAndUnion(returnInfo, param, data, outParam, c2JsresultName = "result") { - let type = returnInfo.type +function generateOptionalAndUnion(returnInfo, param, data, outParam, c2JsresultName = 'result') { + let type = returnInfo.type; if (type === undefined) { - NapiLog.logError("returnGenerate: type of returnInfo is undefined!"); + NapiLog.logError('returnGenerate: type of returnInfo is undefined!'); return; } if (returnInfo.optional) { - param.optionalParamDestory += "C_DELETE(vio->out);\n " + param.optionalParamDestory += 'C_DELETE(vio->out);\n '; } // 判断callback是否有效,若无效,则为普通函数 - let paramCallbackFlag = param.callback !== undefined? true: false - let paramCallbackIsArrow + let paramCallbackFlag = param.callback !== undefined ? true : false; + let paramCallbackIsArrow if (paramCallbackFlag) { // 若callback有效, 判断是否是箭头函数 - paramCallbackIsArrow = param.callback.isArrowFuncFlag + paramCallbackIsArrow = param.callback.isArrowFuncFlag; } // 普通函数 paramCallbackFlag === undefined if (!isEnum(type, data) && !isArrowFunc(type) && !paramCallbackIsArrow) { - param.valuePackage = cToJs(outParam, type, c2JsresultName) - } else if (type.indexOf("|") >= 0) { - returnGenerateUnion(param) + param.valuePackage = cToJs(outParam, type, c2JsresultName); + } else if (type.indexOf('|') >= 0) { + returnGenerateUnion(param); } } function returnGenerateForArrowCbMultiPara(paramInfo, param, data, i) { - let type = paramInfo.type + let type = paramInfo.type; if (type === undefined) { - NapiLog.logError("returnGenerate: type of %s is undefined!".format(paramInfo)); + NapiLog.logError('returnGenerate: type of %s is undefined!'.format(paramInfo)); return; } - let valueFillStr = getReturnFill(paramInfo, param) - param.valueFill += ("%s" + valueFillStr).format(param.valueFill.length > 0 ? ", " : "") - let outParam = paramInfo.optional ? "(*vio->%s)" : "vio->%s".format(paramInfo.name, paramInfo.name) + let valueFillStr = getReturnFill(paramInfo, param); + param.valueFill += ('%s' + valueFillStr).format(param.valueFill.length > 0 ? ', ' : ''); + let outParam = paramInfo.optional ? '(*vio->%s)' : 'vio->%s'.format(paramInfo.name, paramInfo.name); // 回调为,参数个数为1,其转换结果保存在result中 // 回调给箭头函数,支持参数个数大于1,参数转换结果保存在args[i] generateOptionalAndUnion(paramInfo, param, data, outParam); - param.valuePackage += cToJs(outParam, type, "args[%s]".format(i)) + param.valuePackage += cToJs(outParam, type, 'args[%s]'.format(i)); - let modifiers = paramInfo.optional ? "*" : "&" - if (type === "string") { - param.valueOut += paramInfo.optional ? "std::string* %s = nullptr;" : "std::string %s;\n" - .format(paramInfo.name, paramInfo.name) - param.valueDefine += "%sstd::string%s %s".format(param.valueDefine.length > 0 ? ", " : "", modifiers, - paramInfo.name) + let modifiers = paramInfo.optional ? '*' : '&'; + if (type === 'string') { + param.valueOut += paramInfo.optional ? 'std::string* %s = nullptr;' : 'std::string %s;\n' + .format(paramInfo.name, paramInfo.name); + param.valueDefine += '%sstd::string%s %s'.format(param.valueDefine.length > 0 ? ', ' : '', modifiers, + paramInfo.name); } - else if (type === "void") { - NapiLog.logInfo("The current void type don't need generate"); + else if (type === 'void') { + NapiLog.logInfo('The current void type don\'t need generate'); } - else if (type === "boolean") { - param.valueOut += paramInfo.optional ? "bool* %s = nullptr;" : "bool %s;\n" - .format(paramInfo.name, paramInfo.name) - param.valueDefine += "%sbool%s %s".format(param.valueDefine.length > 0 ? ", " : "", modifiers, paramInfo.name) + else if (type === 'boolean') { + param.valueOut += paramInfo.optional ? 'bool* %s = nullptr;' : 'bool %s;\n' + .format(paramInfo.name, paramInfo.name); + param.valueDefine += '%sbool%s %s'.format(param.valueDefine.length > 0 ? ', ' : '', modifiers, paramInfo.name) } - else if (type.substring(0, 12) === "NUMBER_TYPE_") { - param.valueOut += type + (paramInfo.optional ? "* %s = nullptr;" : " %s;\n") - .format(paramInfo.name, paramInfo.name) - param.valueDefine += "%s%s%s %s".format(param.valueDefine.length > 0 ? ", " : "", type, modifiers, - paramInfo.name) + else if (type.substring(0, 12) === 'NUMBER_TYPE_') { + param.valueOut += type + (paramInfo.optional ? '* %s = nullptr;' : ' %s;\n') + .format(paramInfo.name, paramInfo.name); + param.valueDefine += '%s%s%s %s'.format(param.valueDefine.length > 0 ? ', ' : '', type, modifiers, + paramInfo.name); } else { - NapiLog.logError("Do not support returning the type [%s]." + NapiLog.logError('Do not support returning the type [%s].' .format(type), getLogErrInfo()); } } function returnGenerateForOnOffMultiPara(paramInfo, param, data) { - let type = paramInfo.type + let type = paramInfo.type; if (type === undefined) { - NapiLog.logError("returnGenerate: type of %s is undefined!".format(paramInfo)); + NapiLog.logError('returnGenerate: type of %s is undefined!'.format(paramInfo)); return; } - let valueFillStr = getReturnFill(paramInfo, param) - param.valueFill += ("%s" + valueFillStr).format(param.valueFill.length > 0 ? ", " : "") - let outParam = paramInfo.optional ? "(*vio->%s)" : "vio->%s".format(paramInfo.name, paramInfo.name) + let valueFillStr = getReturnFill(paramInfo, param); + param.valueFill += ('%s' + valueFillStr).format(param.valueFill.length > 0 ? ', ' : ''); + let outParam = paramInfo.optional ? '(*vio->%s)' : 'vio->%s'.format(paramInfo.name, paramInfo.name); generateOptionalAndUnion(paramInfo, param, data, outParam); - param.useParams += "%s %s".format(param.useParams.length > 0 ? ", " : "", paramInfo.name) - param.resultDefine += 'napi_value %sNapi = nullptr;\n '.format(paramInfo.name) - param.cbParams += cToJs(paramInfo.name, paramInfo.type, paramInfo.name + "Napi") + '\n'; - - let modifiers = paramInfo.optional ? "*" : "&" - if (type === "string") { - param.valueOut += paramInfo.optional ? "std::string* %s = nullptr;" : "std::string %s;\n" - .format(paramInfo.name, paramInfo.name) - param.params += "%sstd::string%s %s".format(param.params.length > 0 ? ", " : "", modifiers, - paramInfo.name) - } - else if (type === "void") { - NapiLog.logInfo("The current void type don't need generate"); - } - else if (type === "boolean") { - param.valueOut += paramInfo.optional ? "bool* %s = nullptr;" : "bool %s;\n" - .format(paramInfo.name, paramInfo.name) - param.params += "%sbool%s %s".format(param.params.length > 0 ? ", " : "", modifiers, paramInfo.name) - } - else if (type.substring(0, 12) === "NUMBER_TYPE_") { - param.valueOut += type + (paramInfo.optional ? "* %s = nullptr;" : " %s;\n") - .format(paramInfo.name, paramInfo.name) - param.params += "%s%s%s %s".format(param.params.length > 0 ? ", " : "", type, modifiers, - paramInfo.name) - } - else if(generateType(type)) { - returnGenerate2(paramInfo, param, data) - param.params += "%s%s%s %s".format(param.params.length > 0 ? ", " : "", type, modifiers, paramInfo.name) + param.useParams += '%s %s'.format(param.useParams.length > 0 ? ', ' : '', paramInfo.name); + param.resultDefine += 'napi_value %sNapi = nullptr;\n '.format(paramInfo.name); + param.cbParams += cToJs(paramInfo.name, paramInfo.type, paramInfo.name + 'Napi') + '\n'; + + let modifiers = paramInfo.optional ? '*' : '&'; + if (type === 'string') { + param.valueOut += paramInfo.optional ? 'std::string* %s = nullptr;' : 'std::string %s;\n' + .format(paramInfo.name, paramInfo.name); + param.params += '%sstd::string%s %s'.format(param.params.length > 0 ? ', ' : '', modifiers, + paramInfo.name); + } + else if (type === 'void') { + NapiLog.logInfo('The current void type don\'t need generate'); + } + else if (type === 'boolean') { + param.valueOut += paramInfo.optional ? 'bool* %s = nullptr;' : 'bool %s;\n'; + .format(paramInfo.name, paramInfo.name); + param.params += '%sbool%s %s'.format(param.params.length > 0 ? ', ' : '', modifiers, paramInfo.name); + } + else if (type.substring(0, 12) === 'NUMBER_TYPE_') { + param.valueOut += type + (paramInfo.optional ? '* %s = nullptr;' : ' %s;\n'); + .format(paramInfo.name, paramInfo.name); + param.params += '%s%s%s %s'.format(param.params.length > 0 ? ', ' : '', type, modifiers, + paramInfo.name) + } + else if (generateType(type)) { + returnGenerate2(paramInfo, param, data); + param.params += '%s%s%s %s'.format(param.params.length > 0 ? ', ' : '', type, modifiers, paramInfo.name); } else { - NapiLog.logError("Do not support returning the type [%s]." + NapiLog.logError('Do not support returning the type [%s].' .format(type), getLogErrInfo()); } } function returnGenerate(returnInfo, param, data, isOnFuncFlag = false) { if (returnInfo === undefined) { - NapiLog.logError("returnGenerate: returnInfo is undefined!"); - return; + NapiLog.logError('returnGenerate: returnInfo is undefined!'); + return; } - let type = returnInfo.type + let type = returnInfo.type; if (type === undefined) { - NapiLog.logError("returnGenerate: type of %s is undefined!".format(returnInfo)); + NapiLog.logError('returnGenerate: type of %s is undefined!'.format(returnInfo)); return; } - let valueFillStr = getReturnFill(returnInfo, param) - param.valueFill += ("%s" + valueFillStr).format(param.valueFill.length > 0 ? ", " : "") - let outParam = returnInfo.optional ? "(*vio->out)" : "vio->out" - let modifiers = returnInfo.optional ? "*" : "&" + let valueFillStr = getReturnFill(returnInfo, param); + param.valueFill += ('%s' + valueFillStr).format(param.valueFill.length > 0 ? ', ' : ''); + let outParam = returnInfo.optional ? '(*vio->out)' : 'vio->out'; + let modifiers = returnInfo.optional ? '*' : '&'; let result = onCallbackC2JsResName(isOnFuncFlag, type, outParam); - let c2JsresultName = result[0] - outParam = result[1] + let c2JsresultName = result[0]; + outParam = result[1]; generateOptionalAndUnion(returnInfo, param, data, outParam, c2JsresultName); - returnGenerateCheckType(type, param, returnInfo, modifiers, data); + returnGenerateCheckType(type, param, returnInfo, modifiers, data); } function returnGenerateCheckType(type, param, returnInfo, modifiers, data) { - if (type === 'string') { - param.valueOut = returnInfo.optional ? 'std::string* out = nullptr;' : 'std::string out;\n'; - param.valueDefine += '%sstd::string%s out'.format(param.valueDefine.length > 0 ? ', ' : '', modifiers); - } else if (type === 'void') { - NapiLog.logInfo('The current void type do not need generate'); - } else if (type === 'boolean') { - param.valueOut = returnInfo.optional ? 'bool* out = nullptr;' : 'bool out;\n'; - param.valueDefine += '%sbool%s out'.format(param.valueDefine.length > 0 ? ', ' : '', modifiers); - } else if (isEnum(type, data)) { - returnGenerateEnum(data, returnInfo, param); - } else if (generateType(type)) { - returnGenerate2(returnInfo, param, data); - } else if (type.substring(0, 12) === 'NUMBER_TYPE_') { - param.valueOut = type + (returnInfo.optional ? '* out = nullptr;' : ' out;\n'); - param.valueDefine += '%s%s%s out'.format(param.valueDefine.length > 0 ? ', ' : '', type, modifiers); - } else if (isObjectType(type)) { - returnGenerateObject(returnInfo, param, data); - } else if (isArrowFunc(type)) { - genArrowFuncParam(param, returnInfo, data); - } else { - NapiLog.logError('Do not support returning the type [%s].' - .format(type), getLogErrInfo()); - } + if (type === 'string') { + param.valueOut = returnInfo.optional ? 'std::string* out = nullptr;' : 'std::string out;\n'; + param.valueDefine += '%sstd::string%s out'.format(param.valueDefine.length > 0 ? ', ' : '', modifiers); + } else if (type === 'void') { + NapiLog.logInfo('The current void type do not need generate'); + } else if (type === 'boolean') { + param.valueOut = returnInfo.optional ? 'bool* out = nullptr;' : 'bool out;\n'; + param.valueDefine += '%sbool%s out'.format(param.valueDefine.length > 0 ? ', ' : '', modifiers); + } else if (isEnum(type, data)) { + returnGenerateEnum(data, returnInfo, param); + } else if (generateType(type)) { + returnGenerate2(returnInfo, param, data); + } else if (type.substring(0, 12) === 'NUMBER_TYPE_') { + param.valueOut = type + (returnInfo.optional ? '* out = nullptr;' : ' out;\n'); + param.valueDefine += '%s%s%s out'.format(param.valueDefine.length > 0 ? ', ' : '', type, modifiers); + } else if (isObjectType(type)) { + returnGenerateObject(returnInfo, param, data); + } else if (isArrowFunc(type)) { + genArrowFuncParam(param, returnInfo, data); + } else { + NapiLog.logError('Do not support returning the type [%s].' + .format(type), getLogErrInfo()); + } } function genArrowFuncParam(param, returnInfo, data) { @@ -742,12 +746,12 @@ function genArrowFuncParam(param, returnInfo, data) { let paramInfo = { name: returnInfo.arrowFuncParamList[i].name, type: returnInfo.arrowFuncParamList[i].type, - optional: returnInfo.optional + optional: returnInfo.optional, }; if (returnInfo.onFlag) { //on/off处理 returnGenerateForOnOffMultiPara(paramInfo, param, data); param.valueSetArray += 'napi_set_element(pAsyncFuncs->env_, result, %d, %sNapi);\n ' - .format(i, paramInfo.name); + .format(i, paramInfo.name); } else { returnGenerateForArrowCbMultiPara(paramInfo, param, data, i); } @@ -755,116 +759,116 @@ function genArrowFuncParam(param, returnInfo, data) { } function onCallbackC2JsResName(isOnFuncFlag, type, outParam) { - let c2JsresultName = "result"; + let c2JsresultName = 'result'; if (isOnFuncFlag && !isArrowFunc(type) && type !== 'void') { // on事件普通回调方法的参数 - outParam = "valueIn"; - c2JsresultName = "resultTmp"; + outParam = 'valueIn'; + c2JsresultName = 'resultTmp'; } return [c2JsresultName, outParam]; } -function generateType(type){ +function generateType(type) { if (InterfaceList.getValue(type)) { - return true + return true; } else if (TypeList.getValue(type)) { - return true + return true; } - else if (type.substring(0, 6) === "Array<") { - return true + else if (type.substring(0, 6) === 'Array<') { + return true; } - else if (type.substring(type.length - 2) === "[]") { - return true + else if (type.substring(type.length - 2) === '[]') { + return true; } - else if (type.substring(0, 4) === "Map<" || type.indexOf("{[key:") === 0) { - return true + else if (type.substring(0, 4) === 'Map<' || type.indexOf('{[key:') === 0) { + return true; } - else if (type === "any" || type === "Object" || type === "object") { - return true + else if (type === 'any' || type === 'Object' || type === 'object') { + return true; } else { - return false + return false; } } function isMapType(type) { - if(type.substring(0, 4) === "Map<" || type.indexOf("{[key:") === 0) { + if (type.substring(0, 4) === 'Map<' || type.indexOf('{[key:') === 0) { return true; } return false; } -function returnGenerate2(returnInfo, param, data){ - let type = returnInfo.type - let modifiers = returnInfo.optional ? "*" : "&" +function returnGenerate2(returnInfo, param, data) { + let type = returnInfo.type; + let modifiers = returnInfo.optional ? '*' : '&'; - let flag = InterfaceList.getValue(type) || TypeList.getValue(type) + let flag = InterfaceList.getValue(type) || TypeList.getValue(type); if (flag) { - param.valueOut = type + (returnInfo.optional ? "* out = nullptr;" : " out;\n") - param.valueDefine += "%s%s%s out".format(param.valueDefine.length > 0 ? ", " : "", type, modifiers) - } else if (type.substring(0, 6) === "Array<") { + param.valueOut = type + (returnInfo.optional ? '* out = nullptr;' : ' out;\n'); + param.valueDefine += '%s%s%s out'.format(param.valueDefine.length > 0 ? ', ' : '', type, modifiers); + } else if (type.substring(0, 6) === 'Array<') { returnArrayGen(type, param, returnInfo, modifiers); - } else if (type.substring(type.length - 2) === "[]") { - let arrayType = getArrayTypeTwo(type) - arrayType = jsType2CType(arrayType) - if (arrayType === "any") { + } else if (type.substring(type.length - 2) === '[]') { + let arrayType = getArrayTypeTwo(type); + arrayType = jsType2CType(arrayType); + if (arrayType === 'any') { param.valueOut = `std::any out;\n std::string out_type;` - param.valueDefine += "%sstd::any &out".format(param.valueDefine.length > 0 ? ", " : "") + param.valueDefine += '%sstd::any &out'.format(param.valueDefine.length > 0 ? ', ' : ''); } else { - param.valueOut = returnInfo.optional ? "std::vector<%s>* out = nullptr;\n".format(arrayType) - : "std::vector<%s> out;".format(arrayType) - param.valueDefine += "%sstd::vector<%s>%s out".format( - param.valueDefine.length > 0 ? ", " : "", arrayType, modifiers) + param.valueOut = returnInfo.optional ? 'std::vector<%s>* out = nullptr;\n'.format(arrayType) + : 'std::vector<%s> out;'.format(arrayType); + param.valueDefine += '%sstd::vector<%s>%s out'.format( + param.valueDefine.length > 0 ? ', ' : '', arrayType, modifiers); } } else if (isMapType(type)) { - returnGenerateMap(returnInfo, param) - } else if (type === "any") { + returnGenerateMap(returnInfo, param); + } else if (type === 'any') { param.valueOut = `std::any out; - std::string out_type;` - param.valueDefine += "%sstd::any &out".format(param.valueDefine.length > 0 ? ", " : "") + std::string out_type;`; + param.valueDefine += '%sstd::any &out'.format(param.valueDefine.length > 0 ? ', ' : ''); } else if (isObjectType(type)) { - param.valueOut = `std::map out;\n` - param.valueDefine += "%sstd::map &out".format(param.valueDefine.length > 0 ? ", " : "") + param.valueOut = `std::map out;\n`; + param.valueDefine += '%sstd::map &out'.format(param.valueDefine.length > 0 ? ', ' : ''); } } function returnArrayGen(type, param, returnInfo, modifiers) { - let arrayType = getArrayType(type); - arrayType = jsType2CType(arrayType); - if (arrayType === "any") { - param.valueOut = `std::any out; + let arrayType = getArrayType(type); + arrayType = jsType2CType(arrayType); + if (arrayType === 'any') { + param.valueOut = `std::any out; std::string out_type;`; - param.valueDefine += "%sstd::any &out".format(param.valueDefine.length > 0 ? ", " : ""); - } else { - param.valueOut = returnInfo.optional ? "std::vector<%s>* out = nullptr;".format(arrayType) - : "std::vector<%s> out;".format(arrayType); - param.valueDefine += "%sstd::vector<%s>%s out".format( - param.valueDefine.length > 0 ? ", " : "", arrayType, modifiers); - } + param.valueDefine += '%sstd::any &out'.format(param.valueDefine.length > 0 ? ', ' : ''); + } else { + param.valueOut = returnInfo.optional ? 'std::vector<%s>* out = nullptr;'.format(arrayType) + : 'std::vector<%s> out;'.format(arrayType); + param.valueDefine += '%sstd::vector<%s>%s out'.format( + param.valueDefine.length > 0 ? ', ' : '', arrayType, modifiers); + } } function returnGenerateEnum(data, returnInfo, param) { - let type = returnInfo.type - let enumType = returnInfo.type - let index = enumIndex(type, data) - let modifiers = returnInfo.optional ? "*" : "&" + let type = returnInfo.type; + let enumType = returnInfo.type; + let index = enumIndex(type, data); + let modifiers = returnInfo.optional ? '*' : '&'; if (data.enum[index].body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_NUMBER) { - type = "NUMBER_TYPE_" + NumberIncrease.getAndIncrease() + type = 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease(); } else if (data.enum[index].body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_STRING) { - type = "string" + type = 'string'; } else { NapiLog.logError(`function returnGenerateEnum:this type is not support %s` .format(type), getLogErrInfo()); - return + return; } - param.valuePackage = cToJs("vio->out", type, "result", 1, returnInfo.optional, enumType) - if (type === "string") { - param.valueOut = returnInfo.optional ? "std::string* out = nullptr;" : "std::string out;\n" - param.valueDefine += "%sstd::string%s out".format(param.valueDefine.length > 0 ? ", " : "", modifiers) + param.valuePackage = cToJs('vio->out', type, 'result', 1, returnInfo.optional, enumType); + if (type === 'string') { + param.valueOut = returnInfo.optional ? 'std::string* out = nullptr;' : 'std::string out;\n'; + param.valueDefine += '%sstd::string%s out'.format(param.valueDefine.length > 0 ? ', ' : '', modifiers); } - else if (type.substring(0, 12) === "NUMBER_TYPE_") { - param.valueOut = enumType + " out;\n" - param.valueDefine += "%s%s%s out".format(param.valueDefine.length > 0 ? ", " : "", enumType, modifiers) + else if (type.substring(0, 12) === 'NUMBER_TYPE_') { + param.valueOut = enumType + ' out;\n'; + param.valueDefine += '%s%s%s out'.format(param.valueDefine.length > 0 ? ', ' : '', enumType, modifiers); } } @@ -874,5 +878,5 @@ module.exports = { returnGenerate, returnGenerateEnum, objectTempleteFuncReturn, - cToJsForType + cToJsForType, } -- Gitee From 21e02d94872816770f7cc8f0af9f6eecb0b8ef2c Mon Sep 17 00:00:00 2001 From: LiYuxi Date: Thu, 11 Jul 2024 10:36:53 +0800 Subject: [PATCH 02/12] modify type.js Signed-off-by: LiYuxi --- src/cli/dts2cpp/src/gen/generate/type.js | 382 ++++++++++++----------- 1 file changed, 192 insertions(+), 190 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/generate/type.js b/src/cli/dts2cpp/src/gen/generate/type.js index b43aa7ea..aef7251b 100644 --- a/src/cli/dts2cpp/src/gen/generate/type.js +++ b/src/cli/dts2cpp/src/gen/generate/type.js @@ -12,87 +12,87 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { TypeList, getArrayType, getArrayTypeTwo, getMapType, EnumList, jsType2CType } - = require("../tools/common"); -const { NapiLog } = require("../tools/NapiLog"); -const { addUniqObj2List } = require("../tools/tool"); -const re = require("../tools/re"); +const { TypeList, getArrayType, getArrayTypeTwo, getMapType, EnumList, jsType2CType } + = require('../tools/common'); +const { NapiLog } = require('../tools/NapiLog'); +const { addUniqObj2List } = require('../tools/tool'); +const re = require('../tools/re'); function getHDefineOfType(data, name, type, variable, inNamespace, nameSpaceName, toolNamespace) { - if (typeof(type) === 'object') { - // 字符常量转化 - let result = generateTypeEnum(name, data, inNamespace, nameSpaceName, toolNamespace) - variable.hDefine += result.implH - variable.cppDefine += result.implCpp - variable.middleInitDefine += result.midInitEnum - variable.midInitEnumDefine += result.midInitEnumDefine - } else if (type.indexOf("|") >= 0) { - variable.hDefine += "\n typedef std::any %s;".format(name) - } else if (type === "string") { - variable.hDefine += "\n typedef std::string %s;".format(name) - } - else if (type === "boolean") { - variable.hDefine += "\n typedef bool %s;".format(name) - } - else if (type.substring(0, 12) === "NUMBER_TYPE_") { - variable.hDefine += "\n typedef %s %s;".format(type, name) - } - else { - NapiLog.logError(` + if (typeof (type) === 'object') { + // 字符常量转化 + let result = generateTypeEnum(name, data, inNamespace, nameSpaceName, toolNamespace); + variable.hDefine += result.implH; + variable.cppDefine += result.implCpp; + variable.middleInitDefine += result.midInitEnum; + variable.midInitEnumDefine += result.midInitEnumDefine; + } else if (type.indexOf('|') >= 0) { + variable.hDefine += '\n typedef std::any %s;'.format(name); + } else if (type === 'string') { + variable.hDefine += '\n typedef std::string %s;'.format(name); + } + else if (type === 'boolean') { + variable.hDefine += '\n typedef bool %s;'.format(name); + } + else if (type.substring(0, 12) === 'NUMBER_TYPE_') { + variable.hDefine += '\n typedef %s %s;'.format(type, name); + } + else { + NapiLog.logError(` ---- generateVariable fail %s,%s ---- `.format(name, type)); - } + } } function generateTypeEnum(name, data, inNamespace, nameSpaceName, toolNamespace) { - let implH = "" - let implCpp = "" - let midInitEnum = "" - let midInitEnumDefine = "" + let implH = ''; + let implCpp = ''; + let midInitEnum = ''; + let midInitEnumDefine = ''; - implH = `\nclass %s {\npublic:\n`.format(name, implH) - for (let i in data.element) { - let v = data.element[i] - if(midInitEnumDefine === "") { - midInitEnumDefine += 'std::map enumMap%s;\n'.format(name) - } - 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) - } - 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 + implH = `\nclass %s {\npublic:\n`.format(name, implH); + for (let i in data.element) { + let v = data.element[i]; + if (midInitEnumDefine === '') { + midInitEnumDefine += 'std::map enumMap%s;\n'.format(name); + } + 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); + } + 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; } function getHDefineOfVariable(name, type, variable, optional) { - if (type.indexOf("|") >= 0) { - unionTypeString(name, type, variable, optional) - } else if (type === "string") { + if (type.indexOf('|') >= 0) { + unionTypeString(name, type, variable, optional); + } else if (type === 'string') { variableTypeString(optional, variable, name); } - else if (TypeList.getValue(type)) variable.hDefine += "\n %s %s;".format(type, name) - else if (EnumList.getValue(type)) variable.hDefine += "\n %s %s;".format(type, name) - else if (type.indexOf("Array<") === 0) { + else if (TypeList.getValue(type)) variable.hDefine += '\n %s %s;'.format(type, name); + else if (EnumList.getValue(type)) variable.hDefine += '\n %s %s;'.format(type, name); + else if (type.indexOf('Array<') === 0) { typeArrFunctionOne(type, variable, name, optional); - } else if (type === "boolean") { + } else if (type === 'boolean') { variableTypeBoolean(optional, variable, name); - } else if (type.substring(type.length - 2) === "[]") { + } else if (type.substring(type.length - 2) === '[]') { typeArrFunctionTwo(type, variable, name, optional); } else if (checkIsMap(type)) { - variable.hDefine += mapTypeString(type, name, optional) - } else if (type === "any") { - variable.hDefine += anyTypeString(type, name) - } else if (type.substring(0, 12) === "NUMBER_TYPE_") { + variable.hDefine += mapTypeString(type, name, optional); + } else if (type === 'any') { + variable.hDefine += anyTypeString(type, name); + } else if (type.substring(0, 12) === 'NUMBER_TYPE_') { variableTypeNumber(optional, variable, type, name); } else if (checkIsObject(type)) { - variable.hDefine += "\n std::map %s;".format(name) + variable.hDefine += '\n std::map %s;'.format(name); } else { NapiLog.logError(` @@ -102,228 +102,230 @@ function getHDefineOfVariable(name, type, variable, optional) { } function checkIsObject(type) { - return type === 'Object' || type === 'object'; + return type === 'Object' || type === 'object'; } function checkIsMap(type) { - return type.substring(0, 4) === 'Map<' || type.indexOf('{[key:') === 0; + return type.substring(0, 4) === 'Map<' || type.indexOf('{[key:') === 0; } function variableTypeNumber(optional, variable, type, name) { - if (optional) { - variable.hDefine += '\n std::optional<%s> %s;'.format(type, name); - } else { - variable.hDefine += '\n %s %s;'.format(type, name); - } + if (optional) { + variable.hDefine += '\n std::optional<%s> %s;'.format(type, name); + } else { + variable.hDefine += '\n %s %s;'.format(type, name); + } } function variableTypeBoolean(optional, variable, name) { - if (optional) { - variable.hDefine += '\n std::optional %s;'.format(name); - } else { - variable.hDefine += '\n bool %s;'.format(name); - } + if (optional) { + variable.hDefine += '\n std::optional %s;'.format(name); + } else { + variable.hDefine += '\n bool %s;'.format(name); + } } function variableTypeString(optional, variable, name) { - if (optional) { - variable.hDefine += '\n std::optional %s;'.format(name); - } else { - variable.hDefine += '\n std::string %s;'.format(name); - } + if (optional) { + variable.hDefine += '\n std::optional %s;'.format(name); + } else { + variable.hDefine += '\n std::string %s;'.format(name); + } } function typeArrFunctionTwo(type, variable, name, optional) { let arrayType = getArrayTypeTwo(type); - if (arrayType === "any") { - variable.hDefine += "\n std::string %s_type;\n std::any %s;".format(name, name); + if (arrayType === 'any') { + variable.hDefine += '\n std::string %s_type;\n std::any %s;'.format(name, name); } else { let cType = jsType2CType(arrayType); if (optional) { - variable.hDefine += "\n std::optional> %s;".format(cType, name); + variable.hDefine += '\n std::optional> %s;'.format(cType, name); } else { - variable.hDefine += "\n std::vector<%s> %s;".format(cType, name); + variable.hDefine += '\n std::vector<%s> %s;'.format(cType, name); } } } function typeArrFunctionOne(type, variable, name, optional) { let arrayType = getArrayType(type); - if (arrayType === "any") { - variable.hDefine += "\n std::string %s_type; \n std::any %s;".format(name, name); + if (arrayType === 'any') { + variable.hDefine += '\n std::string %s_type; \n std::any %s;'.format(name, name); } else { let cType = jsType2CType(arrayType); if (optional) { - variable.hDefine += "\n std::optional> %s;".format(cType, name); + variable.hDefine += '\n std::optional> %s;'.format(cType, name); } else { - variable.hDefine += "\n std::vector<%s> %s;".format(cType, name); + variable.hDefine += '\n std::vector<%s> %s;'.format(cType, name); } } } function generateVariable(value, variable) { - let name = value.name - let type = value.type - let optional = value.optional - getHDefineOfVariable(name, type, variable, optional) + let name = value.name; + let type = value.type; + let optional = value.optional; + getHDefineOfVariable(name, type, variable, optional); } function unionTypeString(name, type, variable, optional) { if (optional) { variable.hDefine += `std::optional %s_type;\n - std::optional %s;`.format(name, name) + std::optional %s;`.format(name, name); } else { variable.hDefine += `std::string %s_type;\n - std::any %s;`.format(name, name) + std::any %s;`.format(name, name); } - + } function mapTypeString(type, name, optional) { - let mapType = getMapType(type) - let mapTypeString + let mapType = getMapType(type); + let mapTypeString; if (mapType[1] !== undefined && mapType[2] === undefined) { - if (mapType[1] === "string") mapTypeString = "std::string, std::string" - else if (mapType[1] === "boolean") mapTypeString = "std::string, bool" - else if (mapType[1].substring(0, 12) === "NUMBER_TYPE_") { - mapTypeString = "std::string, %s".format(mapType[1]) + if (mapType[1] === 'string') mapTypeString = 'std::string, std::string' + else if (mapType[1] === 'boolean') mapTypeString = 'std::string, bool' + else if (mapType[1].substring(0, 12) === 'NUMBER_TYPE_') { + mapTypeString = 'std::string, %s'.format(mapType[1]); } - else if (mapType[1].substring(0, 12) === "any") { - mapTypeString = `std::string, std::any`.format(mapType[1]) + else if (mapType[1].substring(0, 12) === 'any') { + mapTypeString = `std::string, std::any`.format(mapType[1]); return `\n std::map<%s> %s; - std::string %s_type;`.format(mapTypeString, name, name) + std::string %s_type;`.format(mapTypeString, name, name); + } + else if (TypeList.getValue(mapType[1])) { + mapTypeString = 'std::string, %s'.format(mapType[1]); } - else if (TypeList.getValue(mapType[1])) mapTypeString = "std::string, %s".format(mapType[1]) } if (mapType[2] !== undefined) { - if (mapType[2] === "string") mapTypeString = "std::string, std::map" - else if (mapType[2] === "boolean") mapTypeString = "std::string, std::map" - else if (mapType[2].substring(0, 12) === "NUMBER_TYPE_") { - mapTypeString = "std::string, std::map".format(mapType[2]) + if (mapType[2] === 'string') mapTypeString = 'std::string, std::map'; + else if (mapType[2] === 'boolean') mapTypeString = 'std::string, std::map'; + else if (mapType[2].substring(0, 12) === 'NUMBER_TYPE_') { + mapTypeString = 'std::string, std::map'.format(mapType[2]); } } if (mapType[3] !== undefined) { - if (mapType[3] === "string") mapTypeString = "std::string, std::vector" - else if (mapType[3] === "boolean") mapTypeString = "std::string, std::vector" - else if (mapType[3].substring(0, 12) === "NUMBER_TYPE_") { - mapTypeString = "std::string, std::vector<%s>".format(mapType[3]) + if (mapType[3] === 'string') mapTypeString = 'std::string, std::vector'; + else if (mapType[3] === 'boolean') mapTypeString = 'std::string, std::vector'; + else if (mapType[3].substring(0, 12) === 'NUMBER_TYPE_') { + mapTypeString = 'std::string, std::vector<%s>'.format(mapType[3]); } } if (optional) { - return "\n std::optional> %s;".format(mapTypeString, name); + return '\n std::optional> %s;'.format(mapTypeString, name); } else { - return "\n std::map<%s> %s;".format(mapTypeString, name); + return '\n std::map<%s> %s;'.format(mapTypeString, name); } } -function anyTypeString (type, name) { +function anyTypeString(type, name) { let anyType = `\n std::string %s_type; - std::any %s;` + std::any %s;`; - return anyType.format(name, name) + return anyType.format(name, name); } function getSelfNs(inNamespace) { - let selfNs = '' + 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]; } } - return selfNs + return selfNs; } function generateType(name, data, inNamespace, inNameSpaceEnum, nameSpaceName, toolNamespace) { let result = { - implH: '', - implCpp: '', - middleBody: '', - middleInit: '', - declarationH:'', - middleH: '', - midInitEnumDefine: '' - } - let resultConnect = connectResult(name, data, inNameSpaceEnum, nameSpaceName, toolNamespace) - let implH = resultConnect[1] - let implCpp = resultConnect[2] - let middleInit = resultConnect[3] - let midInitEnumDefine = resultConnect[4] - let selfNs = "" - selfNs = getSelfNs(inNamespace); - if (implH.indexOf("typedef") > 0) { - result = { - implH: implH, - implCpp: implCpp, + implH: '', + implCpp: '', middleBody: '', - middleInit: middleInit, - declarationH:'', + middleInit: '', + declarationH: '', middleH: '', - midInitEnumDefine: midInitEnumDefine - } + midInitEnumDefine: '', + } + let resultConnect = connectResult(name, data, inNameSpaceEnum, nameSpaceName, toolNamespace); + let implH = resultConnect[1]; + let implCpp = resultConnect[2]; + let middleInit = resultConnect[3]; + let midInitEnumDefine = resultConnect[4]; + let selfNs = ''; + selfNs = getSelfNs(inNamespace); + if (implH.indexOf('typedef') > 0) { + result = { + implH: implH, + implCpp: implCpp, + middleBody: '', + middleInit: middleInit, + declarationH: '', + middleH: '', + midInitEnumDefine: midInitEnumDefine, + } } else if (implCpp !== '' && middleInit !== '') { - result = { - implH: implH, - implCpp: implCpp, - middleBody: '', - middleInit: middleInit, - declarationH:'', - middleH: '', - midInitEnumDefine: midInitEnumDefine - } + result = { + implH: implH, + implCpp: implCpp, + middleBody: '', + middleInit: middleInit, + declarationH: '', + middleH: '', + midInitEnumDefine: midInitEnumDefine, + } } else { - result = { - implH: ` + result = { + implH: ` struct %s { %s };\n`.format(name, implH), - implCpp: implCpp, - middleBody: '', - middleInit: middleInit, - declarationH: ` + implCpp: implCpp, + middleBody: '', + middleInit: middleInit, + declarationH: `, struct %s;\r`.format(name), - middleH: '', - midInitEnumDefine: '' - } + middleH: '', + midInitEnumDefine: '', + } } - return result + return result; } // 递归获取所有成员属性和 function getAllPropties(interfaceBody, properties) { for (let i in interfaceBody.value) { - addUniqObj2List(interfaceBody.value[i], properties.values) + addUniqObj2List(interfaceBody.value[i], properties.values); } -} +} function connectResult(name, data, inNamespace, nameSpaceName, toolNamespace) { - let implH = "" - let implCpp = "" - let middleFunc = "" - let middleInit = "" - let midInitEnumDefine = "" + let implH = ''; + let implCpp = ''; + let middleFunc = ''; + let middleInit = ''; + let midInitEnumDefine = ''; let variable = { - hDefine: "", - cppDefine: "", - middleInitDefine: "", - midInitEnumDefine: "" + hDefine: '', + cppDefine: '', + middleInitDefine: '', + midInitEnumDefine: '', } - if (Object.prototype.hasOwnProperty.call(data, "value")) { - data.allProperties = {values:[]} - getAllPropties(data, data.allProperties) - for (let i in data.allProperties.values) { - let v = data.allProperties.values[i] - generateVariable(v, variable) - } + if (Object.prototype.hasOwnProperty.call(data, 'value')) { + data.allProperties = { values: [] } + getAllPropties(data, data.allProperties); + for (let i in data.allProperties.values) { + let v = data.allProperties.values[i]; + generateVariable(v, variable); + } } else { - let type = data - getHDefineOfType(data, name, type, variable, inNamespace, nameSpaceName, toolNamespace) + let type = data; + getHDefineOfType(data, name, type, variable, inNamespace, nameSpaceName, toolNamespace); } - implH += variable.hDefine - implCpp += variable.cppDefine - middleInit += variable.middleInitDefine - midInitEnumDefine += variable.midInitEnumDefine - return [middleFunc, implH, implCpp, middleInit, midInitEnumDefine] + implH += variable.hDefine; + implCpp += variable.cppDefine; + middleInit += variable.middleInitDefine; + midInitEnumDefine += variable.midInitEnumDefine; + return [middleFunc, implH, implCpp, middleInit, midInitEnumDefine]; } module.exports = { @@ -331,7 +333,7 @@ module.exports = { connectResult, generateVariable, mapTypeString, - generateTypeEnum + generateTypeEnum, } -- Gitee From b920cedc563bf6f11dc6344044c0927cbc8cfc45 Mon Sep 17 00:00:00 2001 From: LiYuxi Date: Thu, 11 Jul 2024 10:42:47 +0800 Subject: [PATCH 03/12] modify main.js Signed-off-by: LiYuxi --- src/cli/dts2cpp/src/gen/main.js | 58 ++++++++++++++++----------------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/main.js b/src/cli/dts2cpp/src/gen/main.js index 49bd092e..5322d2fe 100644 --- a/src/cli/dts2cpp/src/gen/main.js +++ b/src/cli/dts2cpp/src/gen/main.js @@ -12,11 +12,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { analyzeFile } = require("./analyze"); -const { analyzeFileRaw } = require("./analyzeRaw"); -const { generateAll } = require("./generate"); -const { NapiLog } = require("./tools/NapiLog"); -const re = require("./tools/re"); +const { analyzeFile } = require('./analyze'); +const { analyzeFileRaw } = require('./analyzeRaw'); +const { generateAll } = require('./generate'); +const { NapiLog } = require('./tools/NapiLog'); +const re = require('./tools/re'); var fs = require('fs'); function doGenerate(ifname, destdir, imports, numberType, jsonCfg) { @@ -25,16 +25,16 @@ function doGenerate(ifname, destdir, imports, numberType, jsonCfg) { // to repace analyzeFile bythe below: let structOfTsRaw = analyzeFileRaw(ifname); let fn = re.getFileInPath(ifname); let tt = re.match('(@ohos\.)*([.a-z_A-Z0-9]+).d.ts', fn); - if (structOfTs === undefined || structOfTs.declareNamespace.length === 0 || + if (structOfTs === undefined || structOfTs.declareNamespace.length === 0 || structOfTs.declareNamespace[0].name === undefined) { NapiLog.logError('analyzeFile file fail and file name is: ' + fn); return; } - + // step2: generate code if (tt) { let moduleName = re.getReg(fn, tt.regs[2]); - let importsStr = '' + imports + let importsStr = '' + imports; if (importsStr === 'true') { importsFun(structOfTs.imports, destdir, ifname); } else { @@ -44,44 +44,44 @@ function doGenerate(ifname, destdir, imports, numberType, jsonCfg) { } else { NapiLog.logError('file name ' + fn + ' format invalid in function of doGenerate!'); } - return structOfTs.declareNamespace[0].name + return structOfTs.declareNamespace[0].name; } function importsFun(imports, destDir, ifname) { for (let i = 0; i < imports.length; i++) { - let importSearch = re.search("([.,/a-zA-Z {}']+from)", imports[i]) - let importPath = re.removeReg(imports[i], importSearch.regs[0]) - importPath = importPath.replace - (/[`:~!#$%^&*() \+ =<>?"{}|, ;' [ \] ·~!#¥%……&*()—— \+ ={}|《》?:“”【】、;‘’,。、]/g,'') - importPath = importPath.split('/') + let importSearch = re.search('([.,/a-zA-Z {}\']+from)', imports[i]); + let importPath = re.removeReg(imports[i], importSearch.regs[0]); + importPath = importPath.replace( + /[`:~!#$%^&*() \+ =<>?"{}|, ;' [ \] ·~!#¥%……&*()—— \+ ={}|《》?:“”【】、;‘’,。、]/g, ''); + importPath = importPath.split('/'); - let ifnameSearch = re.search("(@[./a-zA-Z]+d.ts)", ifname) - let ifnamePath = re.removeReg(ifname, ifnameSearch.regs[0]) - let filePath = ifnamePath+importPath[importPath.length-1]+'.d.ts' + let ifnameSearch = re.search('(@[./a-zA-Z]+d.ts)', ifname); + let ifnamePath = re.removeReg(ifname, ifnameSearch.regs[0]); + let filePath = ifnamePath + importPath[importPath.length - 1] + '.d.ts'; - let ifnameFile = fs.readFileSync(ifname,'utf-8') - let importFile + let ifnameFile = fs.readFileSync(ifname, 'utf-8'); + let importFile; try { - importFile = fs.readFileSync(ifnamePath+importPath[importPath.length-1]+'.d.ts','utf-8') + importFile = fs.readFileSync(ifnamePath + importPath[importPath.length - 1] + '.d.ts', 'utf-8'); } catch (err) { - imports[i] = '' - return + imports[i] = ''; + return; } - + if (ifnameFile === importFile) { - return + return; } else { try { - fs.accessSync(destDir+'/'+importPath[importPath.length-1], fs.constants.R_OK | fs.constants.W_OK); + fs.accessSync(destDir + '/' + importPath[importPath.length - 1], fs.constants.R_OK | fs.constants.W_OK); } catch (err) { - fs.mkdirSync(destDir+'/'+importPath[importPath.length-1]); + fs.mkdirSync(destDir + '/' + importPath[importPath.length - 1]); } - imports[i] = '#include '+'"'+importPath[importPath.length-1]+'/'+ - doGenerate(filePath,destDir+'/'+importPath[importPath.length-1])+'.h"\n' + imports[i] = '#include ' + '"' + importPath[importPath.length - 1] + '/' + + doGenerate(filePath, destDir + '/' + importPath[importPath.length - 1]) + '.h"\n' } } } module.exports = { - doGenerate + doGenerate, } -- Gitee From 5b61c127d9cfee156397706f0a0b0d485f146f9f Mon Sep 17 00:00:00 2001 From: LiYuxi Date: Thu, 11 Jul 2024 11:24:10 +0800 Subject: [PATCH 04/12] modify tools/ Signed-off-by: LiYuxi --- src/cli/dts2cpp/src/gen/tools/FileRW.js | 194 +++++------ src/cli/dts2cpp/src/gen/tools/NapiLog.js | 66 ++-- src/cli/dts2cpp/src/gen/tools/common.js | 406 +++++++++++------------ src/cli/dts2cpp/src/gen/tools/re.js | 28 +- src/cli/dts2cpp/src/gen/tools/tool.js | 225 ++++++------- 5 files changed, 462 insertions(+), 457 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/tools/FileRW.js b/src/cli/dts2cpp/src/gen/tools/FileRW.js index 0e950ebc..8f202d87 100644 --- a/src/cli/dts2cpp/src/gen/tools/FileRW.js +++ b/src/cli/dts2cpp/src/gen/tools/FileRW.js @@ -15,126 +15,126 @@ const fs = require('fs'); function utf8ArrayToStr(array) { - var out, i, len, c; - var char2, char3; + var out, i, len, c; + var char2, char3; - out = ""; - len = array.length; - i = 0; - while (i < len) { - c = array[i++]; - switch (c >> 4) { - case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: - // 0xxxxxxx - out += String.fromCharCode(c); - break; - case 12: case 13: - // 110x xxxx 10xx xxxx - char2 = array[i++]; - out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); - break; - case 14: - // 1110 xxxx 10xx xxxx 10xx xxxx - char2 = array[i++]; - char3 = array[i++]; - out += String.fromCharCode(((c & 0x0F) << 12) | - ((char2 & 0x3F) << 6) | - ((char3 & 0x3F) << 0)); - break; + out = ""; + len = array.length; + i = 0; + while (i < len) { + c = array[i++]; + switch (c >> 4) { + case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: + // 0xxxxxxx + out += String.fromCharCode(c); + break; + case 12: case 13: + // 110x xxxx 10xx xxxx + char2 = array[i++]; + out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); + break; + case 14: + // 1110 xxxx 10xx xxxx 10xx xxxx + char2 = array[i++]; + char3 = array[i++]; + out += String.fromCharCode(((c & 0x0F) << 12) | + ((char2 & 0x3F) << 6) | + ((char3 & 0x3F) << 0)); + break; + } } - } - return out; + return out; } function stringToUint8Array(string, options = { stream: false }) { - if (options.stream) { - throw new Error(`Failed to encode: the 'stream' option is unsupported.`); - } - let pos = 0; - const len = string.length; - let at = 0; // output position - let tlen = Math.max(32, len + (len >> 1) + 7); // 1.5x size - let target = new Uint8Array((tlen >> 3) << 3); // ... but at 8 byte offset + if (options.stream) { + throw new Error(`Failed to encode: the 'stream' option is unsupported.`); + } + let pos = 0; + const len = string.length; + let at = 0; // output position + let tlen = Math.max(32, len + (len >> 1) + 7); // 1.5x size + let target = new Uint8Array((tlen >> 3) << 3); // ... but at 8 byte offset - while (pos < len) { - let value = string.charCodeAt(pos++); - let isContinue = false; - if (value >= 0xd800 && value <= 0xdbff) { - if (pos < len) {// high surrogate - const extra = string.charCodeAt(pos); - if ((extra & 0xfc00) === 0xdc00) { - ++pos; - value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000; + while (pos < len) { + let value = string.charCodeAt(pos++); + let isContinue = false; + if (value >= 0xd800 && value <= 0xdbff) { + if (pos < len) {// high surrogate + const extra = string.charCodeAt(pos); + if ((extra & 0xfc00) === 0xdc00) { + ++pos; + value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000; + } + } + if (value >= 0xd800 && value <= 0xdbff) { + isContinue = true; // drop lone surrogate + } } - } - if (value >= 0xd800 && value <= 0xdbff) { - isContinue = true; // drop lone surrogate - } - } - if (!isContinue) { - // expand the buffer if we couldn't write 4 bytes - if (at + 4 > target.length) { - tlen += 8; // minimum extra - tlen *= (1.0 + (pos / string.length) * 2); // take 2x the remaining - tlen = (tlen >> 3) << 3; // 8 byte offset + if (!isContinue) { + // expand the buffer if we couldn't write 4 bytes + if (at + 4 > target.length) { + tlen += 8; // minimum extra + tlen *= (1.0 + (pos / string.length) * 2); // take 2x the remaining + tlen = (tlen >> 3) << 3; // 8 byte offset - target = uint8Array(tlen, target); - } + target = uint8Array(tlen, target); + } - let calculateResult = calculate(value, target, at) - isContinue = calculateResult[0] - target = calculateResult[1] - at = calculateResult[2] + let calculateResult = calculate(value, target, at); + isContinue = calculateResult[0]; + target = calculateResult[1]; + at = calculateResult[2]; + } } - } - return target.slice(0, at); + return target.slice(0, at); } function calculate(value, target, at) { - let isContinue = false - if ((value & 0xffffff80) === 0) { // 1-byte - target[at++] = value; // ASCII - isContinue = true; - } else if ((value & 0xfffff800) === 0) { // 2-byte - target[at++] = ((value >> 6) & 0x1f) | 0xc0; - } else if ((value & 0xffff0000) === 0) { // 3-byte - target[at++] = ((value >> 12) & 0x0f) | 0xe0; - target[at++] = ((value >> 6) & 0x3f) | 0x80; - } else if ((value & 0xffe00000) === 0) { // 4-byte - target[at++] = ((value >> 18) & 0x07) | 0xf0; - target[at++] = ((value >> 12) & 0x3f) | 0x80; - target[at++] = ((value >> 6) & 0x3f) | 0x80; - } else { - isContinue = true; - } - if (!isContinue) { - target[at++] = (value & 0x3f) | 0x80; - } - return [isContinue, target, at] + let isContinue = false; + if ((value & 0xffffff80) === 0) { // 1-byte + target[at++] = value; // ASCII + isContinue = true; + } else if ((value & 0xfffff800) === 0) { // 2-byte + target[at++] = ((value >> 6) & 0x1f) | 0xc0; + } else if ((value & 0xffff0000) === 0) { // 3-byte + target[at++] = ((value >> 12) & 0x0f) | 0xe0; + target[at++] = ((value >> 6) & 0x3f) | 0x80; + } else if ((value & 0xffe00000) === 0) { // 4-byte + target[at++] = ((value >> 18) & 0x07) | 0xf0; + target[at++] = ((value >> 12) & 0x3f) | 0x80; + target[at++] = ((value >> 6) & 0x3f) | 0x80; + } else { + isContinue = true; + } + if (!isContinue) { + target[at++] = (value & 0x3f) | 0x80; + } + return [isContinue, target, at]; } function uint8Array(tlen, target) { - const update = new Uint8Array(tlen); - update.set(target); - return update + const update = new Uint8Array(tlen); + update.set(target); + return update; } function readFile(fn) { - if (!fs.existsSync(fn)) { - return ""; - } - let data = fs.readFileSync(fn); - data = utf8ArrayToStr(data); - return data; + if (!fs.existsSync(fn)) { + return ""; + } + let data = fs.readFileSync(fn); + data = utf8ArrayToStr(data); + return data; } function writeFile(fn, str) { - let data = stringToUint8Array(str); - fs.writeFileSync(fn, data); + let data = stringToUint8Array(str); + fs.writeFileSync(fn, data); } module.exports = { - readFile, - writeFile -} \ No newline at end of file + readFile, + writeFile, +}; \ No newline at end of file diff --git a/src/cli/dts2cpp/src/gen/tools/NapiLog.js b/src/cli/dts2cpp/src/gen/tools/NapiLog.js index ce9c4f0b..b35db3cf 100644 --- a/src/cli/dts2cpp/src/gen/tools/NapiLog.js +++ b/src/cli/dts2cpp/src/gen/tools/NapiLog.js @@ -13,7 +13,7 @@ * limitations under the License. */ const fs = require('fs'); -const path = require("path"); +const path = require('path'); let vscode = null; try { vscode = require('vscode'); @@ -31,10 +31,10 @@ NapiLog.LEV_ERROR = 1; NapiLog.LEV_DEBUG = 2; NapiLog.LEV_INFO = 3; -const LEV_STR = ["[NON]", "[ERR]", "[DBG]", "[INF]"] +const LEV_STR = ['[NON]', '[ERR]', '[DBG]', '[INF]']; var logLevel = NapiLog.LEV_ERROR; var logFileName = null; -var logResultMessage = [true, ""] +var logResultMessage = [true, '']; function getDateString() { let nowDate = new Date(); @@ -43,7 +43,7 @@ function getDateString() { function saveLog(dateStr, levStr, detail) { if (logFileName) { - let logStr = dateStr + " " + levStr + " " + detail + "\n"; + let logStr = dateStr + ' ' + levStr + ' ' + detail + '\n'; fs.appendFileSync(logFileName, logStr); } } @@ -51,7 +51,7 @@ function saveLog(dateStr, levStr, detail) { NapiLog.init = function (level, fileName) { logLevel = level in [NapiLog.LEV_NONE, NapiLog.LEV_ERROR, NapiLog.LEV_DEBUG, NapiLog.LEV_INFO] ? level : NapiLog.LEV_ERROR; - logFileName = fileName ? fileName : "napi_generator.log"; + logFileName = fileName ? fileName : 'napi_generator.log'; } /** @@ -59,33 +59,33 @@ NapiLog.init = function (level, fileName) { * @param {} callerFuncName 指定取调用栈中哪个方法名所在的帧作为目标帧 * @returns */ -NapiLog.getCallPath = function(callerFuncName = null) { - let callPath = "" +NapiLog.getCallPath = function (callerFuncName = null) { + let callPath = ''; let stackArray = new Error().stack.split('\n'); // 如果没有指定目标方法,默认在调用栈中查找当前方法"getCallPath"所在的帧 - let destFuncName = callerFuncName != null ? callerFuncName : "getCallPath" + let destFuncName = callerFuncName != null ? callerFuncName : 'getCallPath'; - for (let i = stackArray.length -1; i >=0 ; --i) { + for (let i = stackArray.length - 1; i >= 0; --i) { // debug模式和打包后的可执行程序调用栈函数名不同, 以NapiLog.log()方法为例: // vscode debug模式下调用栈打印的方法名为NapiLog.log,而可执行程序的调用栈中显示为Function.log() - let callerMatch = (stackArray[i].indexOf("NapiLog." + destFuncName) > 0 - || stackArray[i].indexOf("Function." + destFuncName) > 0) + let callerMatch = (stackArray[i].indexOf('NapiLog.' + destFuncName) > 0 || + stackArray[i].indexOf('Function.' + destFuncName) > 0); if (callerMatch) { - let stackMsg = stackArray[i+1].trim() - let leftIndex = stackMsg.indexOf("(") - let rightIndex = stackMsg.indexOf(")") + let stackMsg = stackArray[i + 1].trim(); + let leftIndex = stackMsg.indexOf('('); + let rightIndex = stackMsg.indexOf(')'); if (leftIndex > 0 && rightIndex > 0) { let funInfo = stackMsg.substring(0, leftIndex); - let srcPath = stackMsg.substring(leftIndex + 1, rightIndex) - let colNumIndex = srcPath.lastIndexOf(":") - let colNum = srcPath.substring(colNumIndex + 1, srcPath.length) - let lineNumIndex = srcPath.lastIndexOf(":", colNumIndex - 1) - let lineNum = srcPath.substring(lineNumIndex + 1, colNumIndex) - let filePath = srcPath.substring(0, lineNumIndex) - - callPath = "%s[%s(%s:%s)]".format(funInfo,filePath,lineNum,colNum) + let srcPath = stackMsg.substring(leftIndex + 1, rightIndex); + let colNumIndex = srcPath.lastIndexOf(':'); + let colNum = srcPath.substring(colNumIndex + 1, srcPath.length); + let lineNumIndex = srcPath.lastIndexOf(':', colNumIndex - 1); + let lineNum = srcPath.substring(lineNumIndex + 1, colNumIndex); + let filePath = srcPath.substring(0, lineNumIndex); + + callPath = '%s[%s(%s:%s)]'.format(funInfo, filePath, lineNum, colNum); } break; } @@ -98,19 +98,19 @@ function print(...args) { if (vscode) { vscode.window.showInformationMessage(...args); } - console.log(args + ""); + console.log(args + ''); } function recordLog(lev, ...args) { let origMsgInfo = args; - let callPath = NapiLog.getCallPath("log"); + let callPath = NapiLog.getCallPath('log'); let dataStr = getDateString(); - let detail = args.join(" "); - saveLog(dataStr + " " + callPath, LEV_STR[lev], detail); + let detail = args.join(' '); + saveLog(dataStr + ' ' + callPath, LEV_STR[lev], detail); if (lev === NapiLog.LEV_ERROR) { logResultMessage = [false, detail]; } - let logStr = callPath + " " + detail; + let logStr = callPath + ' ' + detail; if (logLevel <= lev) return logStr; NapiLog.logInfo(origMsgInfo[0]); return logStr; @@ -119,20 +119,20 @@ function recordLog(lev, ...args) { NapiLog.logError = function (...args) { let logInfo = recordLog(NapiLog.LEV_ERROR, args); print(logInfo); -} +}; NapiLog.logDebug = function (...args) { recordLog(NapiLog.LEV_DEBUG, args); -} +}; NapiLog.logInfo = function (...args) { recordLog(NapiLog.LEV_INFO, args); -} +}; NapiLog.getResult = function () { return logResultMessage; -} +}; module.exports = { - NapiLog -} \ No newline at end of file + NapiLog, +}; \ No newline at end of file diff --git a/src/cli/dts2cpp/src/gen/tools/common.js b/src/cli/dts2cpp/src/gen/tools/common.js index e7d56b9e..dffc6d93 100644 --- a/src/cli/dts2cpp/src/gen/tools/common.js +++ b/src/cli/dts2cpp/src/gen/tools/common.js @@ -12,70 +12,70 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const re = require("./re"); -const tsc = require("../../node_modules/typescript"); +const re = require('./re'); +const tsc = require('../../node_modules/typescript'); function checkFileError(ifname) { - let program = tsc.createProgram([ifname], {target: tsc.ScriptTarget.Latest,}) + let program = tsc.createProgram([ifname], { target: tsc.ScriptTarget.Latest, }); let emitResult = program.emit(); let allDiagnostics = tsc.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); - let errorMsg = '' + let errorMsg = ''; allDiagnostics.forEach(diagnostic => { if (diagnostic.file) { let { line, character } = tsc.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); - let message = tsc.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); + let message = tsc.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); errorMsg += `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}\n`; } else { - errorMsg += tsc.flattenDiagnosticMessageText(diagnostic.messageText, "\n") + "\n"; + errorMsg += tsc.flattenDiagnosticMessageText(diagnostic.messageText, '\n') + '\n'; } }); if (allDiagnostics.length > 0) { return [false, errorMsg]; } - return [true, ""]; + return [true, '']; } class FuncType { } -FuncType.DIRECT = 1 -FuncType.SYNC = 2 -FuncType.ASYNC = 4 -FuncType.PROMISE = 8 +FuncType.DIRECT = 1; +FuncType.SYNC = 2; +FuncType.ASYNC = 4; +FuncType.PROMISE = 8; FuncType.ToString = function (type) { - if (type === FuncType.DIRECT) return "DIRECT"; - else if (type === FuncType.SYNC) return "SYNC"; - else if (type === FuncType.ASYNC) return "ASYNC"; - else if (type === FuncType.PROMISE) return "PROMISE"; - return "UNKNOW"; -} + if (type === FuncType.DIRECT) return 'DIRECT'; + else if (type === FuncType.SYNC) return 'SYNC'; + else if (type === FuncType.ASYNC) return 'ASYNC'; + else if (type === FuncType.PROMISE) return 'PROMISE'; + return 'UNKNOW'; +}; class NumberIncrease { } -NumberIncrease.num = 1 +NumberIncrease.num = 1; NumberIncrease.getAndIncrease = function () { return NumberIncrease.num++; -} +}; NumberIncrease.get = function () { return NumberIncrease.num; -} +}; NumberIncrease.reset = function () { - NumberIncrease.num = 1 -} + NumberIncrease.num = 1; +}; class InterfaceList { } InterfaceList.interfacess_ = []; InterfaceList.push = function (ifs) { - InterfaceList.interfacess_.push(ifs) -} + InterfaceList.interfacess_.push(ifs); +}; InterfaceList.pop = function () { - InterfaceList.interfacess_.pop() -} + InterfaceList.interfacess_.pop(); +}; InterfaceList.getValue = function (name) { - let ifs = InterfaceList.interfacess_[InterfaceList.interfacess_.length - 1] + let ifs = InterfaceList.interfacess_[InterfaceList.interfacess_.length - 1]; for (let i in ifs) { let vv = ifs[i]; if (ifs[i].name === name) { - var hasProperty = Object.prototype.hasOwnProperty.call(ifs[i].body, "allProperties") + var hasProperty = Object.prototype.hasOwnProperty.call(ifs[i].body, 'allProperties'); if (hasProperty) { return ifs[i].body.allProperties.values; } else { @@ -84,69 +84,69 @@ InterfaceList.getValue = function (name) { } } return null; -} +}; InterfaceList.getBody = function (name) { - let ifs = InterfaceList.interfacess_[InterfaceList.interfacess_.length - 1] + let ifs = InterfaceList.interfacess_[InterfaceList.interfacess_.length - 1]; for (let i in ifs) { if (ifs[i].name === name) { return ifs[i].body; } } return null; -} +}; class CallFunctionList { } CallFunctionList.callFuncs = []; CallFunctionList.push = function (ifs) { - CallFunctionList.callFuncs.push(ifs) -} + CallFunctionList.callFuncs.push(ifs); +}; CallFunctionList.pop = function () { - CallFunctionList.callFuncs.pop() -} + CallFunctionList.callFuncs.pop(); +}; CallFunctionList.getValue = function (name) { if (CallFunctionList.callFuncs.length === 0) { - return null + return null; } - let cfs = CallFunctionList.callFuncs[CallFunctionList.callFuncs.length - 1] + let cfs = CallFunctionList.callFuncs[CallFunctionList.callFuncs.length - 1]; if (cfs === undefined) { - return null + return null; } for (let i = 0; i < cfs.length; i++) { if (cfs[i].name === name) { - return [cfs[i].body, cfs[i].ret] - } + return [cfs[i].body, cfs[i].ret]; + } } - return null -} + return null; +}; CallFunctionList.getObjOnFuncName = function (interfaceName) { - let cfs = CallFunctionList.callFuncs[CallFunctionList.callFuncs.length - 1] - let funNames = [] + let cfs = CallFunctionList.callFuncs[CallFunctionList.callFuncs.length - 1]; + let funNames = []; for (let i = 0; i < cfs.length; i++) { if (cfs[i].name.indexOf(interfaceName) === 0) { - let funName = cfs[i].name.substring(interfaceName.length+1, cfs[i].name.length) - funNames.push(funName) - } + let funName = cfs[i].name.substring(interfaceName.length + 1, cfs[i].name.length); + funNames.push(funName); + } } - return funNames -} + return funNames; +}; class TypeList { } TypeList.types = []; TypeList.push = function (ifs) { - TypeList.types.push(ifs) -} + TypeList.types.push(ifs); +}; TypeList.pop = function () { - TypeList.types.pop() -} + TypeList.types.pop(); +}; TypeList.getValue = function (name) { - let ifs = TypeList.types[TypeList.types.length - 1] + let ifs = TypeList.types[TypeList.types.length - 1]; for (let i in ifs) { if (ifs[i].name === name) { - var hasProperty = Object.prototype.hasOwnProperty.call(ifs[i].body, "allProperties") + var hasProperty = Object.prototype.hasOwnProperty.call(ifs[i].body, 'allProperties'); if (hasProperty) { return ifs[i].body.allProperties.values; } else { @@ -155,192 +155,192 @@ TypeList.getValue = function (name) { } } return null; -} +}; class EnumList { } EnumList.enum_ = []; EnumList.push = function (ifs) { - EnumList.enum_.push(ifs) -} + EnumList.enum_.push(ifs); +}; EnumList.pop = function () { - EnumList.enum_.pop() -} + EnumList.enum_.pop(); +}; EnumList.getValue = function (name) { - let ifs = EnumList.enum_[EnumList.enum_.length - 1] + let ifs = EnumList.enum_[EnumList.enum_.length - 1]; for (let i in ifs) { if (ifs[i].name === name) { return ifs[i].body.element; } } return null; -} +}; function getArrayType(type) { - let tt = re.match("Array<([a-zA-Z_0-9]+)>", type) + let tt = re.match('Array<([a-zA-Z_0-9]+)>', type); if (tt !== null && tt !== undefined) { - return re.getReg(type, tt.regs[1]) - } - - tt = re.match("Array<{([[a-z:]+)([a-z:]]+)([a-zA-Z_1-9:]+)", type) + return re.getReg(type, tt.regs[1]); + } + + tt = re.match('Array<{([[a-z:]+)([a-z:]]+)([a-zA-Z_1-9:]+)', type); if (tt !== null && tt !== undefined) { - let res = '' - let len = tt.regs.length - for (let i=1; i]+)>", type) - let ttMap = re.search(",([a-zA-Z_0-9]+)>>", type) - let ttArray = re.search("Array<([a-zA-Z_0-9]+)>", type) - - if(ttArray === null) { - ttArray = re.search("([a-zA-Z_0-9]+)\\[\\]>", type) - } - - let valueType - let valueMapType - let valueArrayType + type = type.replace(/\s*/g, ''); + let ttKey = re.search('Map<([a-zA-Z_0-9]+),', type); + let ttValue = re.search(',([a-zA-Z_0-9<>]+)>', type); + let ttMap = re.search(',([a-zA-Z_0-9]+)>>', type); + let ttArray = re.search('Array<([a-zA-Z_0-9]+)>', type); + + if (ttArray === null) { + ttArray = re.search('([a-zA-Z_0-9]+)\\[\\]>', type); + } + + let valueType; + let valueMapType; + let valueArrayType; if (ttKey === null && ttValue === null && ttMap === null) { - ttKey = re.search("key:([a-zA-Z_0-9]+)", type) - ttValue = re.search(":([a-zA-Z_0-9]+)}", type) - ttMap = re.search(":([a-zA-Z_0-9]+)}}", type) - ttArray = re.search("Array<([a-zA-Z_0-9]+)>", type) + ttKey = re.search('key:([a-zA-Z_0-9]+)', type); + ttValue = re.search(':([a-zA-Z_0-9]+)}', type); + ttMap = re.search(':([a-zA-Z_0-9]+)}}', type); + ttArray = re.search('Array<([a-zA-Z_0-9]+)>', type); if (ttArray === null) { - ttArray = re.search(":([a-zA-Z_0-9]+)\\[\\]}", type) - } + ttArray = re.search(':([a-zA-Z_0-9]+)\\[\\]}', type); + } } - + if (ttValue !== null && ttValue !== undefined) { - valueType = re.getReg(type, ttValue.regs[1]) - if (valueType.indexOf("Array<") === 0) { - valueArrayType = re.getReg(valueType, ttArray.regs[1]) - valueType = undefined + valueType = re.getReg(type, ttValue.regs[1]); + if (valueType.indexOf('Array<') === 0) { + valueArrayType = re.getReg(valueType, ttArray.regs[1]); + valueType = undefined; } else if (ttMap !== undefined && ttMap !== null) { - valueMapType = re.getReg(type, ttMap.regs[1]) - valueType = undefined + valueMapType = re.getReg(type, ttMap.regs[1]); + valueType = undefined; } } if (ttMap !== null && ttMap !== undefined) { - valueMapType = re.getReg(type, ttMap.regs[1]) + valueMapType = re.getReg(type, ttMap.regs[1]); } if (ttArray !== null && ttArray !== undefined) { - valueArrayType = re.getReg(type, ttArray.regs[1]) + valueArrayType = re.getReg(type, ttArray.regs[1]); } - return [re.getReg(type, ttKey.regs[1]), valueType, valueMapType, valueArrayType] + return [re.getReg(type, ttKey.regs[1]), valueType, valueMapType, valueArrayType]; } function getUnionType(type) { - type = type.replace(/\s*/g,"") - var typeArr = new Array() - typeArr = type.split("|") - return typeArr + type = type.replace(/\s*/g, ''); + var typeArr = new Array(); + typeArr = type.split('|'); + return typeArr; } function isFuncType(type) { - let isFunction = false; + let isFunction = false; if (type === null || type === undefined) { return isFunction; } - + if (type === 'function' || type === 'Function') { isFunction = true; return isFunction; @@ -349,30 +349,30 @@ function isFuncType(type) { function isRegisterFunc(name) { let regIndex = name.indexOf('register'); - let isRegister = false + let isRegister = false; if (regIndex === 0) { - isRegister = true + isRegister = true; } - return isRegister + return isRegister; } function isUnRegisterFunc(name) { let unRegIndex = name.indexOf('unRegister'); - let isRegister = false + let isRegister = false; if (unRegIndex === 0) { - isRegister = true + isRegister = true; } - return isRegister + return isRegister; } function isOnObjCallback(name) { let regIndex = name.indexOf('on'); - let flag = false + let flag = false; let onLen = 2; if (regIndex === 0 && name.length > onLen) { - flag = true + flag = true; } - return flag + return flag; } // 箭头函数,如funTest(cb: (wid: boolean) => void): string; @@ -387,7 +387,7 @@ function isArrowFunc(type) { function isOnOffRegisterFunc(name) { let flag = false; if (name === 'on' || name === 'off' || isRegisterFunc(name) || isUnRegisterFunc(name) || - isOnObjCallback(name)) { + isOnObjCallback(name)) { flag = true; } return flag; @@ -395,53 +395,53 @@ function isOnOffRegisterFunc(name) { function isCreateThreadsafeFunc(name) { let index = name.indexOf('createThreadSafeFunc'); - let isTdSafeFunc = false + let isTdSafeFunc = false; if (index === 0) { - isTdSafeFunc = true + isTdSafeFunc = true; } - return isTdSafeFunc + return isTdSafeFunc; } function getOnObjCallbackType(funcName, interName) { - let onObjCbType = '' + let onObjCbType = ''; if (interName !== '') { - onObjCbType = interName + '_' + funcName + onObjCbType = interName + '_' + funcName; } else { - onObjCbType = funcName + onObjCbType = funcName; } - return 'AUTO_CALLFUNCTION_' + onObjCbType + return 'AUTO_CALLFUNCTION_' + onObjCbType; } function getOnCallbackFunAndInterName(CallbackType) { - CallbackType = CallbackType.replaceAll('AUTO_CALLFUNCTION_', '') - let CallbackTypes = CallbackType.split('_') + CallbackType = CallbackType.replaceAll('AUTO_CALLFUNCTION_', ''); + let CallbackTypes = CallbackType.split('_'); let funcName = CallbackTypes[1]; let interName = CallbackTypes[0]; - return [interName, funcName] -} - -class jsonCfgList { } -jsonCfgList.jsonCfg = []; -jsonCfgList.push = function (ifs) { - jsonCfgList.jsonCfg.push(ifs) -} -jsonCfgList.pop = function () { - jsonCfgList.jsonCfg.pop() -} -jsonCfgList.getValue = function (className, inter) { - let ifs = jsonCfgList.jsonCfg[jsonCfgList.jsonCfg.length - 1] + return [interName, funcName]; +} + +class JsonCfgList { } +JsonCfgList.jsonCfg = []; +JsonCfgList.push = function (ifs) { + JsonCfgList.jsonCfg.push(ifs); +}; +JsonCfgList.pop = function () { + JsonCfgList.jsonCfg.pop(); +}; +JsonCfgList.getValue = function (className, inter) { + let ifs = JsonCfgList.jsonCfg[JsonCfgList.jsonCfg.length - 1]; for (let i in ifs) { if (ifs[i].interfaceName.className === className && ifs[i].interfaceName.funcName === inter) { - return ifs[i].serviceCode + return ifs[i].serviceCode; } } return null; -} +}; function getLogErrInfo() { - let errInfo = " Please refer to for support capacity:" - + "https://gitee.com/openharmony/napi_generator/tree/master/release-notes" - return errInfo + let errInfo = ' Please refer to for support capacity:' + + 'https://gitee.com/openharmony/napi_generator/tree/master/release-notes'; + return errInfo; } module.exports = { @@ -464,12 +464,12 @@ module.exports = { getUnionType, isFuncType, isArrowFunc, - jsonCfgList, + jsonCfgList: JsonCfgList, isRegisterFunc, isUnRegisterFunc, isOnObjCallback, isOnOffRegisterFunc, getOnObjCallbackType, getLogErrInfo, - isCreateThreadsafeFunc -} \ No newline at end of file + isCreateThreadsafeFunc, +}; \ No newline at end of file diff --git a/src/cli/dts2cpp/src/gen/tools/re.js b/src/cli/dts2cpp/src/gen/tools/re.js index d1279519..6ee3f992 100644 --- a/src/cli/dts2cpp/src/gen/tools/re.js +++ b/src/cli/dts2cpp/src/gen/tools/re.js @@ -15,18 +15,18 @@ const path = require('path'); function search(ss, data) { - ss = replaceAll(ss, "\\.", "\\.") + ss = replaceAll(ss, '\\.', '\\.'); let reg = new RegExp(ss); let tt = reg.exec(data); if (tt == null) return null; - let ret = { "regs": [] } + let ret = { 'regs': [] }; for (let i = 0; i < tt.length; i++) { let p = data.indexOf(tt[i]); if (tt[i] == null) { - ret["regs"].push([-1, -1]) + ret['regs'].push([-1, -1]); } else { - ret["regs"].push([p, p + tt[i].length]) + ret['regs'].push([p, p + tt[i].length]); } } @@ -34,17 +34,19 @@ function search(ss, data) { } function match(ss, data) { - let tt = search(ss, data) - if (tt !== null && tt !== undefined && tt.regs[0][0] == 0) return tt; + let tt = search(ss, data); + if (tt !== null && tt !== undefined && tt.regs[0][0] == 0) { + return tt; + } return null; } function removeReg(data, reg) { - return data.substring(0, reg[0]) + data.substring(reg[1], data.length) + return data.substring(0, reg[0]) + data.substring(reg[1], data.length); } function getReg(data, reg) { - return data.substring(reg[0], reg[1]) + return data.substring(reg[0], reg[1]); } function getFileInPath(tpath) { @@ -56,15 +58,15 @@ function getPathInPath(tpath) { } function all(sfrom) { - return new RegExp(sfrom, "g"); + return new RegExp(sfrom, 'g'); } function replaceAll(ss, sfrom, sto) { - return ss.replace(all(sfrom), sto) + return ss.replace(all(sfrom), sto); } function pathJoin(...args) { - return path.join(...args) + return path.join(...args); } module.exports = { @@ -76,5 +78,5 @@ module.exports = { getPathInPath, pathJoin, replaceAll, - all -} \ No newline at end of file + all, +}; \ No newline at end of file diff --git a/src/cli/dts2cpp/src/gen/tools/tool.js b/src/cli/dts2cpp/src/gen/tools/tool.js index f2d2a3c7..708dcd29 100644 --- a/src/cli/dts2cpp/src/gen/tools/tool.js +++ b/src/cli/dts2cpp/src/gen/tools/tool.js @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const re = require("./re"); +const re = require('./re'); let vscode = null; try { vscode = require('vscode'); @@ -22,9 +22,9 @@ catch (err) { } const NUM_CONST_MAP = new Map([ - [0, "XNapiTool::ZERO"], [1, "XNapiTool::ONE"], [2, "XNapiTool::TWO"], [3, "XNapiTool::THREE"], - [4, "XNapiTool::FOUE"], [5, "XNapiTool::FIVE"], [6, "XNapiTool::SIX"], [7, "XNapiTool::SEVEN"], - [8, "XNapiTool::EIGHT"], [9, "XNapiTool::NINE"] + [0, 'XNapiTool::ZERO'], [1, 'XNapiTool::ONE'], [2, 'XNapiTool::TWO'], [3, 'XNapiTool::THREE'], + [4, 'XNapiTool::FOUE'], [5, 'XNapiTool::FIVE'], [6, 'XNapiTool::SIX'], [7, 'XNapiTool::SEVEN'], + [8, 'XNapiTool::EIGHT'], [9, 'XNapiTool::NINE'] ]); function print(...args) { @@ -36,52 +36,55 @@ function print(...args) { 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; result = result.substring(0, p) + args[i] + result.substring(p + 2, result.length) } return result; -} +}; String.prototype.replaceAll = function (...args) { let result = this; while (result.indexOf(args[0]) >= 0) { - result = result.replace(args[0], args[1]) + result = result.replace(args[0], args[1]); } return result; -} +}; function checkOutBody(body, off, flag, binside) { off = off || 0; - flag = flag || ["{", "}"]; + flag = flag || ['{', '}']; binside = binside || false; let idx = { - "(": ")", - "{": "}", - "<": ">", - //"<": "<", - //">": ">", + '(': ')', + '{': '}', + '<': '>', + //'<': '<', + //'>': '>', }; let csl = {}; let csr = {}; for (let f in idx) { - csl[f] = 0 - csr[idx[f]] = 0 + csl[f] = 0; + csr[idx[f]] = 0; } - let cs1 = 0 + let cs1 = 0; if (flag[0].length > 0 && body.substring(off, off + flag[0].length) !== flag[0]) { return null; } for (let i = off + flag[0].length; i < body.length; i++) { - if (body[i] === '"') cs1 += 1 + if (body[i] === '"') { + cs1 += 1; + } if (cs1 % 2 === 0) { let tb1 = getTb1(csl, csr, idx); if (tb1 && body.substring(i, i + flag[1].length) === flag[1]) { - if (binside) + if (binside) { return body.substring(off + flag[0].length, i); + } return body.substring(off, i + flag[1].length); } checkOutBody2(body, i, csl, csr); @@ -91,122 +94,122 @@ function checkOutBody(body, off, flag, binside) { } function checkOutBody2(body, i, csl, csr) { - if (body[i] in csl) { - csl[body[i]] += 1; - if (body[i] in csr) { - csr[body[i]] += 1; + if (body[i] in csl) { + csl[body[i]] += 1; + if (body[i] in csr) { + csr[body[i]] += 1; + } } - } - if (body[i] in csr) { - if (!(body[i] === '>' && body[i - 1] === '=')) { // 尖括号匹配时忽略关键字 "=>" - csr[body[i]] += 1; + if (body[i] in csr) { + if (!(body[i] === '>' && body[i - 1] === '=')) { // 尖括号匹配时忽略关键字 "=>" + csr[body[i]] += 1; + } } - } } function getTb1(csl, csr, idx) { - let tb1 = true; - for (let k in csl) { - if (csl[k] !== csr[idx[k]]) { - tb1 = false; - break; + let tb1 = true; + for (let k in csl) { + if (csl[k] !== csr[idx[k]]) { + tb1 = false; + break; + } } - } - return tb1; + return tb1; } function removeExplains(data) { // 去除 /** */ 类型的注释 - while (data.indexOf("/*") >= 0) { - let i1 = data.indexOf("/*") - let i2 = data.indexOf("*/") + 2 - data = data.substring(0, i1) + data.substring(i2, data.length) + while (data.indexOf('/*') >= 0) { + let i1 = data.indexOf('/*'); + let i2 = data.indexOf('*/') + 2; + data = data.substring(0, i1) + data.substring(i2, data.length); } // 去除 namespace 域外 // 类型的注释 // 如果换行格式是\r\n, 去除\r, 统一成\n格式 - while (data.indexOf("\r") >= 0) { - data = data.replace("\r", "") + while (data.indexOf('\r') >= 0) { + data = data.replace('\r', ''); } - while (data.indexOf("//") >= 0) { - let i1 = data.indexOf("//") - let i2 = data.indexOf("\n") - let end = data.indexOf("declare namespace ") + while (data.indexOf('//') >= 0) { + let i1 = data.indexOf('//'); + let i2 = data.indexOf('\n'); + let end = data.indexOf('declare namespace '); while (i2 < end && i1 < end) { while (i1 > i2) { - data = data.substring(0, i2) + data.substring(i2 + 2, data.length) - i2 = data.indexOf("\n") - i1 = data.indexOf("//") - } - data = data.substring(0, i1) + data.substring(i2 + 1, data.length) - i1 = data.indexOf("//") - i2 = data.indexOf("\n") - end = data.indexOf("declare namespace ") + data = data.substring(0, i2) + data.substring(i2 + 2, data.length); + i2 = data.indexOf('\n'); + i1 = data.indexOf('//'); + } + data = data.substring(0, i1) + data.substring(i2 + 1, data.length); + i1 = data.indexOf('//'); + i2 = data.indexOf('\n'); + end = data.indexOf('declare namespace '); } if (i2 > end || i1 > end) { break; } } - return data + return data; } function getLicense(data) { - while (data.indexOf("/*") >= 0) { - let i1 = data.indexOf("/*") - let i2 = data.indexOf("*/") + 2 - let licenseData = data.substring(i1, i2) - if (licenseData.search("Copyright") !== -1) { - return licenseData + while (data.indexOf('/*') >= 0) { + let i1 = data.indexOf('/*'); + let i2 = data.indexOf('*/') + 2; + let licenseData = data.substring(i1, i2); + if (licenseData.search('Copyright') !== -1) { + return licenseData; } else { - return null + return null; } } } function removeEmptyLine(data) { - while (data.indexOf("\r") >= 0) { - data = data.replace("\r", "") + while (data.indexOf('\r') >= 0) { + data = data.replace('\r', ''); } - while (data.indexOf("\t") >= 0) { - data = data.replace("\t", "") + while (data.indexOf('\t') >= 0) { + data = data.replace('\t', ''); } - while (data.indexOf(" \n") >= 0) { - data = data.replace(" \n", "\n") + while (data.indexOf(' \n') >= 0) { + data = data.replace(' \n', '\n'); } - while (data.indexOf("\n ") >= 0) { - data = data.replace("\n ", "\n") + while (data.indexOf('\n ') >= 0) { + data = data.replace('\n ', '\n'); } - while (data.indexOf("\n\n") >= 0) { - data = data.replace("\n\n", "\n") + while (data.indexOf('\n\n') >= 0) { + data = data.replace('\n\n', '\n'); } - while (data.indexOf("\n") === 0) { - data = data.substring(1, data.length) + while (data.indexOf('\n') === 0) { + data = data.substring(1, data.length); } - while (data.indexOf(" ") === 0) { - data = data.substring(1, data.length) + while (data.indexOf(' ') === 0) { + data = data.substring(1, data.length); } - return data + return data; } function replaceTab(data) { - while (data.indexOf("\t") >= 0) { - data = data.replace("\t", " ") + while (data.indexOf('\t') >= 0) { + data = data.replace('\t', ' '); } - return data + return data; } function removeEmptyLine2(data) { - while (data.indexOf(" \n")) - data = data.replace(" \n", "\n") - while (data.indexOf("\n\n\n")) - data = data.replace("\n\n\n", "\n\n") - return data + while (data.indexOf(' \n')); + data = data.replace(' \n', '\n'); + while (data.indexOf('\n\n\n')); + data = data.replace('\n\n\n', '\n\n'); + return data; } function replaceAll(s, sfrom, sto) { while (s.indexOf(sfrom) >= 0) { - s = s.replace(sfrom, sto) + s = s.replace(sfrom, sto); } return s; } @@ -217,20 +220,20 @@ function replaceAll(s, sfrom, sto) { * @param func2 方法2 * @returns 方法名称与形参是否完全相同 */ - function isSameFunc(func1, func2) { +function isSameFunc(func1, func2) { if (func1.name !== func2.name) { // 判断方法名称是否相同 return false; } - let func1ParamCount = func1.value.length + let func1ParamCount = func1.value.length; if (func1ParamCount !== func2.value.length) { // 判断方法形参个数是否一样 return false; } for (let i in func1.value) { // 判断方法每个形参数据类型是否相同 - if (func1.value[i].type !== func2.value[i].type) { - if (!(func1.value[i].type.indexOf("NUMBER_TYPE_") >= 0 && - func2.value[i].type.indexOf("NUMBER_TYPE_") >= 0)) { + if (func1.value[i].type !== func2.value[i].type) { + if (!(func1.value[i].type.indexOf('NUMBER_TYPE_') >= 0 && + func2.value[i].type.indexOf('NUMBER_TYPE_') >= 0)) { return false; } } @@ -246,14 +249,14 @@ function replaceAll(s, sfrom, sto) { * @param list 目标列表 * @returns 是否成功插入列表 */ - function addUniqFunc2List(obj, list) { +function addUniqFunc2List(obj, list) { for (let i in list) { if (isSameFunc(obj, list[i])) { - return false + return false; } } - list.push(obj) - return true + list.push(obj); + return true; } /** @@ -262,11 +265,11 @@ function replaceAll(s, sfrom, sto) { * @param childFunclist 子类全部方法列表 * @returns void */ - function setOverrideFunc(parentFunc, childFunclist) { +function setOverrideFunc(parentFunc, childFunclist) { for (let i in childFunclist) { if (isSameFunc(parentFunc, childFunclist[i])) { - childFunclist[i].isOverride = true - return + childFunclist[i].isOverride = true; + return; } } } @@ -277,13 +280,13 @@ function replaceAll(s, sfrom, sto) { * @param list 目标列表 * @returns void */ - function addUniqObj2List(obj, list) { +function addUniqObj2List(obj, list) { for (let i in list) { if (list[i].name === obj.name) { - return + return; } } - list.push(obj) + list.push(obj); } /** @@ -292,17 +295,17 @@ function replaceAll(s, sfrom, sto) { * @param funcInfo 方法信息 * return tabStr 缩进,staticStr 静态函数关键词,virtualStr 虚函数关键词, overrideStr 重写关键词 */ - function getPrefix(data, funcInfo) { - let isStatic = funcInfo.isStatic - let tabStr = "" - let virtualStr = "" - let staticStr = isStatic ? "static " : "" +function getPrefix(data, funcInfo) { + let isStatic = funcInfo.isStatic; + let tabStr = ''; + let virtualStr = ''; + let staticStr = isStatic ? 'static ' : ''; if (data.childList) { - tabStr = " " // 类中的方法增加一个缩进 - virtualStr = (data.childList.length > 0 && !isStatic) ? "virtual " : "" //如果是基类中的非静态方法,定义为虚函数 + tabStr = ' ' // 类中的方法增加一个缩进 + virtualStr = (data.childList.length > 0 && !isStatic) ? 'virtual ' : '' //如果是基类中的非静态方法,定义为虚函数 } - let overrideStr = funcInfo.isOverride ? " override" : "" // 重写了父类方法,需要加上override关键字,否则触发c++门禁告警 - return [tabStr, staticStr, virtualStr, overrideStr] + let overrideStr = funcInfo.isOverride ? ' override' : '' // 重写了父类方法,需要加上override关键字,否则触发c++门禁告警 + return [tabStr, staticStr, virtualStr, overrideStr]; } function getConstNum(num) { @@ -322,5 +325,5 @@ module.exports = { addUniqFunc2List, getPrefix, getConstNum, - setOverrideFunc -} + setOverrideFunc, +}; -- Gitee From b8dbef4478873f53bb0379f19b603e217ece69b1 Mon Sep 17 00:00:00 2001 From: LiYuxi Date: Thu, 11 Jul 2024 11:52:23 +0800 Subject: [PATCH 05/12] modify analyze/ Signed-off-by: LiYuxi --- src/cli/dts2cpp/src/gen/analyze/enum.js | 78 ++-- src/cli/dts2cpp/src/gen/analyze/function.js | 268 +++++++------- src/cli/dts2cpp/src/gen/analyze/interface.js | 121 ++++--- src/cli/dts2cpp/src/gen/analyze/namespace.js | 360 ++++++++++--------- src/cli/dts2cpp/src/gen/analyze/params.js | 114 +++--- src/cli/dts2cpp/src/gen/analyze/return.js | 14 +- src/cli/dts2cpp/src/gen/analyze/type.js | 112 +++--- 7 files changed, 544 insertions(+), 523 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/analyze/enum.js b/src/cli/dts2cpp/src/gen/analyze/enum.js index 92f2bfd8..03f9a829 100644 --- a/src/cli/dts2cpp/src/gen/analyze/enum.js +++ b/src/cli/dts2cpp/src/gen/analyze/enum.js @@ -12,80 +12,80 @@ * 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代表字符串 + enumValueType: 0, // 0代表数字,1代表字符串 } for (let i in body) { - let bodyContent = body[i] + let bodyContent = body[i]; while (bodyContent.length > 0 && bodyContent[0] === ' ') { - bodyContent = bodyContent.substring(1, bodyContent.length) + bodyContent = bodyContent.substring(1, bodyContent.length); } while (bodyContent.length > 0 && bodyContent[-1] === ' ') { - bodyContent = bodyContent.substring(0, bodyContent.length - 1) + bodyContent = bodyContent.substring(0, bodyContent.length - 1); } - if (bodyContent === "") { - break + 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 + type: 'string', + }); + 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 + type: 'string', + }); + 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 + analyzeEnumResult, +}; \ 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 82fc133f..80b1e253 100644 --- a/src/cli/dts2cpp/src/gen/analyze/function.js +++ b/src/cli/dts2cpp/src/gen/analyze/function.js @@ -13,8 +13,8 @@ * limitations under the License. */ const re = require('../tools/re'); -const { FuncType, NumberIncrease, isEnum, EnumValueType, enumIndex, isType, typeIndex, isOnObjCallback, - getOnObjCallbackType, getLogErrInfo } = require('../tools/common'); +const { FuncType, NumberIncrease, isEnum, EnumValueType, enumIndex, isType, typeIndex, isOnObjCallback, + getOnObjCallbackType, getLogErrInfo } = require('../tools/common'); const { analyzeParams } = require('./params'); const { analyzeReturn } = require('./return'); const { NapiLog } = require('../tools/NapiLog'); @@ -22,177 +22,183 @@ const { randomInt } = require('crypto'); const { print } = require('../tools/tool'); function analyzeSubInterface(data) { - let body = re.replaceAll(data, '\n', '').split(';') // # replace(' ', ''). + let body = re.replaceAll(data, '\n', '').split(';'); // # replace(' ', ''). let result = { value: [], function: [], parentNameList: [], childList: [], - parentList: [] - } + parentList: [], + }; for (let i in body) { - let t = body[i] - 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]; + // 去除前面的空格 + 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) { // 变量 analyzeSubInterfaceVal(t, tt, result); } } - return result + return result; } function analyzeSubInterfaceVal(t, tt, result) { - let valueName = re.getReg(t, tt.regs[1]); - let valueType = re.getReg(t, tt.regs[2]); - let index = valueType.indexOf('number'); - while (index !== -1) { - valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); - index = valueType.indexOf('number'); - } - result.value.push({ - name: valueName, - type: valueType - }); + let valueName = re.getReg(t, tt.regs[1]); + let valueType = re.getReg(t, tt.regs[2]); + let index = valueType.indexOf('number'); + while (index !== -1) { + valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); + index = valueType.indexOf('number'); + } + result.value.push({ + name: valueName, + type: valueType, + }); } function getFuncParaType(v, interfaceName, data, results) { - let arrayType = re.match('(Async)*Callback<(Array<([a-zA-Z_0-9]+)>)>', v.type) - let parameter = v.type + let arrayType = re.match('(Async)*Callback<(Array<([a-zA-Z_0-9]+)>)>', v.type); + let parameter = v.type; if (arrayType) { - parameter = re.getReg(v.type, arrayType.regs[2]) + 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()) + v.type = v.type.replace(parameter, 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); } else if (data.enum[index].body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_STRING) { - v.type = v.type.replace(parameter, 'string') + v.type = v.type.replace(parameter, 'string'); } 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) + else if (isEnum(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 + v.type = v.type.replace(parameter, 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); + v.realType = v.type; } else if (results.enum[index].body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_STRING) { - v.type = v.type.replace(parameter, 'string') + v.type = v.type.replace(parameter, 'string'); } else { - NapiLog.logError('analyzeFunction getFuncParaType is not support this type %s.' - .format(results.enum[index].body.enumValueType), getLogErrInfo()); - return null - } + NapiLog.logError('analyzeFunction getFuncParaType is not support this type %s.' + .format(results.enum[index].body.enumValueType), getLogErrInfo()); + 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) - if (data.type[index].isEnum) { - v.type = v.type.replace(parameter, 'string') - } + let index = typeIndex(parameter, data); + if (data.type[index].isEnum) { + 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 = '' - 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) + 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); 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) - }) + body: analyzeSubInterface(interfaceBody), + }); } else if (Object.prototype.hasOwnProperty.call(results, 'interface')) { results.interface.push({ name: interfaceName, - body: analyzeSubInterface(interfaceBody) - }) - } + body: analyzeSubInterface(interfaceBody), + }); + } } - matchs = re.match(matchNoName, values) - if(matchs) { - let resNoNameInter = analyzeFuncNoNameInterface(data, values) - values = resNoNameInter.values + matchs = re.match(matchNoName, values); + if (matchs) { + let resNoNameInter = analyzeFuncNoNameInterface(data, values); + values = resNoNameInter.values; } let result = { interfaceName: interfaceName, - values: values - } - return result + values: values, + }; + 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 = '' - 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) { @@ -200,8 +206,8 @@ function getObjCallFunc(results, onObjCbType, values, ret) { results.callFunction.push({ 'name': onObjCbType, 'body': values, - 'ret': ret - }) + 'ret': ret, + }); } } function getFuncResult(name, funcType, values, ret, isStatic) { @@ -210,67 +216,67 @@ function getFuncResult(name, funcType, values, ret, isStatic) { type: funcType, value: values, ret: ret, - isStatic: isStatic - } - return result + isStatic: isStatic, + }; + return result; } function getArrowCallFunc(tmp, results) { - let callbackFunc = null + let callbackFunc = null; if (tmp[2][0] !== undefined) { 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) - paramType = paramType.replace(paramAsync, paramTypeVal); + // 匿名interface处理 + 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) - } - return result + let onObjCbType = getOnObjCallbackType(name, interfaceName); + getObjCallFunc(results, onObjCbType, values, ret); + } + return result; } module.exports = { @@ -278,5 +284,5 @@ module.exports = { analyzeSubInterface, getFuncParaType, analyzeFuncNoNameInterface, - analyseSubReturn -} \ No newline at end of file + analyseSubReturn, +}; \ 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 158a8114..86c5f784 100644 --- a/src/cli/dts2cpp/src/gen/analyze/interface.js +++ b/src/cli/dts2cpp/src/gen/analyze/interface.js @@ -19,99 +19,108 @@ 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 + body: analyzeInterface(interfaceBody, rsltInterface), + }); + valueType = interfaceTypeName; } - return valueType + return valueType; } /* 去除单行注释// */ function parseNotes(data) { - let notes = data.indexOf('//') >= 0 ? data.substring(data.indexOf('//'), data.length) : ''; - while(notes !== '') { - notes = notes.substring(0, notes.indexOf('\n')); + let notes = data.indexOf('//') >= 0 ? data.substring(data.indexOf('//'), data.length) : ''; + while (notes !== '') { + notes = notes.substring(0, notes.indexOf('\n')); data = data.replace(notes, ''); - notes = '' + notes = ''; let st = data.indexOf('//'); - if(st >= 0) { + 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: [] - } + 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); + } + // 如果t为空直接返回 + if (t === '') { + break; + } + let tt = re.match(' *([a-zA-Z0-9_]+)(\\?*)*: *([a-zA-Z_0-9<>,:{}[\\]| ]+)', t); if (tt && t.indexOf('=>') < 0) { // 接口成员变量, 但不包括带'=>'的成员,带'=>'的接口成员需要按函数处理 analyzeInterfaceVariable(t, tt, rsltInterface, result); } - tt = re.match("(static )* *(\\$*[A-Za-z0-9_]+) *[:]? *\\(([\n 'a-zA-Z\'\'\"\":;=,_0-9?<>{}()=>|[\\]]*)\\)" - + ' *(:|=>)? *([A-Za-z0-9_<>{}:;, .[\\]]+)?', t) + tt = re.match('(static )* *(\\$*[A-Za-z0-9_]+) *[:]? *\\(([\n \'a-zA-Z\'\'\"\":;=,_0-9?<>{}()=>|[\\]]*)\\)' + + ' *(:|=>)? *([A-Za-z0-9_<>{}:;, .[\\]]+)?', t); if (tt) { // 接口函数成员 analyzeInterfaceFunction(t, tt, data, results, interfaceName, result); } } - return result + return result; } module.exports = { analyzeInterface, - parseNotes -} + parseNotes, +}; function analyzeInterfaceFunction(t, tt, data, results, interfaceName, result) { - let ret = re.getReg(t, tt.regs[5]) === '' ? 'void' : re.getReg(t, tt.regs[5]); - let funcDetail = analyzeFunction(data, re.getReg(t, tt.regs[1]) !== '', re.getReg(t, tt.regs[2]), - re.getReg(t, tt.regs[3]), ret, results, interfaceName); - if (funcDetail !== null && funcDetail !== undefined) { - // 完全一样的方法不重复添加 (如同名同参的AsyncCallback和Promise方法) - addUniqFunc2List(funcDetail, result.function); - } + let ret = re.getReg(t, tt.regs[5]) === '' ? 'void' : re.getReg(t, tt.regs[5]); + let funcDetail = analyzeFunction(data, re.getReg(t, tt.regs[1]) !== '', re.getReg(t, tt.regs[2]), + re.getReg(t, tt.regs[3]), ret, results, interfaceName); + if (funcDetail !== null && funcDetail !== undefined) { + // 完全一样的方法不重复添加 (如同名同参的AsyncCallback和Promise方法) + addUniqFunc2List(funcDetail, result.function); + } } function analyzeInterfaceVariable(t, tt, rsltInterface, result) { - let valueName = re.getReg(t, tt.regs[1]); - let valueType = re.getReg(t, tt.regs[3]); - let index = valueType.indexOf('number'); - let optionalFlag = re.getReg(t, tt.regs[2]) === '?' ? true : false; - while (index !== -1) { - valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); - index = valueType.indexOf('number'); - } - valueType = analyzeNoNameInterface(valueType, valueName, rsltInterface); - result.value.push({ - name: valueName, - type: valueType, - realType: valueType, - optional: optionalFlag - }); + let valueName = re.getReg(t, tt.regs[1]); + let valueType = re.getReg(t, tt.regs[3]); + let index = valueType.indexOf('number'); + let optionalFlag = re.getReg(t, tt.regs[2]) === '?' ? true : false; + while (index !== -1) { + valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); + index = valueType.indexOf('number'); + } + valueType = analyzeNoNameInterface(valueType, valueName, rsltInterface); + result.value.push({ + name: valueName, + type: valueType, + realType: valueType, + optional: optionalFlag, + }); } diff --git a/src/cli/dts2cpp/src/gen/analyze/namespace.js b/src/cli/dts2cpp/src/gen/analyze/namespace.js index 221fff1a..7b639ca8 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解析 */ @@ -49,40 +49,42 @@ function analyzeNamespace(data) { 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,215 +93,215 @@ 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] - if(!isValidValue(interf)) { - NapiLog.logError("parseEnumType interf is null!"); - return null; - } - - // function 匹配 - for (let j in interf.body.function) { - let func = interf.body.function[j]; - if(!isValidValue(func)) { - NapiLog.logError("parseEnumType func is null!"); + let interf = result.interface[i]; + if (!isValidValue(interf)) { + NapiLog.logError('parseEnumType interf is null!'); return null; } - - // 参数匹配 - for (let k in func.value) { - let v = func.value[k]; - if(!isValidValue(v)) { - NapiLog.logError("parseEnumType func.value is null!"); + + // function 匹配 + for (let j in interf.body.function) { + let func = interf.body.function[j]; + if (!isValidValue(func)) { + NapiLog.logError('parseEnumType func is null!'); return null; } - if (v.type === enumm.name) { - if (enumm.body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_NUMBER) { - v.type = "NUMBER_TYPE_" + NumberIncrease.getAndIncrease(); - } else if (enumm.body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_STRING) { - v.type = "string"; - } else { - NapiLog.logError("parseEnumType for interface function value is not support this type %s." - .format(enumm.body.enumValueType), getLogErrInfo()); + // 参数匹配 + for (let k in func.value) { + let v = func.value[k]; + if (!isValidValue(v)) { + NapiLog.logError('parseEnumType func.value is null!'); return null; } - result.interface[i].body.function[j].value[k].type = v.type; - } + + if (v.type === enumm.name) { + if (enumm.body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_NUMBER) { + v.type = 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease(); + } else if (enumm.body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_STRING) { + v.type = 'string'; + } else { + NapiLog.logError('parseEnumType for interface function value is not support this type %s.' + .format(enumm.body.enumValueType), getLogErrInfo()); + return null; + } + result.interface[i].body.function[j].value[k].type = v.type; + } + } } - } } } - 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) + body: analyzeNamespace(namespaceBody), + }); + 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) + body: analyzeEnum(enumBody.substring(1, enumBody.length - 1)), + }); + 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]) + body: re.getReg(data, matchs.regs[2]), + }); + 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) { if (value === null || value === undefined) { - return false; + return false; } return true; } 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 - }) + 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 +313,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; } /** @@ -341,72 +343,72 @@ function getParentNameList(firstKey, secondKey, parentStr) { * @param result 解析后的ts数据结构 * @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 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 = [] - if(extendsParent !== '') { - bodyObj.parentNameList = getParentNameList("extends", "implements", extendsParent) +function createInterfaceData(matchs, data, result) { + 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 = []; + if (extendsParent !== '') { + bodyObj.parentNameList = getParentNameList('extends', 'implements', extendsParent); } - if(implementParent !== '') { - bodyObj.parentNameList = getParentNameList("implements", "extends", implementParent) + if (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) + 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); 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, @@ -415,5 +417,5 @@ module.exports = { parseFunction, parseInterface, parseClass, - parseType -} \ No newline at end of file + parseType, +}; \ 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 42498551..a5298d81 100644 --- a/src/cli/dts2cpp/src/gen/analyze/params.js +++ b/src/cli/dts2cpp/src/gen/analyze/params.js @@ -12,15 +12,15 @@ * 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 || - isFuncType(type) || isArrowFunc(type)) { + if (funcType === FuncType.DIRECT && type.indexOf('Callback') >= 0 && type.indexOf('AsyncCallback') < 0 || + isFuncType(type) || isArrowFunc(type)) { isSync = true; } return isSync; @@ -33,64 +33,64 @@ function isSyncFuncType(type, funcType) { * @param {*} rsltCallFunction 解析结果 */ 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 functionRet = re.getReg(valueType, matchs.regs[2]); - let functionBody = re.getReg(valueType, matchs.regs[1]); - - 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 number = NumberIncrease.getAndIncrease(); + 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]; + 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(); + } } - } - rsltCallFunction.push({ - "name": functionTypeName, - "body": bodyRes, - "ret": functionRet - }) - valueType = functionTypeName - } - return valueType + rsltCallFunction.push({ + 'name': functionTypeName, + 'body': bodyRes, + 'ret': functionRet, + }); + valueType = functionTypeName; + } + 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 -} + analyzeParams, +}; diff --git a/src/cli/dts2cpp/src/gen/analyze/return.js b/src/cli/dts2cpp/src/gen/analyze/return.js index 1fec3b3a..9ca095f2 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 + analyzeReturn, +}; \ 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 66c1eb4a..8633deae 100644 --- a/src/cli/dts2cpp/src/gen/analyze/type.js +++ b/src/cli/dts2cpp/src/gen/analyze/type.js @@ -17,101 +17,105 @@ const { NumberIncrease } = require('../tools/common'); /* 去除单行注释// */ function parseNotes(data) { - let notes = data.indexOf('//') >= 0 ? data.substring(data.indexOf('//'), data.length) : ''; - while(notes !== '') { - notes = notes.substring(0, notes.indexOf('\n')); + let notes = data.indexOf('//') >= 0 ? data.substring(data.indexOf('//'), data.length) : ''; + while (notes !== '') { + notes = notes.substring(0, notes.indexOf('\n')); data = data.replace(notes, ''); - notes = '' + notes = ''; let st = data.indexOf('//'); - if(st >= 0) { + if (st >= 0) { 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] - 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]; + 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; + } + 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) { - let valueName = re.getReg(t, tt.regs[1]); - let valueType = re.getReg(t, tt.regs[3]); - let index = valueType.indexOf('number'); - let optionalFlag = re.getReg(t, tt.regs[2]) === '?' ? true : false; - while (index !== -1) { - valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); - index = valueType.indexOf('number'); - } - result.value.push({ - name: valueName, - type: valueType, - optional: optionalFlag - }); + let valueName = re.getReg(t, tt.regs[1]); + let valueType = re.getReg(t, tt.regs[3]); + let index = valueType.indexOf('number'); + let optionalFlag = re.getReg(t, tt.regs[2]) === '?' ? true : false; + while (index !== -1) { + valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); + index = valueType.indexOf('number'); + } + result.value.push({ + name: valueName, + type: valueType, + optional: optionalFlag, + }); } 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] + let bodyContent = body[i]; while (bodyContent.length > 0 && bodyContent[0] === ' ') { - bodyContent = bodyContent.substring(1, bodyContent.length) + bodyContent = bodyContent.substring(1, bodyContent.length); } while (bodyContent.length > 0 && bodyContent[-1] === ' ') { - bodyContent = bodyContent.substring(0, bodyContent.length - 1) + bodyContent = bodyContent.substring(0, bodyContent.length - 1); } if (bodyContent === '') { - break + 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) - if (regString) { - let elementName = re.getReg(bodyContent, regString.regs[1]) - elementName = 'NAME_' + elementName.toUpperCase() - let elementValue = re.getReg(bodyContent, regString.regs[1]) - result.element.push({ - name: elementName, - value: elementValue, - type: 'string' - }) - result.enumValueType = 1 - } - return result + let regString = re.match(' *([a-zA-Z0-9_]+) *', bodyContent); + if (regString) { + let elementName = re.getReg(bodyContent, regString.regs[1]); + elementName = 'NAME_' + elementName.toUpperCase(); + let elementValue = re.getReg(bodyContent, regString.regs[1]); + result.element.push({ + name: elementName, + value: elementValue, + type: 'string', + }); + result.enumValueType = 1; + } + return result; } module.exports = { analyzeType, analyzeType2, analyzeType2Result, - parseNotes -} \ No newline at end of file + parseNotes, +}; \ No newline at end of file -- Gitee From 8cf191711b06185ea7a5877a170cbb4e461e38c7 Mon Sep 17 00:00:00 2001 From: LiYuxi Date: Thu, 11 Jul 2024 14:56:01 +0800 Subject: [PATCH 06/12] modify dts2ets-analyze/ Signed-off-by: LiYuxi --- .../dts2ets/appCodeGen/src/analyze/enum.js | 80 ++-- .../appCodeGen/src/analyze/function.js | 260 ++++++------- .../appCodeGen/src/analyze/interface.js | 116 +++--- .../appCodeGen/src/analyze/namespace.js | 362 +++++++++--------- .../dts2ets/appCodeGen/src/analyze/params.js | 114 +++--- .../dts2ets/appCodeGen/src/analyze/return.js | 14 +- .../dts2ets/appCodeGen/src/analyze/type.js | 117 +++--- 7 files changed, 540 insertions(+), 523 deletions(-) diff --git a/src/cli/dts2ets/appCodeGen/src/analyze/enum.js b/src/cli/dts2ets/appCodeGen/src/analyze/enum.js index 92f2bfd8..179307a0 100644 --- a/src/cli/dts2ets/appCodeGen/src/analyze/enum.js +++ b/src/cli/dts2ets/appCodeGen/src/analyze/enum.js @@ -12,80 +12,80 @@ * 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代表字符串 - } + enumValueType: 0, // 0代表数字,1代表字符串 + }; for (let i in body) { - let bodyContent = body[i] + let bodyContent = body[i]; while (bodyContent.length > 0 && bodyContent[0] === ' ') { - bodyContent = bodyContent.substring(1, bodyContent.length) + bodyContent = bodyContent.substring(1, bodyContent.length); } while (bodyContent.length > 0 && bodyContent[-1] === ' ') { - bodyContent = bodyContent.substring(0, bodyContent.length - 1) + bodyContent = bodyContent.substring(0, bodyContent.length - 1); } - if (bodyContent === "") { - break + 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 + type: 'string', + }); + 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 + type: 'string', + }); + 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 + analyzeEnumResult, +}; \ No newline at end of file diff --git a/src/cli/dts2ets/appCodeGen/src/analyze/function.js b/src/cli/dts2ets/appCodeGen/src/analyze/function.js index 0f749c7a..2cbe699d 100644 --- a/src/cli/dts2ets/appCodeGen/src/analyze/function.js +++ b/src/cli/dts2ets/appCodeGen/src/analyze/function.js @@ -13,8 +13,8 @@ * limitations under the License. */ const re = require('../tools/re'); -const { FuncType, NumberIncrease, isEnum, EnumValueType, enumIndex, isType, typeIndex, isOnObjCallback, - getOnObjCallbackType, getLogErrInfo } = require('../tools/common'); +const { FuncType, NumberIncrease, isEnum, EnumValueType, enumIndex, isType, typeIndex, isOnObjCallback, + getOnObjCallbackType, getLogErrInfo } = require('../tools/common'); const { analyzeParams } = require('./params'); const { analyzeReturn } = require('./return'); const { NapiLog } = require('../tools/NapiLog'); @@ -22,78 +22,82 @@ const { randomInt } = require('crypto'); const { print } = require('../tools/tool'); function analyzeSubInterface(data) { - let body = re.replaceAll(data, '\n', '').split(';') // # replace(' ', ''). + let body = re.replaceAll(data, '\n', '').split(';'); // # replace(' ', ''). let result = { value: [], function: [], parentNameList: [], childList: [], - parentList: [] - } + parentList: [], + }; for (let i in body) { - let t = body[i] - 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]; + 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; + } + let tt = re.match(' *([a-zA-Z0-9_]+) *: *([a-zA-Z_0-9<>,:{}[\\] ]+)', t); if (tt) { // 变量 analyzeSubInterfaceVariable(t, tt, result); } } - return result + return result; } function analyzeSubInterfaceVariable(t, tt, result) { - let valueName = re.getReg(t, tt.regs[1]); - let valueType = re.getReg(t, tt.regs[2]); - let index = valueType.indexOf('number'); - while (index !== -1) { - valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); - index = valueType.indexOf('number'); - } - result.value.push({ - name: valueName, - type: valueType - }); + let valueName = re.getReg(t, tt.regs[1]); + let valueType = re.getReg(t, tt.regs[2]); + let index = valueType.indexOf('number'); + while (index !== -1) { + valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); + index = valueType.indexOf('number'); + } + result.value.push({ + name: valueName, + type: valueType, + }); } function getFuncParaType(v, interfaceName, data, results) { - let arrayType = re.match('(Async)*Callback<(Array<([a-zA-Z_0-9]+)>)>', v.type) - let parameter = v.type + let arrayType = re.match('(Async)*Callback<(Array<([a-zA-Z_0-9]+)>)>', v.type); + let parameter = v.type; if (arrayType) { - parameter = re.getReg(v.type, arrayType.regs[2]) + 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()) + v.type = v.type.replace(parameter, 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); } else if (data.enum[index].body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_STRING) { - v.type = v.type.replace(parameter, 'string') + v.type = v.type.replace(parameter, 'string'); } 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) + else if (isEnum(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.type = v.type.replace(parameter, 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); } else if (results.enum[index].body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_STRING) { - v.type = v.type.replace(parameter, 'string') + v.type = v.type.replace(parameter, 'string'); } else { - NapiLog.logError('analyzeFunction getFuncParaType is not support this type %s.' - .format(results.enum[index].body.enumValueType), getLogErrInfo()); - return null - } + NapiLog.logError('analyzeFunction getFuncParaType is not support this type %s.' + .format(results.enum[index].body.enumValueType), getLogErrInfo()); + return null; + } } 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) { @@ -102,95 +106,95 @@ function getFuncParaType(v, interfaceName, data, results) { // type的处理 if (isType(parameter, data)) { - let index = typeIndex(parameter, data) - if (data.type[index].isEnum) { - v.type = v.type.replace(parameter, 'string') - } + let index = typeIndex(parameter, data); + if (data.type[index].isEnum) { + 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 = '' - 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) + 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); 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) - }) + body: analyzeSubInterface(interfaceBody), + }); } else if (Object.prototype.hasOwnProperty.call(results, 'interface')) { results.interface.push({ name: interfaceName, - body: analyzeSubInterface(interfaceBody) - }) - } + body: analyzeSubInterface(interfaceBody), + }); + } } - matchs = re.match(matchNoName, values) - if(matchs) { - let resNoNameInter = analyzeFuncNoNameInterface(data, values) - values = resNoNameInter.values + matchs = re.match(matchNoName, values); + if (matchs) { + let resNoNameInter = analyzeFuncNoNameInterface(data, values); + values = resNoNameInter.values; } let result = { interfaceName: interfaceName, - values: values - } - return result + values: values, + }; + 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 = '' - 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) { @@ -198,8 +202,8 @@ function getObjCallFunc(results, onObjCbType, values, ret) { results.callFunction.push({ 'name': onObjCbType, 'body': values, - 'ret': ret - }) + 'ret': ret, + }); } } function getFuncResult(name, funcType, values, ret, isStatic) { @@ -208,67 +212,67 @@ function getFuncResult(name, funcType, values, ret, isStatic) { type: funcType, value: values, ret: ret, - isStatic: isStatic - } - return result + isStatic: isStatic, + }; + 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) - paramType = paramType.replace(paramAsync, paramTypeVal); + // 匿名interface处理 + let paramAsync = paramType.substring(14, paramType.length - 1); + paramType = paramType.replace(paramAsync, paramTypeVal); } - values.push({name: 'promise', optional: false, type: paramType}) - ret = 'void' // 返回值由Promise改为void,与AsyncCallback接口保持一致 + values.push({ name: 'promise', optional: false, type: 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) - } - return result + let onObjCbType = getOnObjCallbackType(name, interfaceName); + getObjCallFunc(results, onObjCbType, values, ret); + } + return result; } module.exports = { @@ -276,5 +280,5 @@ module.exports = { analyzeSubInterface, getFuncParaType, analyzeFuncNoNameInterface, - analyseSubReturn -} \ No newline at end of file + analyseSubReturn, +}; \ No newline at end of file diff --git a/src/cli/dts2ets/appCodeGen/src/analyze/interface.js b/src/cli/dts2ets/appCodeGen/src/analyze/interface.js index bf46ae28..6d2dc24b 100644 --- a/src/cli/dts2ets/appCodeGen/src/analyze/interface.js +++ b/src/cli/dts2ets/appCodeGen/src/analyze/interface.js @@ -19,98 +19,104 @@ 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 + body: analyzeInterface(interfaceBody, rsltInterface), + }); + valueType = interfaceTypeName; } - return valueType + return valueType; } /* 去除单行注释// */ function parseNotes(data) { - let notes = data.indexOf('//') >= 0 ? data.substring(data.indexOf('//'), data.length) : ''; - while(notes !== '') { - notes = notes.substring(0, notes.indexOf('\n')); + let notes = data.indexOf('//') >= 0 ? data.substring(data.indexOf('//'), data.length) : ''; + while (notes !== '') { + notes = notes.substring(0, notes.indexOf('\n')); data = data.replace(notes, ''); - notes = '' + notes = ''; let st = data.indexOf('//'); - if(st >= 0) { + 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: [] - } + 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); } - tt = re.match("(static )* *(\\$*[A-Za-z0-9_]+) *[:]? *\\(([\n 'a-zA-Z\'\'\"\":;=,_0-9?<>{}()=>|[\\]]*)\\)" - + ' *(:|=>)? *([A-Za-z0-9_<>{}:;, .[\\]]+)?', t) + tt = re.match('(static )* *(\\$*[A-Za-z0-9_]+) *[:]? *\\(([\n \'a-zA-Z\'\'\"\":;=,_0-9?<>{}()=>|[\\]]*)\\)' + + ' *(:|=>)? *([A-Za-z0-9_<>{}:;, .[\\]]+)?', t); if (tt) { // 接口函数成员 analyzeInterfaceFunction(t, tt, data, results, interfaceName, result); } } - return result + return result; } module.exports = { analyzeInterface, - parseNotes -} + parseNotes, +}; function analyzeInterfaceFunction(t, tt, data, results, interfaceName, result) { - let ret = re.getReg(t, tt.regs[5]) === '' ? 'void' : re.getReg(t, tt.regs[5]); - let funcDetail = analyzeFunction(data, re.getReg(t, tt.regs[1]) !== '', re.getReg(t, tt.regs[2]), - re.getReg(t, tt.regs[3]), ret, results, interfaceName); - if (funcDetail !== null && funcDetail !== undefined) { - // 完全一样的方法不重复添加 (如同名同参的AsyncCallback和Promise方法) - addUniqFunc2List(funcDetail, result.function); - } + let ret = re.getReg(t, tt.regs[5]) === '' ? 'void' : re.getReg(t, tt.regs[5]); + let funcDetail = analyzeFunction(data, re.getReg(t, tt.regs[1]) !== '', re.getReg(t, tt.regs[2]), + re.getReg(t, tt.regs[3]), ret, results, interfaceName); + if (funcDetail !== null && funcDetail !== undefined) { + // 完全一样的方法不重复添加 (如同名同参的AsyncCallback和Promise方法) + addUniqFunc2List(funcDetail, result.function); + } } function analyzeInterfaceVariable(t, tt, rsltInterface, result) { - let valueName = re.getReg(t, tt.regs[1]); - let valueType = re.getReg(t, tt.regs[3]); - let index = valueType.indexOf('number'); - let optionalFlag = re.getReg(t, tt.regs[2]) === '?' ? true : false; - while (index !== -1) { - valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); - index = valueType.indexOf('number'); - } - valueType = analyzeNoNameInterface(valueType, valueName, rsltInterface); - result.value.push({ - name: valueName, - type: valueType, - optional: optionalFlag - }); + let valueName = re.getReg(t, tt.regs[1]); + let valueType = re.getReg(t, tt.regs[3]); + let index = valueType.indexOf('number'); + let optionalFlag = re.getReg(t, tt.regs[2]) === '?' ? true : false; + while (index !== -1) { + valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); + index = valueType.indexOf('number'); + } + valueType = analyzeNoNameInterface(valueType, valueName, rsltInterface); + result.value.push({ + name: valueName, + type: valueType, + optional: optionalFlag, + }); } diff --git a/src/cli/dts2ets/appCodeGen/src/analyze/namespace.js b/src/cli/dts2ets/appCodeGen/src/analyze/namespace.js index 221fff1a..347e19db 100644 --- a/src/cli/dts2ets/appCodeGen/src/analyze/namespace.js +++ b/src/cli/dts2ets/appCodeGen/src/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,44 @@ 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 parseTypeResult = parseType(matchs, data, result) - data = getDataByResult(parseTypeResult) + let parseFunctionResult = parseFunction(matchs, data, result); + data = getDataByResult(parseFunctionResult); - let parseClassResult = parseClass(matchs, data, result) - data = getDataByResult(parseClassResult) + let parseTypeResult = parseType(matchs, data, result); + data = getDataByResult(parseTypeResult); - let parseNamespaceResult = parseNamespace(matchs, data, result) - data = getDataByResult(parseNamespaceResult) + let parseClassResult = parseClass(matchs, data, result); + data = getDataByResult(parseClassResult); - data = removeReg(matchs, data, result) + let parseNamespaceResult = parseNamespace(matchs, data, result); + data = getDataByResult(parseNamespaceResult); + + 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,215 +93,215 @@ 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] - if(!isValidValue(interf)) { - NapiLog.logError("parseEnumType interf is null!"); - return null; - } - - // function 匹配 - for (let j in interf.body.function) { - let func = interf.body.function[j]; - if(!isValidValue(func)) { - NapiLog.logError("parseEnumType func is null!"); + let interf = result.interface[i]; + if (!isValidValue(interf)) { + NapiLog.logError('parseEnumType interf is null!'); return null; } - - // 参数匹配 - for (let k in func.value) { - let v = func.value[k]; - if(!isValidValue(v)) { - NapiLog.logError("parseEnumType func.value is null!"); + + // function 匹配 + for (let j in interf.body.function) { + let func = interf.body.function[j]; + if (!isValidValue(func)) { + NapiLog.logError('parseEnumType func is null!'); return null; } - if (v.type === enumm.name) { - if (enumm.body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_NUMBER) { - v.type = "NUMBER_TYPE_" + NumberIncrease.getAndIncrease(); - } else if (enumm.body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_STRING) { - v.type = "string"; - } else { - NapiLog.logError("parseEnumType for interface function value is not support this type %s." - .format(enumm.body.enumValueType), getLogErrInfo()); + // 参数匹配 + for (let k in func.value) { + let v = func.value[k]; + if (!isValidValue(v)) { + NapiLog.logError('parseEnumType func.value is null!'); return null; } - result.interface[i].body.function[j].value[k].type = v.type; - } + + if (v.type === enumm.name) { + if (enumm.body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_NUMBER) { + v.type = 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease(); + } else if (enumm.body.enumValueType === EnumValueType.ENUM_VALUE_TYPE_STRING) { + v.type = 'string'; + } else { + NapiLog.logError('parseEnumType for interface function value is not support this type %s.' + .format(enumm.body.enumValueType), getLogErrInfo()); + return null; + } + result.interface[i].body.function[j].value[k].type = v.type; + } + } } - } } } - 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) + body: analyzeNamespace(namespaceBody), + }); + 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) + body: analyzeEnum(enumBody.substring(1, enumBody.length - 1)), + }); + 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]) + body: re.getReg(data, matchs.regs[2]), + }); + 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) { if (value === null || value === undefined) { - return false; + return false; } return true; } 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 - }) + 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 +313,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; } /** @@ -341,72 +343,72 @@ function getParentNameList(firstKey, secondKey, parentStr) { * @param result 解析后的ts数据结构 * @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 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 = [] - if(extendsParent !== '') { - bodyObj.parentNameList = getParentNameList("extends", "implements", extendsParent) +function createInterfaceData(matchs, data, result) { + 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 = []; + if (extendsParent !== '') { + bodyObj.parentNameList = getParentNameList('extends', 'implements', extendsParent); } - if(implementParent !== '') { - bodyObj.parentNameList = getParentNameList("implements", "extends", implementParent) + if (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) + 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); 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, @@ -415,5 +417,5 @@ module.exports = { parseFunction, parseInterface, parseClass, - parseType -} \ No newline at end of file + parseType, +}; \ No newline at end of file diff --git a/src/cli/dts2ets/appCodeGen/src/analyze/params.js b/src/cli/dts2ets/appCodeGen/src/analyze/params.js index b99812c8..a24b7739 100644 --- a/src/cli/dts2ets/appCodeGen/src/analyze/params.js +++ b/src/cli/dts2ets/appCodeGen/src/analyze/params.js @@ -12,15 +12,15 @@ * 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 || - isFuncType(type) || isArrowFunc(type)) { + if (funcType === FuncType.DIRECT && type.indexOf('Callback') >= 0 && type.indexOf('AsyncCallback') < 0 || + isFuncType(type) || isArrowFunc(type)) { isSync = true; } return isSync; @@ -33,64 +33,64 @@ function isSyncFuncType(type, funcType) { * @param {*} rsltCallFunction 解析结果 */ 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 functionRet = re.getReg(valueType, matchs.regs[2]); - let functionBody = re.getReg(valueType, matchs.regs[1]); - - 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 number = NumberIncrease.getAndIncrease(); + 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]; + 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(); + } } - } - rsltCallFunction.push({ - "name": functionTypeName, - "body": bodyRes, - "ret": functionRet - }) - valueType = functionTypeName - } - return valueType + rsltCallFunction.push({ + 'name': functionTypeName, + 'body': bodyRes, + 'ret': functionRet, + }); + valueType = functionTypeName; + } + 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}) - if (type.indexOf("AsyncCallback") >= 0) { - funcType = FuncType.ASYNC + result.push({ 'name': re.getReg(v, matchs.regs[1]), 'type': type, 'optional': optionalFlag }); + 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 -} + analyzeParams, +}; diff --git a/src/cli/dts2ets/appCodeGen/src/analyze/return.js b/src/cli/dts2ets/appCodeGen/src/analyze/return.js index 1fec3b3a..9ca095f2 100644 --- a/src/cli/dts2ets/appCodeGen/src/analyze/return.js +++ b/src/cli/dts2ets/appCodeGen/src/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 + analyzeReturn, +}; \ No newline at end of file diff --git a/src/cli/dts2ets/appCodeGen/src/analyze/type.js b/src/cli/dts2ets/appCodeGen/src/analyze/type.js index 603a137b..24ab076e 100644 --- a/src/cli/dts2ets/appCodeGen/src/analyze/type.js +++ b/src/cli/dts2ets/appCodeGen/src/analyze/type.js @@ -17,101 +17,106 @@ const { NumberIncrease } = require('../tools/common'); /* 去除单行注释// */ function parseNotes(data) { - let notes = data.indexOf('//') >= 0 ? data.substring(data.indexOf('//'), data.length) : ''; - while(notes != '') { - notes = notes.substring(0, notes.indexOf('\n')); + let notes = data.indexOf('//') >= 0 ? data.substring(data.indexOf('//'), data.length) : ''; + while (notes != '') { + notes = notes.substring(0, notes.indexOf('\n')); data = data.replace(notes, ''); - notes = '' + notes = ''; let st = data.indexOf('//'); - if(st >= 0) { + if (st >= 0) { 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: [] - } + // function: [], + }; for (let i in body) { - let t = body[i] - 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]; + 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) { // 接口成员变量, 但不包括带'=>'的成员,带'=>'的接口成员需要按函数处理 analyzeTypeVariable(t, tt, result); } } - return result + return result; } function analyzeTypeVariable(t, tt, result) { - let valueName = re.getReg(t, tt.regs[1]); - let valueType = re.getReg(t, tt.regs[3]); - let index = valueType.indexOf('number'); - let optionalFlag = re.getReg(t, tt.regs[2]) === '?' ? true : false; - while (index !== -1) { - valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); - index = valueType.indexOf('number'); - } - result.value.push({ - name: valueName, - type: valueType, - optional: optionalFlag - }); + let valueName = re.getReg(t, tt.regs[1]); + let valueType = re.getReg(t, tt.regs[3]); + let index = valueType.indexOf('number'); + let optionalFlag = re.getReg(t, tt.regs[2]) === '?' ? true : false; + while (index !== -1) { + valueType = valueType.replace('number', 'NUMBER_TYPE_' + NumberIncrease.getAndIncrease()); + index = valueType.indexOf('number'); + } + result.value.push({ + name: valueName, + type: valueType, + optional: optionalFlag, + }); } function analyzeType2(data) { - let body = re.replaceAll(data, ' ', '').split('"|"') + let body = re.replaceAll(data, ' ', '').split('"|"') let result = { element: [], function: [], - enumValueType: 0 // 0代表数字,1代表字符串 - } + enumValueType: 0, // 0代表数字,1代表字符串 + }; for (let i in body) { - let bodyContent = body[i] + let bodyContent = body[i]; while (bodyContent.length > 0 && bodyContent[0] === ' ') { - bodyContent = bodyContent.substring(1, bodyContent.length) + bodyContent = bodyContent.substring(1, bodyContent.length); } while (bodyContent.length > 0 && bodyContent[-1] === ' ') { - bodyContent = bodyContent.substring(0, bodyContent.length - 1) + bodyContent = bodyContent.substring(0, bodyContent.length - 1); } if (bodyContent === '') { - break + 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) - if (regString) { - let elementName = re.getReg(bodyContent, regString.regs[1]) - elementName = 'NAME_' + elementName.toUpperCase() - let elementValue = re.getReg(bodyContent, regString.regs[1]) - result.element.push({ - name: elementName, - value: elementValue, - type: 'string' - }) - result.enumValueType = 1 - } - return result + let regString = re.match(' *([a-zA-Z0-9_]+) *', bodyContent); + if (regString) { + let elementName = re.getReg(bodyContent, regString.regs[1]); + elementName = 'NAME_' + elementName.toUpperCase(); + let elementValue = re.getReg(bodyContent, regString.regs[1]); + result.element.push({ + name: elementName, + value: elementValue, + type: 'string', + }); + result.enumValueType = 1; + } + return result; } module.exports = { analyzeType, analyzeType2, analyzeType2Result, - parseNotes -} \ No newline at end of file + parseNotes, +}; \ No newline at end of file -- Gitee From b2a9a834f227f0c8e40b54db932424fb66b11319 Mon Sep 17 00:00:00 2001 From: LiYuxi Date: Thu, 11 Jul 2024 15:08:51 +0800 Subject: [PATCH 07/12] modify dts2ets/appCodeGen/src/ Signed-off-by: LiYuxi --- .../dts2ets/appCodeGen/src/app_code_gen.js | 38 +++++++-------- src/cli/dts2ets/appCodeGen/src/generate.js | 48 +++++++++---------- src/cli/dts2ets/appCodeGen/src/main.js | 18 +++---- 3 files changed, 52 insertions(+), 52 deletions(-) diff --git a/src/cli/dts2ets/appCodeGen/src/app_code_gen.js b/src/cli/dts2ets/appCodeGen/src/app_code_gen.js index 21e7f109..e599da27 100644 --- a/src/cli/dts2ets/appCodeGen/src/app_code_gen.js +++ b/src/cli/dts2ets/appCodeGen/src/app_code_gen.js @@ -12,20 +12,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const main = require("./main"); +const main = require('./main'); -const re = require("./tools/re"); -const { checkFileError } = require("./tools/common"); -const { NapiLog } = require("./tools/NapiLog"); -const path = require("path"); -const stdio = require("stdio"); +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: "@ohos.napitest.d.ts" }, - '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: '@ohos.napitest.d.ts' }, + 'out': { key: 'o', args: 1, description: 'output directory', default: '.' }, + 'loglevel': { key: 'l', args: 1, description: 'Log Level : 0~3', default: '1' }, /* 需要测试的接口函数可配置:写在json文件里: * [{ @@ -34,14 +34,14 @@ let ops = stdio.getopt({ * }] * 配置cfg.json文件路径 */ - 'functionsCfg': {key: 'c', args: 1, description: "configured file including the functions for test", default: ""} + 'functionsCfg': { key: 'c', args: 1, description: 'configured file including the functions for test', default: '' } }); - -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; if (fileNames == null) { - NapiLog.logInfo("fileNames cannot be empty!"); + NapiLog.logInfo('fileNames cannot be empty!'); } else if (fileNames !== '') { readFiles(); } @@ -65,17 +65,17 @@ function readFiles() { * 获取Json配置文件内容 * @returns */ -function getJsonCfg(currentPath) { +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 fn = re.getFileInPath(fileName); let tt = re.match('(@ohos\.)*([.a-z_A-Z0-9]+).d.ts', fn); @@ -109,5 +109,5 @@ else { module.exports = { - getJsonCfg -} \ No newline at end of file + getJsonCfg, +}; \ No newline at end of file diff --git a/src/cli/dts2ets/appCodeGen/src/generate.js b/src/cli/dts2ets/appCodeGen/src/generate.js index 2c5187a6..287a87d0 100644 --- a/src/cli/dts2ets/appCodeGen/src/generate.js +++ b/src/cli/dts2ets/appCodeGen/src/generate.js @@ -14,14 +14,14 @@ */ // 生成BUILD.gn // 生成tool_utility.h,生成tool_utility.cpp -const { replaceAll } = require("./tools/tool"); -const { writeFile } = require("./tools/FileRW"); -const re = require("./tools/re"); +const { replaceAll } = require('./tools/tool'); +const { writeFile } = require('./tools/FileRW'); +const re = require('./tools/re'); -const { jsonCfgList } = require("./tools/common"); -const os = require("os"); +const { jsonCfgList } = require('./tools/common'); +const os = require('os'); const path = require('path') -const { NapiLog } = require("./tools/NapiLog"); +const { NapiLog } = require('./tools/NapiLog'); const DIRECT = 1; const SYNC = 2; @@ -55,7 +55,7 @@ struct Index { .height('100%') } } -` +`; let buttonTemplate = ` Button() { Text('[button_test_interface_name]') @@ -76,9 +76,9 @@ Button() { hilog.info(0x0000, 'testTag', 'button onClick end !'); }); -` +`; -let FuncCfgList = [] +let FuncCfgList = []; function analyzeJsonCfg(jsonCfg) { let len = jsonCfg.length; @@ -86,8 +86,8 @@ function analyzeJsonCfg(jsonCfg) { for (let i = 0; i < len; i++) { FuncCfgList.push({ classOrInterfName: jsonCfg[i].classOrInterfName, - functionName: jsonCfg[i].functionName - }) + functionName: jsonCfg[i].functionName, + }); } } @@ -132,7 +132,7 @@ function genIndexETSCode(indexEts, testFuncName, funcInfo, className = null) { NapiLog.logInfo('This type of function(%s) is not supported!'.format(funcType)); } } else { - NapiLog.logInfo("test function(%s) is not current function(%s)!".format(testFuncName, funcInfo.name)); + NapiLog.logInfo('test function(%s) is not current function(%s)!'.format(testFuncName, funcInfo.name)); } return indexEts; } @@ -155,13 +155,13 @@ function generateAppCode(structOfTs, destDir, moduleName, jsonCfg) { let indexEts = '' // 测试interface中的方法 for (let i in ns0.body.interface) { - let ii = ns0.body.interface[i] + let ii = ns0.body.interface[i]; indexEts = genInterClassFunc(ii, indexEts, FuncCfgList[0].classOrInterfName, FuncCfgList[0].functionName); } // 测试class中的方法 for (let i in ns0.body.class) { - let ii = ns0.body.class[i] + let ii = ns0.body.class[i]; indexEts = genInterClassFunc(ii, indexEts, FuncCfgList[0].classOrInterfName, FuncCfgList[0].functionName); } @@ -172,8 +172,8 @@ function generateAppCode(structOfTs, destDir, moduleName, jsonCfg) { } // index.ets文件生成 - indexEts = replaceAll(indexEts, "[import_module_name]", moduleName) - writeFile(re.pathJoin(destDir, "Index.ets"), null != license ? (license + "\n" + indexEts) : indexEts) + indexEts = replaceAll(indexEts, '[import_module_name]', moduleName); + writeFile(re.pathJoin(destDir, 'Index.ets'), null != license ? (license + '\n' + indexEts) : indexEts); } // 遍历 interface/class 中的function,生成对interface/class中的接口测试的代码 @@ -182,7 +182,7 @@ function genInterClassFunc(ii, indexEts, testClass = null, testFunc) { let interfaceBody = ii.body; if (testClass !== className) { - NapiLog.logInfo("test class(%s) is not current class(%s)!".format(testClass, className)); + NapiLog.logInfo('test class(%s) is not current class(%s)!'.format(testClass, className)); return indexEts; } // 遍历interface中的成员方法 @@ -196,7 +196,7 @@ function genInterClassFunc(ii, indexEts, testClass = null, testFunc) { // 调用direct方法 function callDirectFunction(funcName, funcValue, retValue, indexEts, className = null) { let testInterfaceName = funcName; - let testInterfaceButton = replaceAll(buttonTemplate, "[button_test_interface_name]", testInterfaceName); + let testInterfaceButton = replaceAll(buttonTemplate, '[button_test_interface_name]', testInterfaceName); let testInterfaceValue = ''; // 给方法参数赋初值 let funcParamValue = ''; // 调用方法参数 // 给接口参数赋初值 @@ -235,16 +235,16 @@ function callDirectFunction(funcName, funcValue, retValue, indexEts, className = } else { console.error('The current return type is not supported.'); } - let useInterface = '' + let useInterface = ''; if (className !== null) { - useInterface = 'let %sObj: napitest.%s = new napitest.%s();\n'.format(className, className, className) + useInterface = 'let %sObj: napitest.%s = new napitest.%s();\n'.format(className, className, className); } let buttonTestInterface = `%s%s%s`.format(useInterface, testInterfaceValue, useFunction); - testInterfaceButton = replaceAll(testInterfaceButton, "[button_test_interface_code]", buttonTestInterface); - indexEts = replaceAll(indexEtsTemplete, "[test_interface_button]", testInterfaceButton); + testInterfaceButton = replaceAll(testInterfaceButton, '[button_test_interface_code]', buttonTestInterface); + indexEts = replaceAll(indexEtsTemplete, '[test_interface_button]', testInterfaceButton); return indexEts; } module.exports = { - generateAppCode -} + generateAppCode, +}; diff --git a/src/cli/dts2ets/appCodeGen/src/main.js b/src/cli/dts2ets/appCodeGen/src/main.js index 34c39108..d5a5eafe 100644 --- a/src/cli/dts2ets/appCodeGen/src/main.js +++ b/src/cli/dts2ets/appCodeGen/src/main.js @@ -12,10 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { analyzeFile } = require("./analyze"); -const { generateAppCode } = require("./generate"); -const { NapiLog } = require("./tools/NapiLog"); -const re = require("./tools/re"); +const { analyzeFile } = require('./analyze'); +const { generateAppCode } = require('./generate'); +const { NapiLog } = require('./tools/NapiLog'); +const re = require('./tools/re'); var fs = require('fs'); function doGenerate(ifname, destdir, jsonCfg) { @@ -23,12 +23,12 @@ function doGenerate(ifname, destdir, jsonCfg) { let structOfTs = analyzeFile(ifname); let fn = re.getFileInPath(ifname); let tt = re.match('(@ohos\.)*([.a-z_A-Z0-9]+).d.ts', fn); - if (structOfTs === undefined || structOfTs.declareNamespace.length === 0 || + if (structOfTs === undefined || structOfTs.declareNamespace.length === 0 || structOfTs.declareNamespace[0].name === undefined) { NapiLog.logError('analyzeFile file fail and file name is: ' + fn); return; } - + // step2: generate code if (tt) { let moduleName = re.getReg(fn, tt.regs[2]); @@ -38,9 +38,9 @@ function doGenerate(ifname, destdir, jsonCfg) { } else { NapiLog.logError('file name ' + fn + ' format invalid in function of doGenerate!'); } - return structOfTs.declareNamespace[0].name + return structOfTs.declareNamespace[0].name; } module.exports = { - doGenerate -} + doGenerate, +}; -- Gitee From 189b5c7c1f43035f67d19522571f4aaab80d2c9a Mon Sep 17 00:00:00 2001 From: LiYuxi Date: Thu, 11 Jul 2024 15:31:02 +0800 Subject: [PATCH 08/12] modify dts2ets/appCodeGen/src/tools/ Signed-off-by: LiYuxi --- .../dts2ets/appCodeGen/src/tools/FileRW.js | 194 ++++----- .../dts2ets/appCodeGen/src/tools/NapiLog.js | 66 +-- .../dts2ets/appCodeGen/src/tools/common.js | 382 +++++++++--------- src/cli/dts2ets/appCodeGen/src/tools/re.js | 22 +- src/cli/dts2ets/appCodeGen/src/tools/tool.js | 201 ++++----- 5 files changed, 435 insertions(+), 430 deletions(-) diff --git a/src/cli/dts2ets/appCodeGen/src/tools/FileRW.js b/src/cli/dts2ets/appCodeGen/src/tools/FileRW.js index 0e950ebc..8748fd12 100644 --- a/src/cli/dts2ets/appCodeGen/src/tools/FileRW.js +++ b/src/cli/dts2ets/appCodeGen/src/tools/FileRW.js @@ -15,126 +15,126 @@ const fs = require('fs'); function utf8ArrayToStr(array) { - var out, i, len, c; - var char2, char3; + var out, i, len, c; + var char2, char3; - out = ""; - len = array.length; - i = 0; - while (i < len) { - c = array[i++]; - switch (c >> 4) { - case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: - // 0xxxxxxx - out += String.fromCharCode(c); - break; - case 12: case 13: - // 110x xxxx 10xx xxxx - char2 = array[i++]; - out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); - break; - case 14: - // 1110 xxxx 10xx xxxx 10xx xxxx - char2 = array[i++]; - char3 = array[i++]; - out += String.fromCharCode(((c & 0x0F) << 12) | - ((char2 & 0x3F) << 6) | - ((char3 & 0x3F) << 0)); - break; + out = ''; + len = array.length; + i = 0; + while (i < len) { + c = array[i++]; + switch (c >> 4) { + case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: + // 0xxxxxxx + out += String.fromCharCode(c); + break; + case 12: case 13: + // 110x xxxx 10xx xxxx + char2 = array[i++]; + out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); + break; + case 14: + // 1110 xxxx 10xx xxxx 10xx xxxx + char2 = array[i++]; + char3 = array[i++]; + out += String.fromCharCode(((c & 0x0F) << 12) | + ((char2 & 0x3F) << 6) | + ((char3 & 0x3F) << 0)); + break; + } } - } - return out; + return out; } function stringToUint8Array(string, options = { stream: false }) { - if (options.stream) { - throw new Error(`Failed to encode: the 'stream' option is unsupported.`); - } - let pos = 0; - const len = string.length; - let at = 0; // output position - let tlen = Math.max(32, len + (len >> 1) + 7); // 1.5x size - let target = new Uint8Array((tlen >> 3) << 3); // ... but at 8 byte offset + if (options.stream) { + throw new Error(`Failed to encode: the 'stream' option is unsupported.`); + } + let pos = 0; + const len = string.length; + let at = 0; // output position + let tlen = Math.max(32, len + (len >> 1) + 7); // 1.5x size + let target = new Uint8Array((tlen >> 3) << 3); // ... but at 8 byte offset - while (pos < len) { - let value = string.charCodeAt(pos++); - let isContinue = false; - if (value >= 0xd800 && value <= 0xdbff) { - if (pos < len) {// high surrogate - const extra = string.charCodeAt(pos); - if ((extra & 0xfc00) === 0xdc00) { - ++pos; - value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000; + while (pos < len) { + let value = string.charCodeAt(pos++); + let isContinue = false; + if (value >= 0xd800 && value <= 0xdbff) { + if (pos < len) {// high surrogate + const extra = string.charCodeAt(pos); + if ((extra & 0xfc00) === 0xdc00) { + ++pos; + value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000; + } + } + if (value >= 0xd800 && value <= 0xdbff) { + isContinue = true; // drop lone surrogate + } } - } - if (value >= 0xd800 && value <= 0xdbff) { - isContinue = true; // drop lone surrogate - } - } - if (!isContinue) { - // expand the buffer if we couldn't write 4 bytes - if (at + 4 > target.length) { - tlen += 8; // minimum extra - tlen *= (1.0 + (pos / string.length) * 2); // take 2x the remaining - tlen = (tlen >> 3) << 3; // 8 byte offset + if (!isContinue) { + // expand the buffer if we couldn't write 4 bytes + if (at + 4 > target.length) { + tlen += 8; // minimum extra + tlen *= (1.0 + (pos / string.length) * 2); // take 2x the remaining + tlen = (tlen >> 3) << 3; // 8 byte offset - target = uint8Array(tlen, target); - } + target = uint8Array(tlen, target); + } - let calculateResult = calculate(value, target, at) - isContinue = calculateResult[0] - target = calculateResult[1] - at = calculateResult[2] + let calculateResult = calculate(value, target, at); + isContinue = calculateResult[0]; + target = calculateResult[1]; + at = calculateResult[2]; + } } - } - return target.slice(0, at); + return target.slice(0, at); } function calculate(value, target, at) { - let isContinue = false - if ((value & 0xffffff80) === 0) { // 1-byte - target[at++] = value; // ASCII - isContinue = true; - } else if ((value & 0xfffff800) === 0) { // 2-byte - target[at++] = ((value >> 6) & 0x1f) | 0xc0; - } else if ((value & 0xffff0000) === 0) { // 3-byte - target[at++] = ((value >> 12) & 0x0f) | 0xe0; - target[at++] = ((value >> 6) & 0x3f) | 0x80; - } else if ((value & 0xffe00000) === 0) { // 4-byte - target[at++] = ((value >> 18) & 0x07) | 0xf0; - target[at++] = ((value >> 12) & 0x3f) | 0x80; - target[at++] = ((value >> 6) & 0x3f) | 0x80; - } else { - isContinue = true; - } - if (!isContinue) { - target[at++] = (value & 0x3f) | 0x80; - } - return [isContinue, target, at] + let isContinue = false; + if ((value & 0xffffff80) === 0) { // 1-byte + target[at++] = value; // ASCII + isContinue = true; + } else if ((value & 0xfffff800) === 0) { // 2-byte + target[at++] = ((value >> 6) & 0x1f) | 0xc0; + } else if ((value & 0xffff0000) === 0) { // 3-byte + target[at++] = ((value >> 12) & 0x0f) | 0xe0; + target[at++] = ((value >> 6) & 0x3f) | 0x80; + } else if ((value & 0xffe00000) === 0) { // 4-byte + target[at++] = ((value >> 18) & 0x07) | 0xf0; + target[at++] = ((value >> 12) & 0x3f) | 0x80; + target[at++] = ((value >> 6) & 0x3f) | 0x80; + } else { + isContinue = true; + } + if (!isContinue) { + target[at++] = (value & 0x3f) | 0x80; + } + return [isContinue, target, at]; } function uint8Array(tlen, target) { - const update = new Uint8Array(tlen); - update.set(target); - return update + const update = new Uint8Array(tlen); + update.set(target); + return update; } function readFile(fn) { - if (!fs.existsSync(fn)) { - return ""; - } - let data = fs.readFileSync(fn); - data = utf8ArrayToStr(data); - return data; + if (!fs.existsSync(fn)) { + return ''; + } + let data = fs.readFileSync(fn); + data = utf8ArrayToStr(data); + return data; } function writeFile(fn, str) { - let data = stringToUint8Array(str); - fs.writeFileSync(fn, data); + let data = stringToUint8Array(str); + fs.writeFileSync(fn, data); } module.exports = { - readFile, - writeFile -} \ No newline at end of file + readFile, + writeFile, +}; \ No newline at end of file diff --git a/src/cli/dts2ets/appCodeGen/src/tools/NapiLog.js b/src/cli/dts2ets/appCodeGen/src/tools/NapiLog.js index ce9c4f0b..b35db3cf 100644 --- a/src/cli/dts2ets/appCodeGen/src/tools/NapiLog.js +++ b/src/cli/dts2ets/appCodeGen/src/tools/NapiLog.js @@ -13,7 +13,7 @@ * limitations under the License. */ const fs = require('fs'); -const path = require("path"); +const path = require('path'); let vscode = null; try { vscode = require('vscode'); @@ -31,10 +31,10 @@ NapiLog.LEV_ERROR = 1; NapiLog.LEV_DEBUG = 2; NapiLog.LEV_INFO = 3; -const LEV_STR = ["[NON]", "[ERR]", "[DBG]", "[INF]"] +const LEV_STR = ['[NON]', '[ERR]', '[DBG]', '[INF]']; var logLevel = NapiLog.LEV_ERROR; var logFileName = null; -var logResultMessage = [true, ""] +var logResultMessage = [true, '']; function getDateString() { let nowDate = new Date(); @@ -43,7 +43,7 @@ function getDateString() { function saveLog(dateStr, levStr, detail) { if (logFileName) { - let logStr = dateStr + " " + levStr + " " + detail + "\n"; + let logStr = dateStr + ' ' + levStr + ' ' + detail + '\n'; fs.appendFileSync(logFileName, logStr); } } @@ -51,7 +51,7 @@ function saveLog(dateStr, levStr, detail) { NapiLog.init = function (level, fileName) { logLevel = level in [NapiLog.LEV_NONE, NapiLog.LEV_ERROR, NapiLog.LEV_DEBUG, NapiLog.LEV_INFO] ? level : NapiLog.LEV_ERROR; - logFileName = fileName ? fileName : "napi_generator.log"; + logFileName = fileName ? fileName : 'napi_generator.log'; } /** @@ -59,33 +59,33 @@ NapiLog.init = function (level, fileName) { * @param {} callerFuncName 指定取调用栈中哪个方法名所在的帧作为目标帧 * @returns */ -NapiLog.getCallPath = function(callerFuncName = null) { - let callPath = "" +NapiLog.getCallPath = function (callerFuncName = null) { + let callPath = ''; let stackArray = new Error().stack.split('\n'); // 如果没有指定目标方法,默认在调用栈中查找当前方法"getCallPath"所在的帧 - let destFuncName = callerFuncName != null ? callerFuncName : "getCallPath" + let destFuncName = callerFuncName != null ? callerFuncName : 'getCallPath'; - for (let i = stackArray.length -1; i >=0 ; --i) { + for (let i = stackArray.length - 1; i >= 0; --i) { // debug模式和打包后的可执行程序调用栈函数名不同, 以NapiLog.log()方法为例: // vscode debug模式下调用栈打印的方法名为NapiLog.log,而可执行程序的调用栈中显示为Function.log() - let callerMatch = (stackArray[i].indexOf("NapiLog." + destFuncName) > 0 - || stackArray[i].indexOf("Function." + destFuncName) > 0) + let callerMatch = (stackArray[i].indexOf('NapiLog.' + destFuncName) > 0 || + stackArray[i].indexOf('Function.' + destFuncName) > 0); if (callerMatch) { - let stackMsg = stackArray[i+1].trim() - let leftIndex = stackMsg.indexOf("(") - let rightIndex = stackMsg.indexOf(")") + let stackMsg = stackArray[i + 1].trim(); + let leftIndex = stackMsg.indexOf('('); + let rightIndex = stackMsg.indexOf(')'); if (leftIndex > 0 && rightIndex > 0) { let funInfo = stackMsg.substring(0, leftIndex); - let srcPath = stackMsg.substring(leftIndex + 1, rightIndex) - let colNumIndex = srcPath.lastIndexOf(":") - let colNum = srcPath.substring(colNumIndex + 1, srcPath.length) - let lineNumIndex = srcPath.lastIndexOf(":", colNumIndex - 1) - let lineNum = srcPath.substring(lineNumIndex + 1, colNumIndex) - let filePath = srcPath.substring(0, lineNumIndex) - - callPath = "%s[%s(%s:%s)]".format(funInfo,filePath,lineNum,colNum) + let srcPath = stackMsg.substring(leftIndex + 1, rightIndex); + let colNumIndex = srcPath.lastIndexOf(':'); + let colNum = srcPath.substring(colNumIndex + 1, srcPath.length); + let lineNumIndex = srcPath.lastIndexOf(':', colNumIndex - 1); + let lineNum = srcPath.substring(lineNumIndex + 1, colNumIndex); + let filePath = srcPath.substring(0, lineNumIndex); + + callPath = '%s[%s(%s:%s)]'.format(funInfo, filePath, lineNum, colNum); } break; } @@ -98,19 +98,19 @@ function print(...args) { if (vscode) { vscode.window.showInformationMessage(...args); } - console.log(args + ""); + console.log(args + ''); } function recordLog(lev, ...args) { let origMsgInfo = args; - let callPath = NapiLog.getCallPath("log"); + let callPath = NapiLog.getCallPath('log'); let dataStr = getDateString(); - let detail = args.join(" "); - saveLog(dataStr + " " + callPath, LEV_STR[lev], detail); + let detail = args.join(' '); + saveLog(dataStr + ' ' + callPath, LEV_STR[lev], detail); if (lev === NapiLog.LEV_ERROR) { logResultMessage = [false, detail]; } - let logStr = callPath + " " + detail; + let logStr = callPath + ' ' + detail; if (logLevel <= lev) return logStr; NapiLog.logInfo(origMsgInfo[0]); return logStr; @@ -119,20 +119,20 @@ function recordLog(lev, ...args) { NapiLog.logError = function (...args) { let logInfo = recordLog(NapiLog.LEV_ERROR, args); print(logInfo); -} +}; NapiLog.logDebug = function (...args) { recordLog(NapiLog.LEV_DEBUG, args); -} +}; NapiLog.logInfo = function (...args) { recordLog(NapiLog.LEV_INFO, args); -} +}; NapiLog.getResult = function () { return logResultMessage; -} +}; module.exports = { - NapiLog -} \ No newline at end of file + NapiLog, +}; \ No newline at end of file diff --git a/src/cli/dts2ets/appCodeGen/src/tools/common.js b/src/cli/dts2ets/appCodeGen/src/tools/common.js index 7b25a1f1..a275abf3 100644 --- a/src/cli/dts2ets/appCodeGen/src/tools/common.js +++ b/src/cli/dts2ets/appCodeGen/src/tools/common.js @@ -12,70 +12,70 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const re = require("./re"); -const tsc = require("../../../../node_modules/typescript"); +const re = require('./re'); +const tsc = require('../../../../node_modules/typescript'); function checkFileError(ifname) { - let program = tsc.createProgram([ifname], {target: tsc.ScriptTarget.Latest,}) + let program = tsc.createProgram([ifname], { target: tsc.ScriptTarget.Latest, }); let emitResult = program.emit(); let allDiagnostics = tsc.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); - let errorMsg = '' + let errorMsg = ''; allDiagnostics.forEach(diagnostic => { if (diagnostic.file) { let { line, character } = tsc.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); - let message = tsc.flattenDiagnosticMessageText(diagnostic.messageText, "\n"); + let message = tsc.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); errorMsg += `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}\n`; } else { - errorMsg += tsc.flattenDiagnosticMessageText(diagnostic.messageText, "\n") + "\n"; + errorMsg += tsc.flattenDiagnosticMessageText(diagnostic.messageText, '\n') + '\n'; } }); if (allDiagnostics.length > 0) { return [false, errorMsg]; } - return [true, ""]; + return [true, '']; } class FuncType { } -FuncType.DIRECT = 1 -FuncType.SYNC = 2 -FuncType.ASYNC = 4 -FuncType.PROMISE = 8 +FuncType.DIRECT = 1; +FuncType.SYNC = 2; +FuncType.ASYNC = 4; +FuncType.PROMISE = 8; FuncType.ToString = function (type) { - if (type === FuncType.DIRECT) return "DIRECT"; - else if (type === FuncType.SYNC) return "SYNC"; - else if (type === FuncType.ASYNC) return "ASYNC"; - else if (type === FuncType.PROMISE) return "PROMISE"; - return "UNKNOW"; -} + if (type === FuncType.DIRECT) return 'DIRECT'; + else if (type === FuncType.SYNC) return 'SYNC'; + else if (type === FuncType.ASYNC) return 'ASYNC'; + else if (type === FuncType.PROMISE) return 'PROMISE'; + return 'UNKNOW'; +}; class NumberIncrease { } -NumberIncrease.num = 1 +NumberIncrease.num = 1; NumberIncrease.getAndIncrease = function () { return NumberIncrease.num++; -} +}; NumberIncrease.get = function () { return NumberIncrease.num; -} +}; NumberIncrease.reset = function () { - NumberIncrease.num = 1 -} + NumberIncrease.num = 1; +}; class InterfaceList { } InterfaceList.interfacess_ = []; InterfaceList.push = function (ifs) { - InterfaceList.interfacess_.push(ifs) -} + InterfaceList.interfacess_.push(ifs); +}; InterfaceList.pop = function () { - InterfaceList.interfacess_.pop() -} + InterfaceList.interfacess_.pop(); +}; InterfaceList.getValue = function (name) { - let ifs = InterfaceList.interfacess_[InterfaceList.interfacess_.length - 1] + let ifs = InterfaceList.interfacess_[InterfaceList.interfacess_.length - 1]; for (let i in ifs) { let vv = ifs[i]; if (ifs[i].name === name) { - var hasProperty = Object.prototype.hasOwnProperty.call(ifs[i].body, "allProperties") + var hasProperty = Object.prototype.hasOwnProperty.call(ifs[i].body, 'allProperties') if (hasProperty) { return ifs[i].body.allProperties.values; } else { @@ -84,69 +84,69 @@ InterfaceList.getValue = function (name) { } } return null; -} +}; InterfaceList.getBody = function (name) { - let ifs = InterfaceList.interfacess_[InterfaceList.interfacess_.length - 1] + let ifs = InterfaceList.interfacess_[InterfaceList.interfacess_.length - 1]; for (let i in ifs) { if (ifs[i].name === name) { return ifs[i].body; } } return null; -} +}; class CallFunctionList { } CallFunctionList.callFuncs = []; CallFunctionList.push = function (ifs) { - CallFunctionList.callFuncs.push(ifs) -} + CallFunctionList.callFuncs.push(ifs); +}; CallFunctionList.pop = function () { - CallFunctionList.callFuncs.pop() -} + CallFunctionList.callFuncs.pop(); +}; CallFunctionList.getValue = function (name) { if (CallFunctionList.callFuncs.length === 0) { - return null + return null; } let cfs = CallFunctionList.callFuncs[CallFunctionList.callFuncs.length - 1] if (cfs === undefined) { - return null + return null; } for (let i = 0; i < cfs.length; i++) { if (cfs[i].name === name) { return [cfs[i].body, cfs[i].ret] - } + } } - return null -} + return null; +}; CallFunctionList.getObjOnFuncName = function (interfaceName) { - let cfs = CallFunctionList.callFuncs[CallFunctionList.callFuncs.length - 1] - let funNames = [] + let cfs = CallFunctionList.callFuncs[CallFunctionList.callFuncs.length - 1]; + let funNames = []; for (let i = 0; i < cfs.length; i++) { if (cfs[i].name.indexOf(interfaceName) === 0) { - let funName = cfs[i].name.substring(interfaceName.length+1, cfs[i].name.length) - funNames.push(funName) - } + let funName = cfs[i].name.substring(interfaceName.length + 1, cfs[i].name.length); + funNames.push(funName); + } } - return funNames -} + return funNames; +}; class TypeList { } TypeList.types = []; TypeList.push = function (ifs) { - TypeList.types.push(ifs) -} + TypeList.types.push(ifs); +}; TypeList.pop = function () { - TypeList.types.pop() -} + TypeList.types.pop(); +}; TypeList.getValue = function (name) { - let ifs = TypeList.types[TypeList.types.length - 1] + let ifs = TypeList.types[TypeList.types.length - 1]; for (let i in ifs) { if (ifs[i].name === name) { - var hasProperty = Object.prototype.hasOwnProperty.call(ifs[i].body, "allProperties") + var hasProperty = Object.prototype.hasOwnProperty.call(ifs[i].body, 'allProperties'); if (hasProperty) { return ifs[i].body.allProperties.values; } else { @@ -155,192 +155,192 @@ TypeList.getValue = function (name) { } } return null; -} +}; class EnumList { } EnumList.enum_ = []; EnumList.push = function (ifs) { - EnumList.enum_.push(ifs) -} + EnumList.enum_.push(ifs); +}; EnumList.pop = function () { - EnumList.enum_.pop() -} + EnumList.enum_.pop(); +}; EnumList.getValue = function (name) { - let ifs = EnumList.enum_[EnumList.enum_.length - 1] + let ifs = EnumList.enum_[EnumList.enum_.length - 1]; for (let i in ifs) { if (ifs[i].name === name) { return ifs[i].body.element; } } return null; -} +}; function getArrayType(type) { - let tt = re.match("Array<([a-zA-Z_0-9]+)>", type) + let tt = re.match('Array<([a-zA-Z_0-9]+)>', type); if (tt !== null && tt !== undefined) { - return re.getReg(type, tt.regs[1]) - } - - tt = re.match("Array<{([[a-z:]+)([a-z:]]+)([a-zA-Z_1-9:]+)", type) + return re.getReg(type, tt.regs[1]); + } + + tt = re.match('Array<{([[a-z:]+)([a-z:]]+)([a-zA-Z_1-9:]+)', type); if (tt !== null && tt !== undefined) { - let res = '' - let len = tt.regs.length - for (let i=1; i]+)>", type) - let ttMap = re.search(",([a-zA-Z_0-9]+)>>", type) - let ttArray = re.search("Array<([a-zA-Z_0-9]+)>", type) - - if(ttArray === null) { - ttArray = re.search("([a-zA-Z_0-9]+)\\[\\]>", type) - } - - let valueType - let valueMapType - let valueArrayType + type = type.replace(/\s*/g, ''); + let ttKey = re.search('Map<([a-zA-Z_0-9]+),', type); + let ttValue = re.search(',([a-zA-Z_0-9<>]+)>', type); + let ttMap = re.search(',([a-zA-Z_0-9]+)>>', type); + let ttArray = re.search('Array<([a-zA-Z_0-9]+)>', type); + + if (ttArray === null) { + ttArray = re.search('([a-zA-Z_0-9]+)\\[\\]>', type); + } + + let valueType; + let valueMapType; + let valueArrayType; if (ttKey === null && ttValue === null && ttMap === null) { - ttKey = re.search("key:([a-zA-Z_0-9]+)", type) - ttValue = re.search(":([a-zA-Z_0-9]+)}", type) - ttMap = re.search(":([a-zA-Z_0-9]+)}}", type) - ttArray = re.search("Array<([a-zA-Z_0-9]+)>", type) + ttKey = re.search('key:([a-zA-Z_0-9]+)', type); + ttValue = re.search(':([a-zA-Z_0-9]+)}', type); + ttMap = re.search(':([a-zA-Z_0-9]+)}}', type); + ttArray = re.search('Array<([a-zA-Z_0-9]+)>', type); if (ttArray === null) { - ttArray = re.search(":([a-zA-Z_0-9]+)\\[\\]}", type) - } + ttArray = re.search(':([a-zA-Z_0-9]+)\\[\\]}', type); + } } - + if (ttValue !== null && ttValue !== undefined) { - valueType = re.getReg(type, ttValue.regs[1]) - if (valueType.indexOf("Array<") === 0) { - valueArrayType = re.getReg(valueType, ttArray.regs[1]) - valueType = undefined + valueType = re.getReg(type, ttValue.regs[1]); + if (valueType.indexOf('Array<') === 0) { + valueArrayType = re.getReg(valueType, ttArray.regs[1]); + valueType = undefined; } else if (ttMap !== undefined && ttMap !== null) { - valueMapType = re.getReg(type, ttMap.regs[1]) - valueType = undefined + valueMapType = re.getReg(type, ttMap.regs[1]); + valueType = undefined; } } if (ttMap !== null && ttMap !== undefined) { - valueMapType = re.getReg(type, ttMap.regs[1]) + valueMapType = re.getReg(type, ttMap.regs[1]); } if (ttArray !== null && ttArray !== undefined) { - valueArrayType = re.getReg(type, ttArray.regs[1]) + valueArrayType = re.getReg(type, ttArray.regs[1]); } - return [re.getReg(type, ttKey.regs[1]), valueType, valueMapType, valueArrayType] + return [re.getReg(type, ttKey.regs[1]), valueType, valueMapType, valueArrayType]; } function getUnionType(type) { - type = type.replace(/\s*/g,"") - var typeArr = new Array() - typeArr = type.split("|") - return typeArr + type = type.replace(/\s*/g, ''); + var typeArr = new Array(); + typeArr = type.split('|'); + return typeArr; } function isFuncType(type) { - let isFunction = false; + let isFunction = false; if (type === null || type === undefined) { return isFunction; } - + if (type === 'function' || type === 'Function') { isFunction = true; return isFunction; @@ -349,30 +349,30 @@ function isFuncType(type) { function isRegisterFunc(name) { let regIndex = name.indexOf('register'); - let isRegister = false + let isRegister = false; if (regIndex === 0) { - isRegister = true + isRegister = true; } - return isRegister + return isRegister; } function isUnRegisterFunc(name) { let unRegIndex = name.indexOf('unRegister'); - let isRegister = false + let isRegister = false; if (unRegIndex === 0) { - isRegister = true + isRegister = true; } return isRegister } function isOnObjCallback(name) { let regIndex = name.indexOf('on'); - let flag = false + let flag = false; let onLen = 2; if (regIndex === 0 && name.length > onLen) { - flag = true + flag = true; } - return flag + return flag; } // 箭头函数,如funTest(cb: (wid: boolean) => void): string; @@ -387,7 +387,7 @@ function isArrowFunc(type) { function isOnOffRegisterFunc(name) { let flag = false; if (name === 'on' || name === 'off' || isRegisterFunc(name) || isUnRegisterFunc(name) || - isOnObjCallback(name)) { + isOnObjCallback(name)) { flag = true; } return flag; @@ -395,53 +395,53 @@ function isOnOffRegisterFunc(name) { function isCreateThreadsafeFunc(name) { let index = name.indexOf('createThreadSafeFunc'); - let isTdSafeFunc = false + let isTdSafeFunc = false; if (index === 0) { - isTdSafeFunc = true + isTdSafeFunc = true; } - return isTdSafeFunc + return isTdSafeFunc; } function getOnObjCallbackType(funcName, interName) { - let onObjCbType = '' + let onObjCbType = ''; if (interName !== '') { - onObjCbType = interName + '_' + funcName + onObjCbType = interName + '_' + funcName; } else { - onObjCbType = funcName + onObjCbType = funcName; } - return 'AUTO_CALLFUNCTION_' + onObjCbType + return 'AUTO_CALLFUNCTION_' + onObjCbType; } function getOnCallbackFunAndInterName(CallbackType) { - CallbackType = CallbackType.replaceAll('AUTO_CALLFUNCTION_', '') - let CallbackTypes = CallbackType.split('_') + CallbackType = CallbackType.replaceAll('AUTO_CALLFUNCTION_', ''); + let CallbackTypes = CallbackType.split('_'); let funcName = CallbackTypes[1]; let interName = CallbackTypes[0]; - return [interName, funcName] + return [interName, funcName]; } class jsonCfgList { } jsonCfgList.jsonCfg = []; jsonCfgList.push = function (ifs) { - jsonCfgList.jsonCfg.push(ifs) -} + jsonCfgList.jsonCfg.push(ifs); +}; jsonCfgList.pop = function () { - jsonCfgList.jsonCfg.pop() -} + jsonCfgList.jsonCfg.pop(); +}; jsonCfgList.getValue = function (className, inter) { - let ifs = jsonCfgList.jsonCfg[jsonCfgList.jsonCfg.length - 1] + let ifs = jsonCfgList.jsonCfg[jsonCfgList.jsonCfg.length - 1]; for (let i in ifs) { if (ifs[i].interfaceName.className === className && ifs[i].interfaceName.funcName === inter) { - return ifs[i].serviceCode + return ifs[i].serviceCode; } } return null; } function getLogErrInfo() { - let errInfo = " Please refer to for support capacity:" - + "https://gitee.com/openharmony/napi_generator/tree/master/release-notes" - return errInfo + let errInfo = ' Please refer to for support capacity:' + + 'https://gitee.com/openharmony/napi_generator/tree/master/release-notes'; + return errInfo; } module.exports = { @@ -471,5 +471,5 @@ module.exports = { isOnOffRegisterFunc, getOnObjCallbackType, getLogErrInfo, - isCreateThreadsafeFunc -} \ No newline at end of file + isCreateThreadsafeFunc, +}; \ No newline at end of file diff --git a/src/cli/dts2ets/appCodeGen/src/tools/re.js b/src/cli/dts2ets/appCodeGen/src/tools/re.js index d1279519..04c3233f 100644 --- a/src/cli/dts2ets/appCodeGen/src/tools/re.js +++ b/src/cli/dts2ets/appCodeGen/src/tools/re.js @@ -15,18 +15,18 @@ const path = require('path'); function search(ss, data) { - ss = replaceAll(ss, "\\.", "\\.") + ss = replaceAll(ss, '\\.', '\\.'); let reg = new RegExp(ss); let tt = reg.exec(data); if (tt == null) return null; - let ret = { "regs": [] } + let ret = { 'regs': [] }; for (let i = 0; i < tt.length; i++) { let p = data.indexOf(tt[i]); if (tt[i] == null) { - ret["regs"].push([-1, -1]) + ret['regs'].push([-1, -1]); } else { - ret["regs"].push([p, p + tt[i].length]) + ret['regs'].push([p, p + tt[i].length]); } } @@ -40,11 +40,11 @@ function match(ss, data) { } function removeReg(data, reg) { - return data.substring(0, reg[0]) + data.substring(reg[1], data.length) + return data.substring(0, reg[0]) + data.substring(reg[1], data.length); } function getReg(data, reg) { - return data.substring(reg[0], reg[1]) + return data.substring(reg[0], reg[1]); } function getFileInPath(tpath) { @@ -56,15 +56,15 @@ function getPathInPath(tpath) { } function all(sfrom) { - return new RegExp(sfrom, "g"); + return new RegExp(sfrom, 'g'); } function replaceAll(ss, sfrom, sto) { - return ss.replace(all(sfrom), sto) + return ss.replace(all(sfrom), sto); } function pathJoin(...args) { - return path.join(...args) + return path.join(...args); } module.exports = { @@ -76,5 +76,5 @@ module.exports = { getPathInPath, pathJoin, replaceAll, - all -} \ No newline at end of file + all, +}; \ No newline at end of file diff --git a/src/cli/dts2ets/appCodeGen/src/tools/tool.js b/src/cli/dts2ets/appCodeGen/src/tools/tool.js index 7b65ba27..dffad320 100644 --- a/src/cli/dts2ets/appCodeGen/src/tools/tool.js +++ b/src/cli/dts2ets/appCodeGen/src/tools/tool.js @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const re = require("./re"); +const re = require('./re'); let vscode = null; try { vscode = require('vscode'); @@ -22,9 +22,9 @@ catch (err) { } const NUM_CONST_MAP = new Map([ - [0, "XNapiTool::ZERO"], [1, "XNapiTool::ONE"], [2, "XNapiTool::TWO"], [3, "XNapiTool::THREE"], - [4, "XNapiTool::FOUE"], [5, "XNapiTool::FIVE"], [6, "XNapiTool::SIX"], [7, "XNapiTool::SEVEN"], - [8, "XNapiTool::EIGHT"], [9, "XNapiTool::NINE"] + [0, 'XNapiTool::ZERO'], [1, 'XNapiTool::ONE'], [2, 'XNapiTool::TWO'], [3, 'XNapiTool::THREE'], + [4, 'XNapiTool::FOUE'], [5, 'XNapiTool::FIVE'], [6, 'XNapiTool::SIX'], [7, 'XNapiTool::SEVEN'], + [8, 'XNapiTool::EIGHT'], [9, 'XNapiTool::NINE'] ]); function print(...args) { @@ -36,47 +36,49 @@ function print(...args) { 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) + let p = result.search(reg); if (p < 0) break; - result = result.substring(0, p) + args[i] + result.substring(p + 2, result.length) + result = result.substring(0, p) + args[i] + result.substring(p + 2, result.length); } return result; -} +}; String.prototype.replaceAll = function (...args) { let result = this; while (result.indexOf(args[0]) >= 0) { - result = result.replace(args[0], args[1]) + result = result.replace(args[0], args[1]); } return result; -} +}; function checkOutBody(body, off, flag, binside) { off = off || 0; - flag = flag || ["{", "}"]; + flag = flag || ['{', '}']; binside = binside || false; let idx = { - "(": ")", - "{": "}", - "<": ">", - //"<": "<", - //">": ">", + '(': ')', + '{': '}', + '<': '>', + //'<': '<', + //'>': '>', }; let csl = {}; let csr = {}; for (let f in idx) { - csl[f] = 0 - csr[idx[f]] = 0 + csl[f] = 0; + csr[idx[f]] = 0; } - let cs1 = 0 + let cs1 = 0; if (flag[0].length > 0 && body.substring(off, off + flag[0].length) !== flag[0]) { return null; } for (let i = off + flag[0].length; i < body.length; i++) { - if (body[i] === '"') cs1 += 1 + if (body[i] === '"') { + cs1 += 1; + } if (cs1 % 2 === 0) { let tb1 = true; for (let k in csl) { @@ -86,8 +88,9 @@ function checkOutBody(body, off, flag, binside) { } } if (tb1 && body.substring(i, i + flag[1].length) === flag[1]) { - if (binside) + if (binside) { return body.substring(off + flag[0].length, i); + } return body.substring(off, i + flag[1].length); } @@ -96,7 +99,7 @@ function checkOutBody(body, off, flag, binside) { if (body[i] in csr) csr[body[i]] += 1; } if (body[i] in csr) { - if (!(body[i] === '>' && body[i-1] === '=')) { // 尖括号匹配时忽略关键字 "=>" + if (!(body[i] === '>' && body[i - 1] === '=')) { // 尖括号匹配时忽略关键字 "=>" csr[body[i]] += 1; } } @@ -107,96 +110,98 @@ function checkOutBody(body, off, flag, binside) { function removeExplains(data) { // 去除 /** */ 类型的注释 - while (data.indexOf("/*") >= 0) { - let i1 = data.indexOf("/*") - let i2 = data.indexOf("*/") + 2 - data = data.substring(0, i1) + data.substring(i2, data.length) + while (data.indexOf('/*') >= 0) { + let i1 = data.indexOf('/*'); + let i2 = data.indexOf('*/') + 2; + data = data.substring(0, i1) + data.substring(i2, data.length); } // 去除 namespace 域外 // 类型的注释 // 如果换行格式是\r\n, 去除\r, 统一成\n格式 - while (data.indexOf("\r") >= 0) { - data = data.replace("\r", "") + while (data.indexOf('\r') >= 0) { + data = data.replace('\r', ''); } - while (data.indexOf("//") >= 0) { - let i1 = data.indexOf("//") - let i2 = data.indexOf("\n") - let end = data.indexOf("declare namespace ") + while (data.indexOf('//') >= 0) { + let i1 = data.indexOf('//'); + let i2 = data.indexOf('\n'); + let end = data.indexOf('declare namespace '); while (i2 < end && i1 < end) { while (i1 > i2) { - data = data.substring(0, i2) + data.substring(i2 + 2, data.length) - i2 = data.indexOf("\n") - i1 = data.indexOf("//") - } - data = data.substring(0, i1) + data.substring(i2 + 1, data.length) - i1 = data.indexOf("//") - i2 = data.indexOf("\n") - end = data.indexOf("declare namespace ") + data = data.substring(0, i2) + data.substring(i2 + 2, data.length); + i2 = data.indexOf('\n'); + i1 = data.indexOf('//'); + } + data = data.substring(0, i1) + data.substring(i2 + 1, data.length); + i1 = data.indexOf('//'); + i2 = data.indexOf('\n'); + end = data.indexOf('declare namespace '); } if (i2 > end || i1 > end) { break; } } - return data + return data; } function getLicense(data) { - while (data.indexOf("/*") >= 0) { - let i1 = data.indexOf("/*") - let i2 = data.indexOf("*/") + 2 - let licenseData = data.substring(i1, i2) - if (licenseData.search("Copyright") !== -1) { - return licenseData + while (data.indexOf('/*') >= 0) { + let i1 = data.indexOf('/*'); + let i2 = data.indexOf('*/') + 2; + let licenseData = data.substring(i1, i2); + if (licenseData.search('Copyright') !== -1) { + return licenseData; } else { - return null + return null; } } } function removeEmptyLine(data) { - while (data.indexOf("\r") >= 0) { - data = data.replace("\r", "") + while (data.indexOf('\r') >= 0) { + data = data.replace('\r', ''); } - while (data.indexOf("\t") >= 0) { - data = data.replace("\t", "") + while (data.indexOf('\t') >= 0) { + data = data.replace('\t', ''); } - while (data.indexOf(" \n") >= 0) { - data = data.replace(" \n", "\n") + while (data.indexOf(' \n') >= 0) { + data = data.replace(' \n', '\n'); } - while (data.indexOf("\n ") >= 0) { - data = data.replace("\n ", "\n") + while (data.indexOf('\n ') >= 0) { + data = data.replace('\n ', '\n'); } - while (data.indexOf("\n\n") >= 0) { - data = data.replace("\n\n", "\n") + while (data.indexOf('\n\n') >= 0) { + data = data.replace('\n\n', '\n'); } - while (data.indexOf("\n") === 0) { - data = data.substring(1, data.length) + while (data.indexOf('\n') === 0) { + data = data.substring(1, data.length); } - while (data.indexOf(" ") === 0) { - data = data.substring(1, data.length) + while (data.indexOf(' ') === 0) { + data = data.substring(1, data.length); } - return data + return data; } function replaceTab(data) { - while (data.indexOf("\t") >= 0) { - data = data.replace("\t", " ") + while (data.indexOf('\t') >= 0) { + data = data.replace('\t', ' '); } - return data + return data; } function removeEmptyLine2(data) { - while (data.indexOf(" \n")) - data = data.replace(" \n", "\n") - while (data.indexOf("\n\n\n")) - data = data.replace("\n\n\n", "\n\n") - return data + while (data.indexOf(' \n')); { + data = data.replace(' \n', '\n'); + } + while (data.indexOf('\n\n\n')) { + data = data.replace('\n\n\n', '\n\n'); + } + return data; } function replaceAll(s, sfrom, sto) { while (s.indexOf(sfrom) >= 0) { - s = s.replace(sfrom, sto) + s = s.replace(sfrom, sto); } return s; } @@ -207,20 +212,20 @@ function replaceAll(s, sfrom, sto) { * @param func2 方法2 * @returns 方法名称与形参是否完全相同 */ - function isSameFunc(func1, func2) { +function isSameFunc(func1, func2) { if (func1.name !== func2.name) { // 判断方法名称是否相同 return false; } - let func1ParamCount = func1.value.length + let func1ParamCount = func1.value.length; if (func1ParamCount !== func2.value.length) { // 判断方法形参个数是否一样 return false; } for (let i in func1.value) { // 判断方法每个形参数据类型是否相同 - if (func1.value[i].type !== func2.value[i].type) { - if (!(func1.value[i].type.indexOf("NUMBER_TYPE_") >= 0 && - func2.value[i].type.indexOf("NUMBER_TYPE_") >= 0)) { + if (func1.value[i].type !== func2.value[i].type) { + if (!(func1.value[i].type.indexOf('NUMBER_TYPE_') >= 0 && + func2.value[i].type.indexOf('NUMBER_TYPE_') >= 0)) { return false; } } @@ -236,14 +241,14 @@ function replaceAll(s, sfrom, sto) { * @param list 目标列表 * @returns 是否成功插入列表 */ - function addUniqFunc2List(obj, list) { +function addUniqFunc2List(obj, list) { for (let i in list) { if (isSameFunc(obj, list[i])) { - return false + return false; } } - list.push(obj) - return true + list.push(obj); + return true; } /** @@ -252,11 +257,11 @@ function replaceAll(s, sfrom, sto) { * @param childFunclist 子类全部方法列表 * @returns void */ - function setOverrideFunc(parentFunc, childFunclist) { +function setOverrideFunc(parentFunc, childFunclist) { for (let i in childFunclist) { if (isSameFunc(parentFunc, childFunclist[i])) { - childFunclist[i].isOverride = true - return + childFunclist[i].isOverride = true; + return; } } } @@ -267,13 +272,13 @@ function replaceAll(s, sfrom, sto) { * @param list 目标列表 * @returns void */ - function addUniqObj2List(obj, list) { +function addUniqObj2List(obj, list) { for (let i in list) { if (list[i].name === obj.name) { - return + return; } } - list.push(obj) + list.push(obj); } /** @@ -282,17 +287,17 @@ function replaceAll(s, sfrom, sto) { * @param funcInfo 方法信息 * return tabStr 缩进,staticStr 静态函数关键词,virtualStr 虚函数关键词, overrideStr 重写关键词 */ - function getPrefix(data, funcInfo) { - let isStatic = funcInfo.isStatic - let tabStr = "" - let virtualStr = "" - let staticStr = isStatic ? "static " : "" +function getPrefix(data, funcInfo) { + let isStatic = funcInfo.isStatic; + let tabStr = ''; + let virtualStr = ''; + let staticStr = isStatic ? 'static ' : ''; if (data.childList) { - tabStr = " " // 类中的方法增加一个缩进 - virtualStr = (data.childList.length > 0 && !isStatic) ? "virtual " : "" //如果是基类中的非静态方法,定义为虚函数 + tabStr = ' '; // 类中的方法增加一个缩进 + virtualStr = (data.childList.length > 0 && !isStatic) ? 'virtual ' : ''; //如果是基类中的非静态方法,定义为虚函数 } - let overrideStr = funcInfo.isOverride ? " override" : "" // 重写了父类方法,需要加上override关键字,否则触发c++门禁告警 - return [tabStr, staticStr, virtualStr, overrideStr] + let overrideStr = funcInfo.isOverride ? ' override' : ''; // 重写了父类方法,需要加上override关键字,否则触发c++门禁告警 + return [tabStr, staticStr, virtualStr, overrideStr]; } function getConstNum(num) { @@ -312,5 +317,5 @@ module.exports = { addUniqFunc2List, getPrefix, getConstNum, - setOverrideFunc -} + setOverrideFunc, +}; -- Gitee From f52563ff64c4eb9cf16798618b09abe23c57eb0d Mon Sep 17 00:00:00 2001 From: LiYuxi Date: Thu, 11 Jul 2024 15:41:08 +0800 Subject: [PATCH 09/12] modifyh2dts-tsMain Signed-off-by: LiYuxi --- src/cli/h2dts/src/tsGen/tsMain.js | 334 +++++++++++++++--------------- 1 file changed, 167 insertions(+), 167 deletions(-) diff --git a/src/cli/h2dts/src/tsGen/tsMain.js b/src/cli/h2dts/src/tsGen/tsMain.js index b09f332f..ee77776d 100644 --- a/src/cli/h2dts/src/tsGen/tsMain.js +++ b/src/cli/h2dts/src/tsGen/tsMain.js @@ -12,75 +12,75 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const { NapiLog } = require("../gen/tools/NapiLog"); -const { writeFile } = require("../gen/tools/FileRW"); -const path = require('path') -const re = require("../gen/tools/re"); -const fs = require("fs"); -const os = require("os"); +const { NapiLog } = require('../gen/tools/NapiLog'); +const { writeFile } = require('../gen/tools/FileRW'); +const path = require('path'); +const re = require('../gen/tools/re'); +const fs = require('fs'); +const os = require('os'); function parseFileAll(hFilePath) { - let execSync = require("child_process").execSync - let cmd = "" - if(fs.existsSync("./src/tsGen/header_parser.py")) { + let execSync = require('child_process').execSync; + let cmd = ''; + if (fs.existsSync('./src/tsGen/header_parser.py')) { // call python file (for debug test) - cmd = "python ./src/tsGen/header_parser.py " + hFilePath + cmd = 'python ./src/tsGen/header_parser.py ' + hFilePath; } else { // call exe file (for real runtime) - let sysInfo = os.platform() - let execPath = path.dirname(process.execPath) - let exeFile = sysInfo === 'win32' ? path.join(execPath, "header_parser.exe") : - path.join(execPath, "header_parser") - cmd = exeFile + " " + hFilePath + let sysInfo = os.platform(); + let execPath = path.dirname(process.execPath); + let exeFile = sysInfo === 'win32' ? path.join(execPath, 'header_parser.exe') : + path.join(execPath, 'header_parser'); + cmd = exeFile + ' ' + hFilePath; } - let parseResult = null - let stdout = execSync(cmd) - parseResult = JSON.parse(stdout.toString()).result - return parseResult + let parseResult = null; + let stdout = execSync(cmd); + parseResult = JSON.parse(stdout.toString()).result; + return parseResult; } function createNameSpaceInfo(parseNameSpaceInfo) { let nameSpaceInfo = { - "name": "", - "classes": [], - "functions": [] - } - nameSpaceInfo.name = parseNameSpaceInfo - return nameSpaceInfo + 'name': '', + 'classes': [], + 'functions': [], + }; + nameSpaceInfo.name = parseNameSpaceInfo; + return nameSpaceInfo; } function analyzeNameSpace(rootInfo, parseResult) { - let parseNameSpaces = parseResult.namespaces - for(var i = 0; i < parseNameSpaces.length; ++i) { - let nameSpaceInfo = createNameSpaceInfo(parseNameSpaces[i]) - rootInfo.namespaces.push(nameSpaceInfo) + let parseNameSpaces = parseResult.namespaces; + for (var i = 0; i < parseNameSpaces.length; ++i) { + let nameSpaceInfo = createNameSpaceInfo(parseNameSpaces[i]); + rootInfo.namespaces.push(nameSpaceInfo); } } function isStringType(cType) { - switch(cType) { + switch (cType) { case 'string': case 'std::string': case 'char': case 'wchar_t': case 'char16_t': case 'char32_t': - return true + return true; default: - return false + return false; } } function isBoolType(cType) { if (cType === 'bool') { - return true + return true; } - return false + return false; } function isNumberType(cType) { - switch(cType) { + switch (cType) { case 'short': case 'int': case 'uint32_t': @@ -97,155 +97,155 @@ function isNumberType(cType) { case 'uint64_t': case 'double_t': case 'float_t': - return true + return true; default: - return false + return false; } } function basicC2js(cType) { - let jsType = "" + let jsType = ''; if (isStringType(cType)) { - jsType = 'string' + jsType = 'string'; } else if (isBoolType(cType)) { - jsType = 'boolean' + jsType = 'boolean'; } else if (isNumberType(cType)) { - jsType = 'number' + jsType = 'number'; } else { - jsType = cType + jsType = cType; } - return jsType + return jsType; } function getJsTypeFromC(cType, typeInfo) { - let basicCtype = cType - let matchs = re.match("(std::)?vector<([\x21-\x7e ]+)>", basicCtype); + let basicCtype = cType; + let matchs = re.match('(std::)?vector<([\x21-\x7e ]+)>', basicCtype); if (matchs) { - basicCtype = re.getReg(basicCtype, matchs.regs[2]).trim() - typeInfo.array = 1 + basicCtype = re.getReg(basicCtype, matchs.regs[2]).trim(); + typeInfo.array = 1; } - let unsignedIdx = basicCtype.indexOf('unsigned') - if ( unsignedIdx >= 0) { + let unsignedIdx = basicCtype.indexOf('unsigned'); + if (unsignedIdx >= 0) { // cut off the keywords 'unsigned' - basicCtype = basicCtype.substring(unsignedIdx + 8, basicCtype.length).trim() + basicCtype = basicCtype.substring(unsignedIdx + 8, basicCtype.length).trim(); } - let jsType = basicC2js(basicCtype) + let jsType = basicC2js(basicCtype); if (typeInfo.array) { - jsType = "Array<%s>".format(jsType) + jsType = 'Array<%s>'.format(jsType); } - return jsType + return jsType; } function createParam(parseParamInfo) { let param = { - "name": "", - "type": "" - } - param.name = parseParamInfo.name - let rawType = getJsTypeFromC(parseParamInfo.raw_type, parseParamInfo) - param.type = rawType - - return param + 'name': '', + 'type': '', + }; + param.name = parseParamInfo.name; + let rawType = getJsTypeFromC(parseParamInfo.raw_type, parseParamInfo); + param.type = rawType; + + return param; } function createFuncInfo(parseFuncInfo, isClassFunc) { let funcInfo = { - "name": "", - "params": [], - "namespace": "", - "retType": "", - "static":"" - } - funcInfo.name = parseFuncInfo.name - funcInfo.namespace = parseFuncInfo.namespace - let tokenIndex = funcInfo.namespace.indexOf('::') + 'name': '', + 'params': [], + 'namespace': '', + 'retType': '', + 'static': '', + } + funcInfo.name = parseFuncInfo.name; + funcInfo.namespace = parseFuncInfo.namespace; + let tokenIndex = funcInfo.namespace.indexOf('::'); if (tokenIndex >= 0) { // delete '::' in namespace, get the pure space name. - funcInfo.namespace = funcInfo.namespace.substring(0, tokenIndex) + funcInfo.namespace = funcInfo.namespace.substring(0, tokenIndex); } - let parseParams = parseFuncInfo.parameters - for(var i = 0; i < parseParams.length; ++i) { - let param = createParam(parseParams[i]) - funcInfo.params.push(param) + let parseParams = parseFuncInfo.parameters; + for (var i = 0; i < parseParams.length; ++i) { + let param = createParam(parseParams[i]); + funcInfo.params.push(param); } - funcInfo.isClassFunc = isClassFunc + funcInfo.isClassFunc = isClassFunc; if (parseFuncInfo.static && isClassFunc) { - funcInfo.static = "static " - } - let retType = parseFuncInfo.returns === '' ? parseFuncInfo.rtnType : parseFuncInfo.returns - funcInfo.retType = getJsTypeFromC(retType, parseFuncInfo) - return funcInfo + funcInfo.static = 'static '; + } + let retType = parseFuncInfo.returns === '' ? parseFuncInfo.rtnType : parseFuncInfo.returns; + funcInfo.retType = getJsTypeFromC(retType, parseFuncInfo); + return funcInfo; } function putFuncIntoNamespace(funcInfo, namespaces) { for (var i = 0; i < namespaces.length; ++i) { if (namespaces[i].name === funcInfo.namespace) { - namespaces[i].functions.push(funcInfo) - return + namespaces[i].functions.push(funcInfo); + return; } } NapiLog.logError('The namespace [%s] of function %s is not found.'.format(funcInfo.namespace, funcInfo.name)); } function analyzeRootFunction(rootInfo, parseResult) { - let parseFunctions = parseResult.functions - for(var i = 0; i < parseFunctions.length; ++i) { - let funcInfo = createFuncInfo(parseFunctions[i], false) + let parseFunctions = parseResult.functions; + for (var i = 0; i < parseFunctions.length; ++i) { + let funcInfo = createFuncInfo(parseFunctions[i], false); if (parseFunctions[i].namespace !== '') { // function in namespace - putFuncIntoNamespace(funcInfo, rootInfo.namespaces) + putFuncIntoNamespace(funcInfo, rootInfo.namespaces); } else { // function without namespace, put on root - rootInfo.functions.push(funcInfo) + rootInfo.functions.push(funcInfo); } } } function createProperties(parseProperties) { - let propertyList = [] + let propertyList = []; for (var i = 0; i < parseProperties.length; ++i) { let property = {} - property.name = parseProperties[i].name - property.type = getJsTypeFromC(parseProperties[i].raw_type, parseProperties[i]) - propertyList.push(property) + property.name = parseProperties[i].name; + property.type = getJsTypeFromC(parseProperties[i].raw_type, parseProperties[i]); + propertyList.push(property); } - return propertyList + return propertyList; } function createClassFunctions(parseFuncs) { - let funcList = [] - for(var i = 0; i < parseFuncs.length; ++i) { - let funcInfo = createFuncInfo(parseFuncs[i], true) - funcList.push(funcInfo) + let funcList = []; + for (var i = 0; i < parseFuncs.length; ++i) { + let funcInfo = createFuncInfo(parseFuncs[i], true); + funcList.push(funcInfo); } - return funcList + return funcList; } function createClassInfo(parseClassInfo) { let classInfo = { - "name": "", - "namespace": "", - "properties": [], - "functions": [], - "extends":[] - } - classInfo.name = parseClassInfo.name - classInfo.namespace = parseClassInfo.namespace - classInfo.properties = createProperties(parseClassInfo.properties.public) - classInfo.functions = createClassFunctions(parseClassInfo.methods.public) - - return classInfo + 'name': '', + 'namespace': '', + 'properties': [], + 'functions': [], + 'extends': [], + }; + classInfo.name = parseClassInfo.name; + classInfo.namespace = parseClassInfo.namespace; + classInfo.properties = createProperties(parseClassInfo.properties.public); + classInfo.functions = createClassFunctions(parseClassInfo.methods.public); + + return classInfo; } function putClassIntoNamespace(classInfo, namespaces) { for (var i = 0; i < namespaces.length; ++i) { if (namespaces[i].name === classInfo.namespace) { - namespaces[i].classes.push(classInfo) - return + namespaces[i].classes.push(classInfo); + return; } } NapiLog.logError('The namespace [%s] of class %s is not found.'.format(classInfo.namespace, classInfo.name)); @@ -254,106 +254,106 @@ function putClassIntoNamespace(classInfo, namespaces) { function analyzeClasses(rootInfo, parseResult) { let parseClasses = parseResult.classes; - for(var className in parseClasses) { - let classInfo = createClassInfo(parseClasses[className]) + for (var className in parseClasses) { + let classInfo = createClassInfo(parseClasses[className]); if (classInfo.namespace !== '') { // class in namespace - putClassIntoNamespace(classInfo, rootInfo.namespaces) + putClassIntoNamespace(classInfo, rootInfo.namespaces); } else { // class without namespace, put on root - rootInfo.classes.push(classInfo) + rootInfo.classes.push(classInfo); } } } function getTab(tabLv) { - let tab = "" - for(var i = 0; i < tabLv; ++i) { - tab += " " + let tab = ''; + for (var i = 0; i < tabLv; ++i) { + tab += ' '; } - return tab + return tab; } function genFunction(func, tabLv, needDeclare = false) { - let tab = getTab(tabLv) - let funcPrefix = func.isClassFunc ? "" : "function " - let funcParams = "" + let tab = getTab(tabLv); + let funcPrefix = func.isClassFunc ? '' : 'function '; + let funcParams = ''; for (var i = 0; i < func.params.length; ++i) { - funcParams += i > 0 ? ", " : "" - funcParams += func.params[i].name + ": " + func.params[i].type + funcParams += i > 0 ? ', ' : ''; + funcParams += func.params[i].name + ': ' + func.params[i].type; } - let declareStr = needDeclare ? "declare " : "" - return "%s%s%s%s%s(%s): %s;\n".format(tab, declareStr, funcPrefix, func.static, func.name, funcParams, func.retType) + let declareStr = needDeclare ? 'declare ' : ''; + return '%s%s%s%s%s(%s): %s;\n'.format(tab, declareStr, funcPrefix, func.static, func.name, funcParams, func.retType); } function genClass(classInfo, tabLv, needDeclare = false) { - let tab = getTab(tabLv) - let declareStr = needDeclare ? "declare " : "" - let tsClass = tab + declareStr + "class " + classInfo.name + " {\n" - let tab1 = getTab(tabLv+1) + let tab = getTab(tabLv); + let declareStr = needDeclare ? 'declare ' : ''; + let tsClass = tab + declareStr + 'class ' + classInfo.name + ' {\n'; + let tab1 = getTab(tabLv + 1); for (var i = 0; i < classInfo.properties.length; ++i) { - tsClass += "%s%s: %s;\n".format(tab1, classInfo.properties[i].name, classInfo.properties[i].type) + tsClass += '%s%s: %s;\n'.format(tab1, classInfo.properties[i].name, classInfo.properties[i].type); } for (var i = 0; i < classInfo.functions.length; ++i) { - tsClass += genFunction(classInfo.functions[i], tabLv+1) + tsClass += genFunction(classInfo.functions[i], tabLv + 1); } - tsClass += tab + "}\n" - return tsClass + tsClass += tab + '}\n'; + return tsClass; } function genNamespace(namespace, tabLv) { - let tab = getTab(tabLv) - let tsNamespace = tab + "declare namespace %s {\n".format(namespace.name) - for(var i = 0; i < namespace.functions.length; ++i) { - tsNamespace += genFunction(namespace.functions[i], tabLv+1) + let tab = getTab(tabLv); + let tsNamespace = tab + 'declare namespace %s {\n'.format(namespace.name); + for (var i = 0; i < namespace.functions.length; ++i) { + tsNamespace += genFunction(namespace.functions[i], tabLv + 1); } - for(var i = 0; i < namespace.classes.length; ++i) { - tsNamespace += genClass(namespace.classes[i], tabLv+1) + for (var i = 0; i < namespace.classes.length; ++i) { + tsNamespace += genClass(namespace.classes[i], tabLv + 1); } - tsNamespace += tab + "}\n" - return tsNamespace + tsNamespace += tab + '}\n'; + return tsNamespace; } function genTsContent(rootInfo) { - let tsContent = rootInfo.needCallback ? "import { AsyncCallback, Callback } from './../basic';\n\n" : "" + let tsContent = rootInfo.needCallback ? 'import { AsyncCallback, Callback } from \'./../basic\';\n\n' : ''; - for(var i = 0; i < rootInfo.classes.length; ++i) { - tsContent += genClass(rootInfo.classes[i], 0, true) + for (var i = 0; i < rootInfo.classes.length; ++i) { + tsContent += genClass(rootInfo.classes[i], 0, true); } - for(var i = 0; i < rootInfo.namespaces.length; ++i) { - tsContent += genNamespace(rootInfo.namespaces[i], 0) + for (var i = 0; i < rootInfo.namespaces.length; ++i) { + tsContent += genNamespace(rootInfo.namespaces[i], 0); } - for(var i = 0; i < rootInfo.functions.length; ++i) { - tsContent += genFunction(rootInfo.functions[i], 0, true) + for (var i = 0; i < rootInfo.functions.length; ++i) { + tsContent += genFunction(rootInfo.functions[i], 0, true); } if (rootInfo.namespaces.length > 0) { // export the first namespace as default - tsContent += "\nexport default %s;".format(rootInfo.namespaces[0].name) + tsContent += '\nexport default %s;'.format(rootInfo.namespaces[0].name); } - return tsContent + return tsContent; } function doGenerate(hFilePath, destDir) { - let parseResult = parseFileAll(hFilePath) + let parseResult = parseFileAll(hFilePath); let rootInfo = { - "namespaces": [], - "classes": [], - "functions": [], - "needCallback": false - } - analyzeNameSpace(rootInfo, parseResult) - analyzeRootFunction(rootInfo, parseResult) - analyzeClasses(rootInfo, parseResult) - let hfileName = path.basename(hFilePath, ".h") - let tsFilePath = re.pathJoin(destDir, "%s.d.ts".format(hfileName)) - let tsContent = genTsContent(rootInfo) - writeFile(tsFilePath,tsContent) + 'namespaces': [], + 'classes': [], + 'functions': [], + 'needCallback': false, + }; + analyzeNameSpace(rootInfo, parseResult); + analyzeRootFunction(rootInfo, parseResult); + analyzeClasses(rootInfo, parseResult); + let hfileName = path.basename(hFilePath, '.h'); + let tsFilePath = re.pathJoin(destDir, '%s.d.ts'.format(hfileName)); + let tsContent = genTsContent(rootInfo); + writeFile(tsFilePath, tsContent); } module.exports = { - doGenerate -} + doGenerate, +}; -- Gitee From e316627dbbba49e2292ff23898e1b470d49bcef0 Mon Sep 17 00:00:00 2001 From: LiYuxi Date: Thu, 11 Jul 2024 16:00:57 +0800 Subject: [PATCH 10/12] modify h2dtscpp main Signed-off-by: LiYuxi --- src/cli/h2dtscpp/src/src/main.js | 40 ++++++++++++++++---------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/cli/h2dtscpp/src/src/main.js b/src/cli/h2dtscpp/src/src/main.js index 59eaede2..e7e6ab04 100644 --- a/src/cli/h2dtscpp/src/src/main.js +++ b/src/cli/h2dtscpp/src/src/main.js @@ -13,50 +13,50 @@ * limitations under the License. */ const fs = require('fs'); -const path = require('path') -const stdio = require("stdio"); -const main = require("./TsGen/tsMain"); +const path = require('path'); +const stdio = require('stdio'); +const main = require('./TsGen/tsMain'); let ops = stdio.getopt({ // 输入的.h文件路径,必填 - 'filename': { key: 'f', args: 1, description: ".h file", default: "" }, + 'filename': { key: 'f', args: 1, description: '.h file', default: '' }, // 可选参数,测试文件路径 - 'testFilename': { key: 't', args: 1, description: "Ability.test.ets file", default: "" }, + 'testFilename': { key: 't', args: 1, description: 'Ability.test.ets file', default: '' }, // 可选参数, 声明文件路径 - 'indexFilename': { key: 'i', args: 1, description: "index.d.ts file", default: "" }, + 'indexFilename': { key: 'i', args: 1, description: 'index.d.ts file', default: '' }, // 可选参数, cpp文件路径 - 'outCppPath': { key: 'o', args: 1, description: ".cpp dir path", default: "" }, + 'outCppPath': { key: 'o', args: 1, description: '.cpp dir path', default: '' }, }); // 获取命令行参数 .h文件路径 -let filePath = ops.filename -let testFilePath = ops.testFilename -let tsFilePath = ops.indexFilename -let cppFilePath = ops.outCppPath +let filePath = ops.filename; +let testFilePath = ops.testFilename; +let tsFilePath = ops.indexFilename; +let cppFilePath = ops.outCppPath; // 读取文件内容 判断参数是否为空 if (filePath !== '') { // 若用户没有提供路径 则程序提供默认路径 if (!tsFilePath) { - createDirectorySync(path.join(filePath, '../tsout')) + createDirectorySync(path.join(filePath, '../tsout')); tsFilePath = path.join(filePath, '../tsout/index.d.ts'); } if (!testFilePath) { testFilePath = path.join(filePath, '../testout'); - createDirectorySync(testFilePath) + createDirectorySync(testFilePath); } - if(!cppFilePath) { + if (!cppFilePath) { // 若用户未给定cpp生成路径,则在.h路径下直接生成out路径 cppFilePath = path.join(filePath, '../cppout'); - createDirectorySync(cppFilePath) + createDirectorySync(cppFilePath); } main.doGenerate(filePath, testFilePath, tsFilePath, cppFilePath); } function createDirectorySync(directoryPath) { - try { - fs.mkdirSync(directoryPath, { recursive: true }); - } catch (err) { - console.error(`无法创建文件夹 ${directoryPath}: ${err}`); - } + try { + fs.mkdirSync(directoryPath, { recursive: true }); + } catch (err) { + console.error(`无法创建文件夹 ${directoryPath}: ${err}`); + } } \ No newline at end of file -- Gitee From bc2a203e32e70381751e781db965af6457993f9a Mon Sep 17 00:00:00 2001 From: LiYuxi Date: Thu, 11 Jul 2024 16:01:21 +0800 Subject: [PATCH 11/12] modify dts2cpp/src/gen/ Signed-off-by: LiYuxi --- src/cli/dts2cpp/src/gen/analyze/function.js | 2 +- src/cli/dts2cpp/src/gen/analyze/interface.js | 2 +- src/cli/dts2cpp/src/gen/analyze/namespace.js | 2 +- src/cli/dts2cpp/src/gen/generate/return_generate.js | 3 ++- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/analyze/function.js b/src/cli/dts2cpp/src/gen/analyze/function.js index 80b1e253..56364be1 100644 --- a/src/cli/dts2cpp/src/gen/analyze/function.js +++ b/src/cli/dts2cpp/src/gen/analyze/function.js @@ -225,7 +225,7 @@ function getArrowCallFunc(tmp, results) { 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); diff --git a/src/cli/dts2cpp/src/gen/analyze/interface.js b/src/cli/dts2cpp/src/gen/analyze/interface.js index 86c5f784..66a4ebbe 100644 --- a/src/cli/dts2cpp/src/gen/analyze/interface.js +++ b/src/cli/dts2cpp/src/gen/analyze/interface.js @@ -25,7 +25,7 @@ function analyzeNoNameInterface(valueType, valueName, rsltInterface) { 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') + interfaceBody = re.replaceAll(interfaceBody, ',', ';\n'); rsltInterface.push({ name: interfaceTypeName, body: analyzeInterface(interfaceBody, rsltInterface), diff --git a/src/cli/dts2cpp/src/gen/analyze/namespace.js b/src/cli/dts2cpp/src/gen/analyze/namespace.js index 6c24b3c6..84259b3f 100644 --- a/src/cli/dts2cpp/src/gen/analyze/namespace.js +++ b/src/cli/dts2cpp/src/gen/analyze/namespace.js @@ -51,7 +51,7 @@ function analyzeNamespace(data) { while (data !== '\n') { let oldData = data; data = removeEmptyLine(data); - let matchs = re.match(' *\n*', data) + let matchs = re.match(' *\n*', data); data = preProcessData(data); // 只剩下空格和回车时,解析完成 if (matchs && matchs.regs[0][1] === data.length) { diff --git a/src/cli/dts2cpp/src/gen/generate/return_generate.js b/src/cli/dts2cpp/src/gen/generate/return_generate.js index b94045b3..39516f6a 100644 --- a/src/cli/dts2cpp/src/gen/generate/return_generate.js +++ b/src/cli/dts2cpp/src/gen/generate/return_generate.js @@ -139,7 +139,7 @@ function cToJs(value, type, dest, deep = 1, optional, enumType = 0) { var propertyName = delPrefix(value); if (checkRetIsUndefined(type)) { NapiLog.logError('type is invalid!'); - return; + return undefined; } if (type.indexOf('|') >= 0) { return unionTempleteFunc(value, type, dest, optional); @@ -184,6 +184,7 @@ function cToJs(value, type, dest, deep = 1, optional, enumType = 0) { else { NapiLog.logError(`\n---- This type do not generate cToJs %s,%s,%s ----\n. ` .format(value, type, dest), getLogErrInfo()); + return undefined; } } -- Gitee From d93994c34c3bfc0d3c93cac4e5f0efee3203abe5 Mon Sep 17 00:00:00 2001 From: LiYuxi Date: Thu, 11 Jul 2024 16:12:13 +0800 Subject: [PATCH 12/12] modify dts2cpp/src/gen/genarete/return_generate_js Signed-off-by: LiYuxi --- src/cli/dts2cpp/src/gen/generate/return_generate.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/cli/dts2cpp/src/gen/generate/return_generate.js b/src/cli/dts2cpp/src/gen/generate/return_generate.js index 39516f6a..431c39d2 100644 --- a/src/cli/dts2cpp/src/gen/generate/return_generate.js +++ b/src/cli/dts2cpp/src/gen/generate/return_generate.js @@ -182,8 +182,7 @@ function cToJs(value, type, dest, deep = 1, optional, enumType = 0) { return objectTempleteFuncReturn(value); } else { - NapiLog.logError(`\n---- This type do not generate cToJs %s,%s,%s ----\n. ` - .format(value, type, dest), getLogErrInfo()); + NapiLog.logError(`\n---- This type do not generate cToJs %s,%s,%s ----\n. `.format(value, type, dest), getLogErrInfo()); return undefined; } } -- Gitee