1/* 2* Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development Co., Ltd. 3* Licensed under the Apache License, Version 2.0 (the "License"); 4* you may not use this file except in compliance with the License. 5* You may obtain a copy of the License at 6* 7* http://www.apache.org/licenses/LICENSE-2.0 8* 9* Unless required by applicable law or agreed to in writing, software 10* distributed under the License is distributed on an "AS IS" BASIS, 11* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12* See the License for the specific language governing permissions and 13* limitations under the License. 14*/ 15const re = require("../tools/re"); 16const { checkOutBody, print } = require("../tools/tool"); 17const { FuncType } = require("../tools/common"); 18const { NapiLog } = require("../tools/NapiLog"); 19 20/**函数参数解析 */ 21function analyzeParams(funcName, values) { 22 let result = [] 23 let funcType = FuncType.DIRECT 24 let optionalParamCount = 0; // 可选参数的个数 25 while (values.length > 0) { 26 let v = checkOutBody(values, 0, ["", ","]) 27 if (v == null) 28 v = values 29 values = values.substring(v.length, values.length) 30 let matchs = re.match("([a-zA-Z_0-9\\.]+)(\\?*): *([a-zA-Z<,>|_0-9\\[\\]\\(\\):='{}]+)", v) 31 if (matchs == null && (funcName == "on" || funcName == "off")) { 32 // on和off的第一个参数的类型可以是一串字符 33 matchs = re.match("([a-zA-Z_0-9\\.]+)(\\?*): *\"([a-zA-Z|_0-9\\[\\]\\(\\):='{}]+)\"", v) 34 } 35 if (matchs != null) { 36 let type = re.getReg(v, matchs.regs[3]) 37 if (type.indexOf("Map") < 0) { 38 type = type.replace(/,/g, "") 39 } 40 41 let optionalFlag = re.getReg(v, matchs.regs[2]) == '?' ? true : false; 42 let checkParamOk = true; 43 if (optionalFlag) { 44 optionalParamCount++; 45 } else if (optionalParamCount > 0) { 46 // 可选参数之后不能再有必选参数,必选都是可选参数。 47 NapiLog.logError("Invalid parameter [%s] of function [%s],".format(v, funcName) 48 + " the required parameter cannot follow an optional parameter."); 49 checkParamOk = false; 50 } 51 if (checkParamOk) { 52 result.push({ "name": re.getReg(v, matchs.regs[1]), "type": type , "optional": optionalFlag}) 53 if (type.indexOf("AsyncCallback") >= 0) 54 funcType = FuncType.ASYNC 55 if (funcType == FuncType.DIRECT && type.indexOf("Callback") >= 0 && type.indexOf("AsyncCallback") < 0) 56 funcType = FuncType.SYNC 57 } 58 } 59 else { 60 NapiLog.logError("方法[%s]的参数列表[%s]解析失败。".format(funcName, v)); 61 NapiLog.logError("Failed to analyse parameter [%s] of function [%s].".format(v, funcName)); 62 } 63 } 64 return [result, funcType] 65} 66 67module.exports = { 68 analyzeParams 69}