modify codecheck

Signed-off-by: zhaoxudong <zhaoxudong@kaihongdigi.com>
This commit is contained in:
zhaoxudong 2022-02-07 16:55:54 +08:00
parent 529b850b7b
commit 7be114c574
30 changed files with 429 additions and 372 deletions

3
napi_tool/.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

6
napi_tool/.idea/misc.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_X" project-jdk-name="16" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/napi_tool.iml" filepath="$PROJECT_DIR$/.idea/napi_tool.iml" />
</modules>
</component>
</project>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

6
napi_tool/.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

70
napi_tool/OAT.xml Normal file
View File

@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright (c) 2021 Huawei Device Co., Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- OAT(OSS Audit Tool) configuration guide:
basedir: Root dir, the basedir + project path is the real source file location.
licensefile:
1.If the project don't have "LICENSE" in root dir, please define all the license files in this project in , OAT will check license files according to this rule.
tasklist(only for batch mode):
1. task: Define oat check thread, each task will start a new thread.
2. task name: Only an name, no practical effect.
3. task policy: Default policy for projects under this task, this field is required and the specified policy must defined in policylist.
4. task filter: Default filefilter for projects under this task, this field is required and the specified filefilter must defined in filefilterlist.
5. task project: Projects to be checked, the path field define the source root dir of the project.
policyList:
1. policy: All policyitems will be merged to default OAT.xml rules, the name of policy doesn't affect OAT check process.
2. policyitem: The fields type, name, path, desc is required, and the fields rule, group, filefilter is optional,the default value is:
<policyitem type="" name="" path="" desc="" rule="may" group="defaultGroup" filefilter="defaultPolicyFilter"/>
3. policyitem type:
"compatibility" is used to check license compatibility in the specified path;
"license" is used to check source license header in the specified path;
"copyright" is used to check source copyright header in the specified path;
"import" is used to check source dependency in the specified path, such as import ... ,include ...
"filetype" is used to check file type in the specified path, supported file types: archive, binary
"filename" is used to check whether the specified file exists in the specified path(support projectroot in default OAT.xml), supported file names: LICENSE, README, README.OpenSource
4. policyitem name: This field is used for define the license, copyright, "*" means match all, the "!" prefix means could not match this value. For example, "!GPL" means can not use GPL license.
5. policyitem path: This field is used for define the source file scope to apply this policyitem, the "!" prefix means exclude the files. For example, "!.*/lib/.*" means files in lib dir will be exclude while process this policyitem.
6. policyitem rule and group: These two fields are used together to merge policy results. "may" policyitems in the same group means any one in this group passed, the result will be passed.
7. policyitem filefilter: Used to bind filefilter which define filter rules.
8. filefilter: Filter rules, the type filename is used to filter file name, the type filepath is used to filter file path.
Note:If the text contains special characters, please escape them according to the following rules:
" == &gt;
& == &gt;
' == &gt;
< == &gt;
> == &gt;
-->
<configuration>
<oatconfig>
<licensefile></licensefile>
<policylist>
<policy name="projectPolicy" desc="">
<policyitem type="copyright" name="Copyright (c) 2022 Shenzhen Kaihong Digital" path=".*" rule="may" group="defaultGroup" filefilter="copyrightPolicyFilter" desc=""/>
</policy>
</policylist>
<filefilterlist>
<filefilter name="binaryFileTypePolicyFilter" desc="Filters for binaryFile" >
<filteritem type="filename" name="*.jpg" desc="all jpg file have check "/>
<filteritem type="filename" name="*.gif" desc="all gif file have check "/>
<filteritem type="filename" name="*.png" desc="all png file have check "/>
</filefilter>
</filefilterlist>
</oatconfig>
</configuration>

View File

