modify dts2ets/appCodeGen/src/tools/

Signed-off-by: LiYuxi <liyuxi@kaihong.com>
This commit is contained in:
LiYuxi 2024-07-11 15:31:02 +08:00
parent b2a9a834f2
commit 189b5c7c1f
5 changed files with 436 additions and 431 deletions

View File

@ -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 (!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);
}
let calculateResult = calculate(value, target, at);
isContinue = calculateResult[0];
target = calculateResult[1];
at = calculateResult[2];
}
}
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
target = uint8Array(tlen, target);
}
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
}
readFile,
writeFile,
};

View File

@ -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)
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)
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
}
NapiLog,
};

View File

@ -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)
if (tt !== null && tt !== undefined) {
let res = ''
let len = tt.regs.length
for (let i=1; i<len; i++) {
let regs1 = re.getReg(type, tt.regs[i])
res += regs1
}
return res
}
tt = re.match("Array<map<string", type)
if (tt !== null && tt !== undefined) {
let preStr = 'Array<'
let preStrLen = preStr.length
let res = type.substring(preStrLen, type.length-1)
return res
return re.getReg(type, tt.regs[1]);
}
tt = re.match("Array<Map<string", type)
tt = re.match('Array<{([[a-z:]+)([a-z:]]+)([a-zA-Z_1-9:]+)', type);
if (tt !== null && tt !== undefined) {
let preStr = 'Array<'
let preStrLen = preStr.length
let res = type.substring(preStrLen, type.length-1)
return res
}
return null
let res = '';
let len = tt.regs.length;
for (let i = 1; i < len; i++) {
let regs1 = re.getReg(type, tt.regs[i]);
res += regs1;
}
return res;
}
tt = re.match('Array<map<string', type);
if (tt !== null && tt !== undefined) {
let preStr = 'Array<';
let preStrLen = preStr.length;
let res = type.substring(preStrLen, type.length - 1);
return res;
}
tt = re.match('Array<Map<string', type);
if (tt !== null && tt !== undefined) {
let preStr = 'Array<';
let preStrLen = preStr.length;
let res = type.substring(preStrLen, type.length - 1);
return res;
}
return null;
}
function getArrayTypeTwo(type) {
let tt = re.match("([a-zA-Z_0-9]+)", type)
return re.getReg(type, tt.regs[1])
let tt = re.match('([a-zA-Z_0-9]+)', type);
return re.getReg(type, tt.regs[1]);
}
function jsType2CType(jsTypeName) {
if (jsTypeName === "string") {
return "std::string"
} else if (jsTypeName === "boolean") {
return "bool"
if (jsTypeName === 'string') {
return 'std::string';
} else if (jsTypeName === 'boolean') {
return 'bool';
} else {
return jsTypeName
return jsTypeName;
}
}
class EnumValueType { }
EnumValueType.ENUM_VALUE_TYPE_NUMBER = 0
EnumValueType.ENUM_VALUE_TYPE_STRING = 1
EnumValueType.ENUM_VALUE_TYPE_NUMBER = 0;
EnumValueType.ENUM_VALUE_TYPE_STRING = 1;
function isEnum(type, data) {
let isEnum = false
let isEnum = false;
if (null === data || undefined === data) {
return isEnum
return isEnum;
}
for (let i in data.enum) {
let enumm = data.enum[i]
let enumm = data.enum[i];
if (type === enumm.name) {
isEnum = true
isEnum = true;
}
}
return isEnum
return isEnum;
}
function enumIndex(type, data) {
let index;
if (null === data) {
return index
return index;
}
for (let i in data.enum) {
let enumm = data.enum[i]
let enumm = data.enum[i];
if (type === enumm.name) {
index = i
index = i;
}
}
return index
return index;
}
function isType(type, data) {
let isType = false
if (null === data) {
return isType
}
for (let i in data.type) {
let typee = data.type[i]
if (type === typee.name) {
isType = true
let isType = false;
if (null === data) {
return isType;
}
}
return isType
for (let i in data.type) {
let typee = data.type[i];
if (type === typee.name) {
isType = true;
}
}
return isType;
}
function typeIndex(type, data) {
let index;
if (null === data) {
return index
}
for (let i in data.type) {
let typee = data.type[i]
if (type === typee.name) {
index = i
}
}
return index
let index;
if (null === data) {
return index;
}
for (let i in data.type) {
let typee = data.type[i];
if (type === typee.name) {
index = i;
}
}
return index;
}
function getMapType(type) {
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)
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)
if (ttArray === null) {
ttArray = re.search('([a-zA-Z_0-9]+)\\[\\]>', type);
}
let valueType
let valueMapType
let valueArrayType
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
}
isCreateThreadsafeFunc,
};

View File

@ -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
}
all,
};

View File

@ -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,
};