@ -33,8 +33,8 @@ function activate(context) {
let disposable = vscode.commands.registerCommand('generate_napi', function (uri) {
// The code you place here will be executed every time your command is executed
// Display a message box to the user
vscode.window.showInformationMessage("正在生成"+uri.fsPath);
xgen.DoGenerate(uri.fsPath);
vscode.window.showInformationMessage("正在生成" + uri.fsPath);
xgen.doGenerate(uri.fsPath);
vscode.window.showInformationMessage("生成成功");
});
@ -42,7 +42,7 @@ function activate(context) {
}
// this method is called when your extension is deactivated
function deactivate() {}
function deactivate() { }
module.exports = {
activate,

View File

@ -13,18 +13,18 @@
* limitations under the License.
*/
const re = require("./tools/re");
const { print, RemoveExplains, RemoveEmptyLine, CheckOutBody } = require("./tools/tool");
const { print, removeExplains, removeEmptyLine, checkOutBody } = require("./tools/tool");
const { FuncType, NumberIncrease } = require("./tools/common");
const { ReadFile } = require("./tools/FileRW");
const { readFile } = require("./tools/FileRW");
const { AnalyzeNamespace } = require("./analyze/namespace");
const { analyzeNamespace } = require("./analyze/namespace");
function AnalyzeFile(fn) {
NumberIncrease.Reset();
let data = ReadFile(fn);
function analyzeFile(fn) {
NumberIncrease.reset();
let data = readFile(fn);
// print("[",fn,"]")
data = RemoveExplains(data)//去除注释
data = RemoveEmptyLine(data)//去除空行
data = removeExplains(data)//去除注释
data = removeEmptyLine(data)//去除空行
while (true) {//去除import
let tt = re.search("import ([{}A-Za-z ,]+) from [\"']{1}([@./a-zA-Z]+)[\"']{1};*", data);
if (tt != null) data = re.removeReg(data, tt.regs[0]);
@ -42,7 +42,7 @@ function AnalyzeFile(fn) {
}
while (true) {
let oldData = data
data = RemoveEmptyLine(data)
data = removeEmptyLine(data)
let tt = re.match(" *\n*", data)
if (tt && tt.regs[0][1] == data.length) break//只剩下空格和回车时,解析完成
@ -73,7 +73,7 @@ function AnalyzeFile(fn) {
tt = re.match("(export )*type ([a-zA-Z]+) = ({)", data)
if (tt) {
let exportName = re.getReg(data, tt.regs[2])
let exportBody = CheckOutBody(data, tt.regs[3][0], null, true)
let exportBody = checkOutBody(data, tt.regs[3][0], null, true)
data = data.substring(tt.regs[3][1] + exportBody.length + 2, data.length)
result.declareType.push({
name: exportName,
@ -90,7 +90,7 @@ function AnalyzeFile(fn) {
{
let namespaceName = re.getReg(data, tt.regs[1])
// print(1, "declare namespace", namespaceName)
let namespaceData = CheckOutBody(data, tt.regs[2][0], null, true)
let namespaceData = checkOutBody(data, tt.regs[2][0], null, true)
// XGenerate.gi().Start(re.getFileInPath(ifname), namespaceName)
// CheckOutDeclare(data)
// XGenerate.gi().End(re.getPathInPath(ifname))//odname
@ -98,7 +98,7 @@ function AnalyzeFile(fn) {
result.declareNamespace.push({
name: namespaceName,
// zzzz: "zzzz",//this is namespace
body: AnalyzeNamespace(namespaceData)
body: analyzeNamespace(namespaceData)
})
continue;
}
@ -107,7 +107,7 @@ function AnalyzeFile(fn) {
if (tt) {
let interfaceName = re.getReg(data, tt.regs[3])
// print(1, "declare interface", interfaceName)
let interfaceData = CheckOutBody(data, tt.regs[5][0], null, true)
let interfaceData = checkOutBody(data, tt.regs[5][0], null, true)
data = data.substring(tt.regs[5][1] + interfaceData.length + 1, data.length)
result.declareInterface.push({
name: interfaceName,
@ -144,5 +144,5 @@ function AnalyzeFile(fn) {
}
module.exports = {
AnalyzeFile
analyzeFile
}

View File

@ -13,19 +13,19 @@
* limitations under the License.
*/
const re = require("../tools/re");
const { print, RemoveExplains, RemoveEmptyLine, CheckOutBody } = require("../tools/tool");
const { print, removeExplains, removeEmptyLine, checkOutBody } = require("../tools/tool");
const { FuncType, NumberIncrease } = require("../tools/common");
const { AnalyzeParams } = require("./params");
const { AnalyzeReturn } = require("./return");
const { analyzeParams } = require("./params");
const { analyzeReturn } = require("./return");
/**函数解析 */
function AnalyzeFunction(name, values, ret) {
function analyzeFunction(name, values, ret) {
values = re.replaceAll(re.replaceAll(values, " ", ""), "\n", "")
let tmp = AnalyzeParams(values)
let tmp = analyzeParams(values)
values = tmp[0]
let funcType = tmp[1]
tmp = AnalyzeReturn(ret)
tmp = analyzeReturn(ret)
ret = tmp[0]
if (tmp[1])
funcType = FuncType.PROMISE
@ -39,11 +39,11 @@ function AnalyzeFunction(name, values, ret) {
for (let j in values) {
let v = values[j]
if (v["type"].indexOf("number") >= 0) {
v["type"] = v["type"].replace("number", "NUMBER_TYPE_" + NumberIncrease.GetAndIncrease())
v["type"] = v["type"].replace("number", "NUMBER_TYPE_" + NumberIncrease.getAndIncrease())
}
}
if (ret.indexOf("number") >= 0) {
ret = ret.replace("number", "NUMBER_TYPE_" + NumberIncrease.GetAndIncrease())
ret = ret.replace("number", "NUMBER_TYPE_" + NumberIncrease.getAndIncrease())
}
let result = {
@ -56,5 +56,5 @@ function AnalyzeFunction(name, values, ret) {
}
module.exports = {
AnalyzeFunction
analyzeFunction
}

View File

@ -13,13 +13,13 @@
* limitations under the License.
*/
const re = require("../tools/re");
const { print, RemoveExplains, RemoveEmptyLine, CheckOutBody } = require("../tools/tool");
const { print, removeExplains, removeEmptyLine, checkOutBody } = require("../tools/tool");
const { FuncType, NumberIncrease } = require("../tools/common");
const { AnalyzeFunction } = require("./function");
const { analyzeFunction } = require("./function");
/**interface解析 */
function AnalyzeInterface(data) {//same as class
function analyzeInterface(data) {//same as class
let body = re.replaceAll(data, "\n", "").split(";")// # replace(" ", "").
// print(body)
let result = {
@ -40,7 +40,7 @@ function AnalyzeInterface(data) {//same as class
let valueName = re.getReg(t, tt.regs[1])
let valueType = re.getReg(t, tt.regs[2])
if (valueType.indexOf("number") >= 0) {
valueType = valueType.replace("number", "NUMBER_TYPE_" + NumberIncrease.GetAndIncrease())
valueType = valueType.replace("number", "NUMBER_TYPE_" + NumberIncrease.getAndIncrease())
}
result.value.push({
name: valueName,
@ -50,7 +50,7 @@ function AnalyzeInterface(data) {//same as class
}
tt = re.match(" *([A-Za-z0-9_]+)\\(([\n a-zA-Z:;=,_0-9?<>{}|]*)\\) *: *([A-Za-z0-9_<>{}:, .]+)", t)
if (tt) {//函数
let funcDetail = AnalyzeFunction(re.getReg(t, tt.regs[1]),
let funcDetail = analyzeFunction(re.getReg(t, tt.regs[1]),
re.getReg(t, tt.regs[2]), re.getReg(t, tt.regs[3]))
if (funcDetail != null)
result.function.push(funcDetail)
@ -61,5 +61,5 @@ function AnalyzeInterface(data) {//same as class
}
module.exports = {
AnalyzeInterface
analyzeInterface
}

View File

@ -13,14 +13,14 @@
* limitations under the License.
*/
const re = require("../tools/re");
const { print, RemoveExplains, RemoveEmptyLine, CheckOutBody } = require("../tools/tool");
const { print, removeExplains, removeEmptyLine, checkOutBody } = require("../tools/tool");
const { FuncType, NumberIncrease } = require("../tools/common");
const { AnalyzeFunction } = require("./function");
const { AnalyzeInterface } = require("./interface");
const { analyzeFunction } = require("./function");
const { analyzeInterface } = require("./interface");
/**namespace解析 */
function AnalyzeNamespace(data) {
function analyzeNamespace(data) {
let result = {
exports: [],
@ -35,14 +35,14 @@ function AnalyzeNamespace(data) {
}
while (data != '\n') {
let oldData = data
data = RemoveEmptyLine(data)
data = removeEmptyLine(data)
let tt = re.match(" *\n*", data)
if (tt && tt.regs[0][1] == data.length) break//只剩下空格和回车时,解析完成
tt = re.match("(export )*enum *([A-Za-z]+) *({)", data)
if (tt != null) {
let enumName = re.getReg(data, tt.regs[2]);
let enumBody = CheckOutBody(data, tt.regs[3][0], null, null)
let enumBody = checkOutBody(data, tt.regs[3][0], null, null)
result.enum.push({
name: enumName,
body: enumBody.substring(1, -1)
@ -71,11 +71,11 @@ function AnalyzeNamespace(data) {
tt = re.match("(export )*interface ([A-Za-z_0-9]+)(<T>)* (extends [a-zA-Z]+ )*({)", data)
if (tt) {
let interfaceName = re.getReg(data, tt.regs[2])
let interfaceBody = CheckOutBody(data, tt.regs[5][0], null, null)
let interfaceBody = checkOutBody(data, tt.regs[5][0], null, null)
// print(interfaceBody)
result.interface.push({
name: interfaceName,
body: AnalyzeInterface(interfaceBody.substring(1, interfaceBody.length - 1))
body: analyzeInterface(interfaceBody.substring(1, interfaceBody.length - 1))
})
// XGenerate.gi().AddInterface(re.getReg(data,tt.regs[2]),
// data1.substring(1,data1.length-1))
@ -92,8 +92,8 @@ function AnalyzeNamespace(data) {
if (tt) {
let funcName = re.getReg(data, tt.regs[2])
// print(funcName)
let funcValue = CheckOutBody(data, tt.regs[3][0], ["(", ")"], null)
let funcRet = CheckOutBody(data.substring(tt.regs[3][0] + funcValue.length), 0, ["", "\n"], null)
let funcValue = checkOutBody(data, tt.regs[3][0], ["(", ")"], null)
let funcRet = checkOutBody(data.substring(tt.regs[3][0] + funcValue.length), 0, ["", "\n"], null)
data = data.substring(tt.regs[3][0] + funcValue.length + funcRet.length)
// print(funcValue)
@ -107,7 +107,7 @@ function AnalyzeNamespace(data) {
funcRet = "void"
}
let funcDetail = AnalyzeFunction(funcName, funcValue.substring(1, funcValue.length - 1), funcRet)
let funcDetail = analyzeFunction(funcName, funcValue.substring(1, funcValue.length - 1), funcRet)
if (funcDetail != null)
result.function.push(funcDetail)
@ -134,7 +134,7 @@ function AnalyzeNamespace(data) {
tt = re.match("(export )*type ([a-zA-Z]+) = ({)", data)
if (tt) {
let typeName = re.getReg(data, tt.regs[2]);
let typeBody = CheckOutBody(data, tt.regs[3][0], null, true)
let typeBody = checkOutBody(data, tt.regs[3][0], null, true)
result.type.push({
name: typeName,
body: typeBody
@ -149,7 +149,7 @@ function AnalyzeNamespace(data) {
tt = re.match("(export )*class ([a-zA-Z]+) (extends [a-zA-Z]+ )*(implements [a-zA-Z]+ )*({)", data)
if (tt) {
let className = re.getReg(data, tt.regs[2])
let classBody = CheckOutBody(data, tt.regs[5][0], null, true)
let classBody = checkOutBody(data, tt.regs[5][0], null, true)
result.class.push({
name: className,
body: classBody
@ -166,10 +166,10 @@ function AnalyzeNamespace(data) {
tt = re.match("(export )*namespace ([a-zA-Z0-9]+) ({)", data)
if (tt) {
let namespaceName = re.getReg(data, tt.regs[2])
let namespaceBody = CheckOutBody(data, tt.regs[3][0], null, true)
let namespaceBody = checkOutBody(data, tt.regs[3][0], null, true)
result.namespace.push({
name: namespaceName,
body: AnalyzeNamespace(namespaceBody)
body: analyzeNamespace(namespaceBody)
})
data = data.substring(tt.regs[3][0] + namespaceBody.length + 2, data.length)
if (tt.regs[1][0] != -1) {
@ -211,5 +211,5 @@ function AnalyzeNamespace(data) {
}
module.exports = {
AnalyzeNamespace
analyzeNamespace
}

View File

@ -13,15 +13,15 @@
* limitations under the License.
*/
const re = require("../tools/re");
const { print, RemoveExplains, RemoveEmptyLine, CheckOutBody } = require("../tools/tool");
const { FuncType,NumberIncrease } = require("../tools/common");
const { print, removeExplains, removeEmptyLine, checkOutBody } = require("../tools/tool");
const { FuncType, NumberIncrease } = require("../tools/common");
/**函数参数解析 */
function AnalyzeParams(values) {
function analyzeParams(values) {
let result = []
let funcType = FuncType.DIRECT
while (values.length > 0) {
let v = CheckOutBody(values, 0, ["", ","])
let v = checkOutBody(values, 0, ["", ","])
if (v == null)
v = values
values = values.substring(v.length, values.length)
@ -44,5 +44,5 @@ function AnalyzeParams(values) {
}
module.exports = {
AnalyzeParams
analyzeParams
}

View File

@ -13,11 +13,11 @@
* limitations under the License.
*/
const re = require("../tools/re");
const { print, RemoveExplains, RemoveEmptyLine, CheckOutBody } = require("../tools/tool");
const { FuncType,NumberIncrease } = require("../tools/common");
const { print, removeExplains, removeEmptyLine, checkOutBody } = require("../tools/tool");
const { FuncType, NumberIncrease } = require("../tools/common");
/**函数返回值解析 */
function AnalyzeReturn(ret) {
function analyzeReturn(ret) {
let isPromise = false
if (ret.indexOf("Promise") >= 0) {
isPromise = true
@ -26,5 +26,5 @@ function AnalyzeReturn(ret) {
}
module.exports = {
AnalyzeReturn
analyzeReturn
}

View File

@ -14,30 +14,25 @@
*/
const main = require("./main");
const re = require("./tools/re");
function print(...args)
{
function print(...args) {
console.log(...args)
}
let usageStr=`usage:
let usageStr = `usage:
cmd_gen-win.exe d:\\@ohos.youmodulename.d.ts`
if(process.argv.length<=2)
{
if (process.argv.length <= 2) {
print(usageStr)
}
else
{
let fn=re.getFileInPath(process.argv[2])
let tt=re.match("@ohos.[a-zA-Z0-9]+.d.ts",fn)
if(tt)
{
main.DoGenerate(process.argv[2])
else {
let fn = re.getFileInPath(process.argv[2])
let tt = re.match("@ohos.[a-zA-Z0-9]+.d.ts", fn)
if (tt) {
main.doGenerate(process.argv[2])
}
else
{
print("\n文件名 "+fn+" 校验失败,需要符合 @ohos.xxx.d.ts")
else {
print("\n文件名 " + fn + " 校验失败,需要符合 @ohos.xxx.d.ts")
}
}

View File

@ -12,7 +12,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const { WriteFile } = require("../tools/FileRW");
const { writeFile } = require("../tools/FileRW");
const re = require("../tools/re");
let gypTemplete = `
@ -32,14 +32,14 @@ let gypTemplete = `
`
/**创建nodejs编译文件用于在ubuntu测试 */
function GenerateGYP(destDir, implName) {
function generateGYP(destDir, implName) {
let ss = gypTemplete.ReplaceAll("[implName]", implName)
WriteFile(re.pathJoin(destDir, "binding.gyp"), ss)
writeFile(re.pathJoin(destDir, "binding.gyp"), ss)
writeFile(re.pathJoin(destDir, "test.sh"), "node-gyp configure build && sleep 0.5 && node --expose-gc test.js")
WriteFile(re.pathJoin(destDir, "test.sh"), "node-gyp configure build && sleep 0.5 && node --expose-gc test.js")
}
module.exports = {
GenerateGYP
generateGYP
}

View File

@ -12,7 +12,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const { WriteFile } = require("../tools/FileRW");
const { writeFile } = require("../tools/FileRW");
const re = require("../tools/re");
let gnTemplete = `\
@ -48,11 +48,11 @@ ohos_shared_library("[implName]")
`
/**创建nodejs编译文件用于在ubuntu测试 */
function GenerateGN(destDir, implName) {
function generateGN(destDir, implName) {
let ss = gnTemplete.ReplaceAll("[implName]", implName)
WriteFile(re.pathJoin(destDir, "BUILD.gn"), ss)
writeFile(re.pathJoin(destDir, "BUILD.gn"), ss)
}
module.exports = {
GenerateGN
generateGN
}

View File

@ -12,7 +12,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const { WriteFile } = require("../tools/FileRW");
const { writeFile } = require("../tools/FileRW");
const re = require("../tools/re");
let xNapiToolH = `\
@ -551,7 +551,8 @@ void XNapiTool::DefineClass(const char *className, napi_callback constructorFunc
funcs[p++] = {it->first, 0, it->second, 0, 0, 0, napi_default, 0};
}
napi_status result_status = napi_define_class(env_, className, NAPI_AUTO_LENGTH, constructorFunc, nullptr, p, funcs, &tmpClass);
napi_status result_status = napi_define_class(env_, className, NAPI_AUTO_LENGTH, constructorFunc,
nullptr, p, funcs, &tmpClass);
CC_ASSERT(result_status == napi_ok);
result_status = napi_set_named_property(env_, dest, className, tmpClass);
@ -603,11 +604,11 @@ void *XNapiTool::GetAsyncInstance()
}
`
function GenerateBase(destDir) {
WriteFile(re.pathJoin(destDir, "x_napi_tool.h"), xNapiToolH)
WriteFile(re.pathJoin(destDir, "x_napi_tool.cpp"), xNapiToolCpp)
function generateBase(destDir) {
writeFile(re.pathJoin(destDir, "x_napi_tool.h"), xNapiToolH)
writeFile(re.pathJoin(destDir, "x_napi_tool.cpp"), xNapiToolCpp)
}
module.exports = {
GenerateBase
generateBase
}

View File

@ -15,12 +15,12 @@
//生成BUILD.gn
//生成x_napi_tool.h生成x_napi_tool.cpp
const { ReplaceAll, print } = require("./tools/tool");
const { GenerateNamespace } = require("./generate/namespace");
const { WriteFile } = require("./tools/FileRW");
const { generateNamespace } = require("./generate/namespace");
const { writeFile } = require("./tools/FileRW");
const re = require("./tools/re");
const { GenerateGYP } = require("./extend/binding_gyp");
const { GenerateGN } = require("./extend/build_gn");
const { GenerateBase } = require("./extend/x_napi_tool");
const { generateGYP } = require("./extend/binding_gyp");
const { generateGN } = require("./extend/build_gn");
const { generateBase } = require("./extend/x_napi_tool");
const { NumberIncrease } = require("./tools/common");
let moduleCppTmplete = `\
@ -84,7 +84,7 @@ extern "C" __attribute__((constructor)) void Register_[implName]_Module(void)
}
`
let implH_templete = `\
let implHTemplete = `\
#ifndef IMPL_[impl_name_upper]_H
#define IMPL_[impl_name_upper]_H
@ -101,43 +101,43 @@ let implH_templete = `\
#endif // IMPL_[impl_name_upper]_H
`
let implCpp_templete = `\
let implCppTemplete = `\
#include "[implName].h"
[implCpp_detail]
`
function GenerateAll(structOfTs, destDir) {
function generateAll(structOfTs, destDir) {
let ns0 = structOfTs.declareNamespace[0];
let result = GenerateNamespace(ns0.name, ns0.body)
let result = generateNamespace(ns0.name, ns0.body)
let numberUsing = ""
for (let i = 1; i < NumberIncrease.Get(); i++) {
for (let i = 1; i < NumberIncrease.get(); i++) {
numberUsing += "using NUMBER_TYPE_%d = uint32_t;\n".format(i)
}
let middleCpp = ReplaceAll(moduleCppTmplete, "[body_replace]", result.middleBody);
middleCpp = ReplaceAll(middleCpp, "[init_replace]", result.middleInit);
middleCpp = ReplaceAll(middleCpp, "[implName]", ns0.name);
WriteFile(re.pathJoin(destDir, "%s_middle.cpp".format(ns0.name)), middleCpp)
writeFile(re.pathJoin(destDir, "%s_middle.cpp".format(ns0.name)), middleCpp)
let implH = ReplaceAll(implH_templete, "[impl_name_upper]", ns0.name.toUpperCase())
let implH = ReplaceAll(implHTemplete, "[impl_name_upper]", ns0.name.toUpperCase())
implH = implH.ReplaceAll("[numberUsing]", numberUsing);
implH = ReplaceAll(implH, "[implH_detail]", result.implH)
WriteFile(re.pathJoin(destDir, "%s.h".format(ns0.name)), implH)
writeFile(re.pathJoin(destDir, "%s.h".format(ns0.name)), implH)
let implCpp = implCpp_templete.ReplaceAll("[implName]", ns0.name)
let implCpp = implCppTemplete.ReplaceAll("[implName]", ns0.name)
implCpp = implCpp.ReplaceAll("[implCpp_detail]", result.implCpp)
WriteFile(re.pathJoin(destDir, "%s.cpp".format(ns0.name)), implCpp)
writeFile(re.pathJoin(destDir, "%s.cpp".format(ns0.name)), implCpp)
GenerateGYP(destDir, ns0.name)//生成ubuntu下测试的编译脚本
GenerateGN(destDir, ns0.name)//生成BUILD.gn for ohos
GenerateBase(destDir)//x_napi_tool.h/cpp
generateGYP(destDir, ns0.name)//生成ubuntu下测试的编译脚本
generateGN(destDir, ns0.name)//生成BUILD.gn for ohos
generateBase(destDir)//x_napi_tool.h/cpp
// print(middleCpp)
}
module.exports = {
GenerateAll
generateAll
}

View File

@ -13,8 +13,8 @@
* limitations under the License.
*/
const { ReplaceAll, print } = require("../tools/tool");
const { ParamGenerate } = require("./param_generate");
const { ReturnGenerate } = require("./return_generate");
const { paramGenerate } = require("./param_generate");
const { returnGenerate } = require("./return_generate");
/**
* 结果异步返回Async|Promise
@ -69,7 +69,7 @@ struct [funcName]_value_struct {[valueIn]
return result;
}`
function GenerateFunctionAsync(func, className) {
function generateFunctionAsync(func, className) {
// this.len_to = 0
// // print(type, name, values, ret_type)
let middleFunc = ReplaceAll(funcAsyncTemplete, "[funcName]", func.name)
@ -97,11 +97,10 @@ function GenerateFunctionAsync(func, className) {
for (let i in func.value) {
let v = func.value[i]
ParamGenerate(i, v.name, v.type, param)
paramGenerate(i, v.name, v.type, param)
}
// ReturnGenerate(func.ret, param)
ReturnGenerate(param.callback.type, param)
returnGenerate(param.callback.type, param)
middleFunc = ReplaceAll(middleFunc, "[valueIn]", param.valueIn)// # 输入参数定义
middleFunc = ReplaceAll(middleFunc, "[valueOut]", param.valueOut)// # 输出参数定义
@ -129,5 +128,5 @@ bool %s%s(%s) {
}
module.exports = {
GenerateFunctionAsync
generateFunctionAsync
}

View File

@ -13,8 +13,8 @@
* limitations under the License.
*/
const { ReplaceAll, print } = require("../tools/tool");
const { ParamGenerate } = require("./param_generate");
const { ReturnGenerate } = require("./return_generate");
const { paramGenerate } = require("./param_generate");
const { returnGenerate } = require("./return_generate");
/**
* 结果直接返回
@ -51,20 +51,18 @@ struct [funcName]_value_struct {[valueIn]
return result;
}`
function GenerateFunctionDirect(func, className) {
function generateFunctionDirect(func, className) {
// this.len_to = 0
// // print(type, name, values, ret_type)
let middleFunc = ReplaceAll(funcDirectTemplete, "[funcName]", func.name)
if(className == null)
{
middleFunc = middleFunc.ReplaceAll("[static_define]","")
middleFunc = middleFunc.ReplaceAll("[unwarp_instance]","")
if (className == null) {
middleFunc = middleFunc.ReplaceAll("[static_define]", "")
middleFunc = middleFunc.ReplaceAll("[unwarp_instance]", "")
}
else
{
middleFunc = middleFunc.ReplaceAll("[static_define]","static ")
else {
middleFunc = middleFunc.ReplaceAll("[static_define]", "static ")
middleFunc = middleFunc.ReplaceAll("[unwarp_instance]",
"%s *pInstance = (%s *)pxt->UnWarpInstance();".format(className,className))
"%s *pInstance = (%s *)pxt->UnWarpInstance();".format(className, className))
}
let param = {
valueIn: "",//定义输入
@ -78,17 +76,17 @@ function GenerateFunctionDirect(func, className) {
for (let i in func.value) {
let v = func.value[i]
ParamGenerate(i, v.name, v.type, param)
paramGenerate(i, v.name, v.type, param)
}
ReturnGenerate(func.ret, param)
returnGenerate(func.ret, param)
middleFunc = ReplaceAll(middleFunc, "[valueIn]", param.valueIn)// # 输入参数定义
middleFunc = ReplaceAll(middleFunc, "[valueOut]", param.valueOut)// # 输出参数定义
middleFunc = ReplaceAll(middleFunc, "[valueCheckout]", param.valueCheckout)// # 输入参数解析
let callFunc = "%s%s(%s);".format(className == null?"":"pInstance->",func.name, param.valueFill)
let callFunc = "%s%s(%s);".format(className == null ? "" : "pInstance->", func.name, param.valueFill)
middleFunc = ReplaceAll(middleFunc, "[callFunc]", callFunc)//执行
middleFunc = ReplaceAll(middleFunc, "[valuePackage]", param.valuePackage)//输出参数打包
@ -98,11 +96,11 @@ function GenerateFunctionDirect(func, className) {
bool %s%s(%s) {
return true;
}
`.format(className == null?"":className+"::",func.name, param.valueDefine)
`.format(className == null ? "" : className + "::", func.name, param.valueDefine)
return [middleFunc, implH, implCpp]
}
module.exports = {
GenerateFunctionDirect
generateFunctionDirect
}

View File

@ -13,8 +13,8 @@
* limitations under the License.
*/
const { ReplaceAll, print } = require("../tools/tool");
const { ParamGenerate } = require("./param_generate");
const { ReturnGenerate } = require("./return_generate");
const { paramGenerate } = require("./param_generate");
const { returnGenerate } = require("./return_generate");
/**
* 结果通过同步回调(CallBack)返回
@ -57,20 +57,18 @@ struct [funcName]_value_struct {[valueIn]
return result;
}`
function GenerateFunctionSync(func, className) {
function generateFunctionSync(func, className) {
// this.len_to = 0
// // print(type, name, values, ret_type)
let middleFunc = ReplaceAll(funcSyncTemplete, "[funcName]", func.name)
if(className == null)
{
middleFunc = middleFunc.ReplaceAll("[static_define]","")
middleFunc = middleFunc.ReplaceAll("[unwarp_instance]","")
if (className == null) {
middleFunc = middleFunc.ReplaceAll("[static_define]", "")
middleFunc = middleFunc.ReplaceAll("[unwarp_instance]", "")
}
else
{
middleFunc = middleFunc.ReplaceAll("[static_define]","static ")
else {
middleFunc = middleFunc.ReplaceAll("[static_define]", "static ")
middleFunc = middleFunc.ReplaceAll("[unwarp_instance]",
"%s *pInstance = (%s *)pxt->UnWarpInstance();".format(className,className))
"%s *pInstance = (%s *)pxt->UnWarpInstance();".format(className, className))
}
let param = {
valueIn: "",//定义输入
@ -84,18 +82,17 @@ function GenerateFunctionSync(func, className) {
for (let i in func.value) {
let v = func.value[i]
ParamGenerate(i, v.name, v.type, param)
paramGenerate(i, v.name, v.type, param)
}
// ReturnGenerate(func.ret, param)
ReturnGenerate(param.callback.type, param)
returnGenerate(param.callback.type, param)
middleFunc = ReplaceAll(middleFunc, "[valueIn]", param.valueIn)// # 输入参数定义
middleFunc = ReplaceAll(middleFunc, "[valueOut]", param.valueOut)// # 输出参数定义
middleFunc = ReplaceAll(middleFunc, "[valueCheckout]", param.valueCheckout)// # 输入参数解析
let callFunc = "%s%s(%s);".format(className == null?"":"pInstance->",func.name, param.valueFill)
let callFunc = "%s%s(%s);".format(className == null ? "" : "pInstance->", func.name, param.valueFill)
middleFunc = ReplaceAll(middleFunc, "[callFunc]", callFunc)//执行
middleFunc = ReplaceAll(middleFunc, "[valuePackage]", param.valuePackage)//输出参数打包
@ -107,11 +104,11 @@ function GenerateFunctionSync(func, className) {
bool %s%s(%s) {
return true;
}
`.format(className == null?"":className+"::",func.name, param.valueDefine)
`.format(className == null ? "" : className + "::", func.name, param.valueDefine)
return [middleFunc, implH, implCpp]
}
module.exports = {
GenerateFunctionSync
generateFunctionSync
}

View File

@ -13,12 +13,12 @@
* limitations under the License.
*/
const { print } = require("../tools/tool");
const { GenerateFunctionDirect } = require("./function_direct");
const { GenerateFunctionSync } = require("./function_sync");
const { GenerateFunctionAsync } = require("./function_async");
const { generateFunctionDirect } = require("./function_direct");
const { generateFunctionSync } = require("./function_sync");
const { generateFunctionAsync } = require("./function_async");
const { FuncType, InterfaceList, getArrayType } = require("../tools/common");
const { js_to_c } = require("./param_generate");
const { c_to_js } = require("./return_generate");
const { jsToC } = require("./param_generate");
const { cToJs } = require("./return_generate");
const re = require("../tools/re");
let middleBodyTmplete = `
@ -47,7 +47,7 @@ static void release(void *p)
function GenerateVariable(name, type, variable, className) {
if (type == "string") variable.hDefine += "\n std::string %s;".format(name)
else if (type.substring(0, 12) == "NUMBER_TYPE_") variable.hDefine += "\n %s %s;".format(type, name)
else if (InterfaceList.GetValue(type)) variable.hDefine += "\n %s %s;".format(type, name)
else if (InterfaceList.getValue(type)) variable.hDefine += "\n %s %s;".format(type, name)
else if (type.indexOf("Array<") == 0) {
let type2 = getArrayType(type)
if (type2 == "string") type2 = "std::string"
@ -63,7 +63,7 @@ function GenerateVariable(name, type, variable, className) {
XNapiTool *pxt = std::make_unique<XNapiTool>(env, info).release();
%s *p = (%s *)pxt->UnWarpInstance();
napi_value result;
`.format(name, className, className) + c_to_js("p->" + name, type, "result") + `
`.format(name, className, className) + cToJs("p->" + name, type, "result") + `
delete pxt;
return result;
}
@ -71,13 +71,13 @@ function GenerateVariable(name, type, variable, className) {
{
std::shared_ptr<XNapiTool> pxt = std::make_shared<XNapiTool>(env, info);
%s *p = (%s *)pxt->UnWarpInstance();
`.format(name, className, className) + js_to_c("p->" + name, "pxt->GetArgv(0)", type) + `
`.format(name, className, className) + jsToC("p->" + name, "pxt->GetArgv(0)", type) + `
return nullptr;
}
`
}
function GenerateInterface(name, data, inNamespace) {
function generateInterface(name, data, inNamespace) {
let implH = ""
let implCpp = ""
let middleFunc = ""
@ -95,7 +95,7 @@ function GenerateInterface(name, data, inNamespace) {
middleInit += `
valueList["%s"]["getvalue"]=%s%s_middle::getvalue_%s;
valueList["%s"]["setvalue"]=%s%s_middle::setvalue_%s;`
.format(v.name, inNamespace, name, v.name, v.name, inNamespace, name, v.name)
.format(v.name, inNamespace, name, v.name, v.name, inNamespace, name, v.name)
}
implH += variable.hDefine
middleFunc += variable.middleValue
@ -108,14 +108,14 @@ function GenerateInterface(name, data, inNamespace) {
let tmp;
switch (func.type) {
case FuncType.DIRECT:
tmp = GenerateFunctionDirect(func, name)
tmp = generateFunctionDirect(func, name)
break;
case FuncType.SYNC:
tmp = GenerateFunctionSync(func, name)
tmp = generateFunctionSync(func, name)
break
case FuncType.ASYNC:
case FuncType.PROMISE:
tmp = GenerateFunctionAsync(func, name)
tmp = generateFunctionAsync(func, name)
break
default:
//to do yichangchuli
@ -158,5 +158,5 @@ public:%s
}
module.exports = {
GenerateInterface
generateInterface
}

View File

@ -13,13 +13,13 @@
* limitations under the License.
*/
const { print } = require("../tools/tool");
const { GenerateFunctionDirect } = require("./function_direct");
const { GenerateFunctionSync } = require("./function_sync");
const { GenerateFunctionAsync } = require("./function_async");
const { GenerateInterface } = require("./interface");
const { generateFunctionDirect } = require("./function_direct");
const { generateFunctionSync } = require("./function_sync");
const { generateFunctionAsync } = require("./function_async");
const { generateInterface } = require("./interface");
const { FuncType, InterfaceList } = require("../tools/common");
function GenerateNamespace(name, data, inNamespace = "") {
function generateNamespace(name, data, inNamespace = "") {
// print(name)
// print(data)
// print(inNamespace)
@ -42,12 +42,12 @@ function GenerateNamespace(name, data, inNamespace = "") {
.format(name, nsl.length == 1 ? "exports" : parentNs, name)
}
InterfaceList.Push(data.interface)
// InterfaceList.GetValue("TestClass1")
InterfaceList.push(data.interface)
// InterfaceList.getValue("TestClass1")
for (let i in data.interface) {
let ii = data.interface[i]
// print(ii)
let result = GenerateInterface(ii.name, ii.body, inNamespace + name + "::")
let result = generateInterface(ii.name, ii.body, inNamespace + name + "::")
middleFunc += result.middleBody
implH += result.implH
@ -61,14 +61,14 @@ function GenerateNamespace(name, data, inNamespace = "") {
let tmp;
switch (func.type) {
case FuncType.DIRECT:
tmp = GenerateFunctionDirect(func)
tmp = generateFunctionDirect(func)
break;
case FuncType.SYNC:
tmp = GenerateFunctionSync(func)
tmp = generateFunctionSync(func)
break
case FuncType.ASYNC:
case FuncType.PROMISE:
tmp = GenerateFunctionAsync(func)
tmp = generateFunctionAsync(func)
break
default:
// to do yichangchuli
@ -78,19 +78,19 @@ function GenerateNamespace(name, data, inNamespace = "") {
implH += tmp[1]
implCpp += tmp[2]
middleInit += ' pxt->DefineFunction("%s", %s%s::%s_middle%s);\n'
.format(func.name, inNamespace, name, func.name, inNamespace.length > 0 ? ", "+name : "")
.format(func.name, inNamespace, name, func.name, inNamespace.length > 0 ? ", " + name : "")
}
for (let i in data.namespace) {
let ns = data.namespace[i]
// print(ns)
let result = GenerateNamespace(ns.name, ns.body, inNamespace + name + "::")
let result = generateNamespace(ns.name, ns.body, inNamespace + name + "::")
middleFunc += result.middleBody
implH += result.implH
implCpp += result.implCpp
middleInit += result.middleInit
}
InterfaceList.Pop();
InterfaceList.pop();
if (inNamespace.length > 0) {
middleInit += "}"
@ -116,5 +116,5 @@ namespace %s {
}
module.exports = {
GenerateNamespace
generateNamespace
}

View File

@ -21,7 +21,7 @@ LenIncrease.LEN_TO = 1;
LenIncrease.Reset = function () {
LenIncrease.LEN_TO = 1;
}
LenIncrease.GetAndIncrease = function () {
LenIncrease.getAndIncrease = function () {
return LenIncrease.LEN_TO++;
}
@ -29,10 +29,10 @@ function getValueProperty(napiVn, name) {
return 'pxt->GetValueProperty(%s, "%s")'.format(napiVn, name)
}
function js_to_c(dest, napiVn, type) {
function jsToC(dest, napiVn, type) {
if (type == "string") {
if (napiVn.indexOf("GetValueProperty") >= 0) {
let lt = LenIncrease.GetAndIncrease()
let lt = LenIncrease.getAndIncrease()
return `napi_value tnv%d = %s;\n if(tnv%d!=nullptr){pxt->SwapJs2CUtf8(tnv%d,%s);}`
.format(lt, napiVn, lt, lt, dest)
}
@ -41,26 +41,26 @@ function js_to_c(dest, napiVn, type) {
}
else if (type.substring(0, 12) == "NUMBER_TYPE_") {
if (napiVn.indexOf("GetValueProperty") >= 0) {
let lt = LenIncrease.GetAndIncrease()
let lt = LenIncrease.getAndIncrease()
return `napi_value tnv%d = %s;\n if(tnv%d!=nullptr){NUMBER_JS_2_C(tnv%d,%s,%s);}`
.format(lt, napiVn, lt, lt, type, dest)
}
else
return `NUMBER_JS_2_C(%s,%s,%s);`.format(napiVn, type, dest)
}
else if (InterfaceList.GetValue(type)) {
else if (InterfaceList.getValue(type)) {
let tt = ""
let ifl = InterfaceList.GetValue(type)
let ifl = InterfaceList.getValue(type)
for (let i in ifl) {
let name2 = ifl[i].name
let type2 = ifl[i].type
tt += js_to_c("%s.%s".format(dest, name2), getValueProperty(napiVn, name2), type2)
tt += jsToC("%s.%s".format(dest, name2), getValueProperty(napiVn, name2), type2)
}
return tt
}
else if (type.indexOf("Array<") == 0) {
let arrayType = getArrayType(type)
let lt = LenIncrease.GetAndIncrease()
let lt = LenIncrease.getAndIncrease()
if (arrayType == "string") arrayType = "std::string"
let arrTemplete = `\
uint32_t len[replace_lt]=pxt->GetArrayLength(%s);
@ -79,14 +79,14 @@ function js_to_c(dest, napiVn, type) {
arrTemplete = arrTemplete.ReplaceAll("[replace_swap]",
"pxt->SwapJs2CUtf8(pxt->GetArrayElement(%s,i%d), tt%d);".format(napiVn, lt, lt))
}
else if (InterfaceList.GetValue(arrayType)) {
else if (InterfaceList.getValue(arrayType)) {
arrTemplete = arrTemplete.ReplaceAll("[replace_swap]",
js_to_c("tt" + lt, "pxt->GetArrayElement(%s,i%d)".format(napiVn, lt), arrayType))
jsToC("tt" + lt, "pxt->GetArrayElement(%s,i%d)".format(napiVn, lt), arrayType))
}
return arrTemplete;
}
else
print(`\n---- generate js_to_c fail %s,%s,%s ----\n`.format(dest, napiVn, type))
print(`\n---- generate jsToC fail %s,%s,%s ----\n`.format(dest, napiVn, type))
}
function ParamCheckout(name, napiVn, type) {
@ -96,33 +96,33 @@ function ParamCheckout(name, napiVn, type) {
let name2 = Object.keys(e)[0]
let type2 = e[name2]
this.values_["value_analyze"] += "%s%s".format(new_line(this.values_["value_analyze"]),
this.js_to_c("%s.%s".format(name, name2),
this.jsToC("%s.%s".format(name, name2),
this.getValueProperty(napiVn, name2),
type2))
}
}
else if (type.substring(0, 12) == "NUMBER_TYPE_" || type == "string" || type.substring(0, 6) == "Array<")
this.values_["value_analyze"] += "%s%s".format(new_line(this.values_["value_analyze"]),
this.js_to_c(name, napiVn, type))
this.jsToC(name, napiVn, type))
}
// 函数的参数处理
function ParamGenerate(p, name, type, param) {
function paramGenerate(p, name, type, param) {
if (type == "string") {
param.valueIn += "\n std::string in%d;".format(p)
param.valueCheckout += js_to_c("vio->in" + p, "pxt->GetArgv(%d)".format(p), type)
param.valueCheckout += jsToC("vio->in" + p, "pxt->GetArgv(%d)".format(p), type)
param.valueFill += "%svio->in%d".format(param.valueFill.length > 0 ? ", " : "", p)
param.valueDefine += "%sstd::string &%s".format(param.valueDefine.length > 0 ? ", " : "", name)
}
else if (type.substring(0, 12) == "NUMBER_TYPE_") {
param.valueIn += "\n %s in%d;".format(type, p)
param.valueCheckout += js_to_c("vio->in" + p, "pxt->GetArgv(%d)".format(p), type)
param.valueCheckout += jsToC("vio->in" + p, "pxt->GetArgv(%d)".format(p), type)
param.valueFill += "%svio->in%d".format(param.valueFill.length > 0 ? ", " : "", p)
param.valueDefine += "%s%s &%s".format(param.valueDefine.length > 0 ? ", " : "", type, name)
}
else if (InterfaceList.GetValue(type)) {
else if (InterfaceList.getValue(type)) {
param.valueIn += "\n %s in%d;".format(type, p)
param.valueCheckout += js_to_c("vio->in" + p, "pxt->GetArgv(%d)".format(p), type)
param.valueCheckout += jsToC("vio->in" + p, "pxt->GetArgv(%d)".format(p), type)
param.valueFill += "%svio->in%d".format(param.valueFill.length > 0 ? ", " : "", p)
param.valueDefine += "%s%s &%s".format(param.valueDefine.length > 0 ? ", " : "", type, name)
}
@ -130,7 +130,7 @@ function ParamGenerate(p, name, type, param) {
let arrayType = getArrayType(type)
if (arrayType == "string") arrayType = "std::string"
param.valueIn += "\n std::vector<%s> in%d;".format(arrayType, p)
param.valueCheckout += js_to_c("vio->in" + p, "pxt->GetArgv(%d)".format(p), type)
param.valueCheckout += jsToC("vio->in" + p, "pxt->GetArgv(%d)".format(p), type)
param.valueFill += "%svio->in%d".format(param.valueFill.length > 0 ? ", " : "", p)
param.valueDefine += "%sstd::vector<%s> &%s".format(param.valueDefine.length > 0 ? ", " : "", arrayType, name)
}
@ -146,6 +146,6 @@ function ParamGenerate(p, name, type, param) {
}
module.exports = {
js_to_c,
ParamGenerate
jsToC,
paramGenerate
}

View File

@ -15,7 +15,7 @@
const { ReplaceAll, print } = require("../tools/tool");
const { InterfaceList, getArrayType } = require("../tools/common");
function c_to_js(value, type, dest, deep = 1) {
function cToJs(value, type, dest, deep = 1) {
// print(value, type, dest)
if (type == "void")
return "%s = pxt->UndefinedValue();".format(dest);
@ -25,14 +25,14 @@ function c_to_js(value, type, dest, deep = 1) {
return `%s = pxt->SwapC2JsUtf8(%s.c_str());`.format(dest, value)
else if (type.substring(0, 12) == "NUMBER_TYPE_")
return `%s = NUMBER_C_2_JS(pxt, %s);`.format(dest, value)
else if (InterfaceList.GetValue(type)) {
else if (InterfaceList.getValue(type)) {
let lt = deep
let tt = ""
let ifl = InterfaceList.GetValue(type)
let ifl = InterfaceList.getValue(type)
for (let i in ifl) {
let name2 = ifl[i].name
let type2 = ifl[i].type
let tt1 = c_to_js("%s.%s".format(value, name2), type2, "tnv%d".format(lt), deep + 1)
let tt1 = cToJs("%s.%s".format(value, name2), type2, "tnv%d".format(lt), deep + 1)
tt += "{\nnapi_value tnv%d = nullptr;\n".format(lt) + tt1 + `\npxt->SetValueProperty(%s,"%s",tnv%d);\n}`
.format(dest, name2, lt)
}
@ -55,18 +55,18 @@ function c_to_js(value, type, dest, deep = 1) {
else if (arrayType == "string") {
ret = tnvdef.ReplaceAll("[calc_out]", `tnv%d = pxt->SwapC2JsUtf8(%s[i].c_str());`.format(lt, value))
}
else if (InterfaceList.GetValue(arrayType)) {
ret = tnvdef.ReplaceAll("[calc_out]", c_to_js(value + "[i]", arrayType, "tnv" + lt, deep + 1))
else if (InterfaceList.getValue(arrayType)) {
ret = tnvdef.ReplaceAll("[calc_out]", cToJs(value + "[i]", arrayType, "tnv" + lt, deep + 1))
}
return ret
}
else
print(`\n---- generate c_to_js fail %s,%s,%s ----\n`.format(value, type, dest))
print(`\n---- generate cToJs fail %s,%s,%s ----\n`.format(value, type, dest))
}
function ReturnGenerate(type, param) {
function returnGenerate(type, param) {
param.valueFill += "%svio->out".format(param.valueFill.length > 0 ? ", " : "")
param.valuePackage = "napi_value result = nullptr;\n " + c_to_js("vio->out", type, "result")
param.valuePackage = "napi_value result = nullptr;\n " + cToJs("vio->out", type, "result")
if (type == "string") {
param.valueOut = "std::string out;"
param.valueDefine += "%sstd::string &out".format(param.valueDefine.length > 0 ? ", " : "")
@ -77,12 +77,12 @@ function ReturnGenerate(type, param) {
else if (type == "boolean") {
param.valueOut = "bool out;"
param.valueDefine += "%sbool &out".format(param.valueDefine.length > 0 ? ", " : "")
}
}
else if (type.substring(0, 12) == "NUMBER_TYPE_") {
param.valueOut = type + " out;"
param.valueDefine += "%s%s &out".format(param.valueDefine.length > 0 ? ", " : "", type)
}
else if (InterfaceList.GetValue(type)) {
else if (InterfaceList.getValue(type)) {
param.valueOut = type + " out;"
param.valueDefine += "%s%s &out".format(param.valueDefine.length > 0 ? ", " : "", type)
}
@ -93,12 +93,12 @@ function ReturnGenerate(type, param) {
param.valueDefine += "%sstd::vector<%s> &out".format(param.valueDefine.length > 0 ? ", " : "", arrayType)
}
else {
print(`\n---- ReturnGenerate fail %s ----\n`.format(type))
print(`\n---- returnGenerate fail %s ----\n`.format(type))
}
param.valueFill += "%svio->out".format(param.valueFill.length > 0 ? ", " : "")
param.valueFill += "%svio->out".format(param.valueFill.length > 0 ? ", " : "")
}
module.exports = {
c_to_js,
ReturnGenerate
cToJs,
returnGenerate
}

View File

@ -13,21 +13,21 @@
* limitations under the License.
*/
// const vscode = require('vscode');
const { AnalyzeFile } = require("./analyze");
const { GenerateAll } = require("./generate");
const { analyzeFile } = require("./analyze");
const { generateAll } = require("./generate");
const re = require("./tools/re")
function DoGenerate(ifname) {
function doGenerate(ifname) {
// console.log("----------generate start---------")
let structOfTs = AnalyzeFile(ifname);
let structOfTs = analyzeFile(ifname);
// print(structOfTs)
GenerateAll(structOfTs, re.getPathInPath(ifname));
generateAll(structOfTs, re.getPathInPath(ifname));
// console.log("----------generate end---------")
}
module.exports = {
DoGenerate
doGenerate
}

View File

@ -17,35 +17,4 @@ const path = require("path");
const main = require("./main");
const { print } = require("./tools/tool");
main.DoGenerate("nodejs_test/gen/@ohos.napitest.d.ts");
// if (1 == 1) {
// main.DoGenerate("nodejs_test/gen/@ohos.napitest.d.ts");
// }
// else {
// let test_ts_dir = "test_ts/ohos"
// if (1 == 0) {
// main.DoGenerate(path.join(test_ts_dir, "@ohos.fileio.d.ts"));
// }
// else {
// let files = fs.readdirSync(test_ts_dir)
// for (let i in files) {
// let fn = files[i]
// let gf = path.join(test_ts_dir, fn)
// print("--------------", i, "-----------------")
// print(gf)
// main.DoGenerate(gf);
// // if (i > 20) break
// }
// }
// }
/**
* run test:
* node vscode_plugin/gnapi/gen/test.js
*/
// main.DoGenerate("Z:\\napi_test\\@ohos.napitest.d.ts");
// main.DoGenerate("Z:\\l1\\foundation\\communication\\cx_test\\napi_test\\@ohos.xtestx.d.ts");
main.doGenerate("nodejs_test/gen/@ohos.napitest.d.ts");

View File

@ -14,120 +14,117 @@
*/
const fs = require('fs');
function Utf8ArrayToStr(array) {
var out, i, len, c;
var char2, char3;
function utf8ArrayToStr(array) {
var out, i, len, c;
var char2, char3;
out = "";
len = array.length;
i = 0;
while(i < len) {
out = "";
len = array.length;
i = 0;
while (i < len) {
c = array[i++];
switch(c >> 4)
{
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;
// 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;
// 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;
// 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;
}
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;
const out = [];
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++);
if (value >= 0xd800 && value <= 0xdbff) {
// high surrogate
if (pos < len) {
const extra = string.charCodeAt(pos);
if ((extra & 0xfc00) === 0xdc00) {
++pos;
value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
}
}
if (value >= 0xd800 && value <= 0xdbff) {
continue; // drop lone surrogate
}
}
// 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
const update = new Uint8Array(tlen);
update.set(target);
target = update;
}
if ((value & 0xffffff80) === 0) { // 1-byte
target[at++] = value; // ASCII
continue;
} 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 {
// FIXME: do we care
continue;
}
target[at++] = (value & 0x3f) | 0x80;
}
return target.slice(0, at);
}
function ReadFile(fn)
{
if (!fs.existsSync(fn))
{
return "";
}
let data=fs.readFileSync(fn);
data=Utf8ArrayToStr(data);
return data;
return out;
}
function WriteFile(fn,str)
{
let data=stringToUint8Array(str);
fs.writeFileSync(fn, data);
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;
const out = [];
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++);
if (value >= 0xd800 && value <= 0xdbff) {
// high surrogate
if (pos < len) {
const extra = string.charCodeAt(pos);
if ((extra & 0xfc00) === 0xdc00) {
++pos;
value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
}
}
if (value >= 0xd800 && value <= 0xdbff) {
continue; // drop lone surrogate
}
}
// 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
const update = new Uint8Array(tlen);
update.set(target);
target = update;
}
if ((value & 0xffffff80) === 0) { // 1-byte
target[at++] = value; // ASCII
continue;
} 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 {
// FIXME: do we care
continue;
}
target[at++] = (value & 0x3f) | 0x80;
}
return target.slice(0, at);
}
function readFile(fn) {
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);
}
module.exports = {
ReadFile,
WriteFile
readFile,
writeFile
}

View File

@ -29,25 +29,25 @@ FuncType.ToString = function (type) {
class NumberIncrease { }
NumberIncrease.num = 1
NumberIncrease.GetAndIncrease = function () {
NumberIncrease.getAndIncrease = function () {
return NumberIncrease.num++;
}
NumberIncrease.Get = function () {
NumberIncrease.get = function () {
return NumberIncrease.num;
}
NumberIncrease.Reset = function () {
NumberIncrease.reset = function () {
NumberIncrease.num = 1
}
class InterfaceList { }
InterfaceList.interfacess_ = [];
InterfaceList.Push = function (ifs) {
InterfaceList.push = function (ifs) {
InterfaceList.interfacess_.push(ifs)
}
InterfaceList.Pop = function () {
InterfaceList.pop = function () {
InterfaceList.interfacess_.pop()
}
InterfaceList.GetValue = function (name) {
InterfaceList.getValue = function (name) {
let ifs = InterfaceList.interfacess_[InterfaceList.interfacess_.length - 1]
for (let i in ifs) {
if (ifs[i].name == name) {

View File

@ -13,7 +13,7 @@
* limitations under the License.
*/
const re = require("./re");
let vscode=null;
let vscode = null;
try {
vscode = require('vscode');
}
@ -22,8 +22,7 @@ catch (err) {
}
function print(...args) {
if(vscode)
{
if (vscode) {
vscode.window.showInformationMessage(...args);
}
console.log(...args)
@ -51,7 +50,7 @@ String.prototype.ReplaceAll = function (...args) {
return result;
}
function CheckOutBody(body, off, flag, binside) {
function checkOutBody(body, off, flag, binside) {
off = off || 0;
flag = flag || ["{", "}"];
binside = binside || false;
@ -110,7 +109,7 @@ function CheckOutBody(body, off, flag, binside) {
}
function RemoveExplains(data) {
function removeExplains(data) {
while (data.indexOf("/*") >= 0) {
let i1 = data.indexOf("/*")
let i2 = data.indexOf("*/") + 2
@ -130,7 +129,7 @@ function RemoveExplains(data) {
return data
}
function RemoveEmptyLine(data) {
function removeEmptyLine(data) {
while (data.indexOf("\r") >= 0) {
data = data.replace("\r", "")
}
@ -152,7 +151,7 @@ function RemoveEmptyLine(data) {
return data
}
function RemoveEmptyLine2(data) {
function removeEmptyLine2(data) {
while (data.indexOf(" \n"))
data = data.replace(" \n", "\n")
while (data.indexOf("\n\n\n"))
@ -168,10 +167,10 @@ function ReplaceAll(s, sfrom, sto) {
}
module.exports = {
CheckOutBody,
RemoveExplains,
RemoveEmptyLine,
RemoveEmptyLine2,
checkOutBody,
removeExplains,
removeEmptyLine,
removeEmptyLine2,
ReplaceAll,
print
}