1 Star 0 Fork 0

jared-zheng / ScriptX

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
BSL-1.0

ScriptX

全能的脚本引擎抽象层


README-English License UnitTests GitHub code size in bytes Lines of code GitHub top language Coverage Status

ScriptX架构

ScriptX是一个脚本引擎抽象层。对下封装多种脚本引擎,对上暴露统一的API,使得上层调用者可以完全隔离底层的引擎实现(后端)。

ScriptX不仅隔离了几种JavaScript引擎,甚至可以隔离不同脚本语言,使得上层仅需修改一个编译选项即可无缝切换脚本引擎和脚本语言

ScriptX的术语中,"前端"指对外的C++ API,"后端"则指不同的底层引擎,目前已经实现的后端有:V8, node.js, JavaScriptCore, WebAssembly, Lua.

状态

后端 语言 版本 状态
V8 JavaScript 7.4+ done
JavaScriptCore JavaScript 7604.1.38.0.7+
(iOS 10+/macOS10.12+)
done
Node.js JavaScript 14.x+ done
QuickJs JavaScript 2024-01-13 done
WebAssembly JavaScript Emscripten-2.0.5+ done
Lua Lua 5.4+ done
CPython Python todo
YARV Ruby todo
Mono C# todo

简介

ScriptX 的接口使用现代C++特性。并且做到100%符合C++标准,完全跨平台。

所有API以ScriptX.h聚合头文件暴露出来。

设计目标: 多语言 | 多引擎实现 | 高性能 | API易用 | 跨平台

第一印象

我们通过一段比较完整的代码来对ScriptX留下一个整体印象。

EngineScope enter(engine);
try {
  engine->eval("function fibo(x) { if (x<=2 ) return 1; else return fibo(x-1) + fibo(x-2) }");
  Local<Function> fibo = engine->get("fibo").asFunction();
  Local<Value> ret = fibo.call({}, 10);
  ret.asNumber().toInt32() == 55;

  auto log = Function::newFunction(
      [](const std::string& msg) {
        std::cerr << "[log]: " << msg << std::endl;
      });
  // or use: Function::newFunction(std::puts);
  engine->set("log", log);
  engine->eval("log('hello world');");

  auto json = engine->eval(R"( JSON.parse('{"length":1,"info":{"version": "1.18","time":132}}'); )")
                  .asObject();
  json.get("length").asNumber().toInt32() == 1;

  auto info = json.get("info").asObject();
  info.get("version").asString().toString() ==  "1.18";
  info.get("time").asNumber().toInt32() == 132;

  Local<Object> bind = engine->eval("...").asObject();
  MyBind* ptr = engine->getNativeInstance<MyBind>(bind);
  ptr->callCppFunction();

} catch (Exception& e) {
  FAIL() << e.message() << e.stacktrace();
  // or FAIL() << e;
}
  1. 使用 EngineScope 进入引擎环境
  2. 绝大多是API可以接受C++原生类型作为参数,内部自动转换类型
  3. 可以从C/C++函数直接创建脚本函数(native 绑定)
  4. 支持脚本的异常处理
  5. API强类型

特性介绍

1. 支持多种引擎,多脚本语言

ScriptX设计之初就目标为支持多种脚本语言,并在JavaScript上实现了V8和JavaScriptCore的引擎封装。 后续为了验证ScriptX的多语言设计,实现了完整的Lua绑定。 目前针对WebAssembly的支持也已经完成。

2. 现代的 C++ API

API设计上符合现代 C++ 风格,如:

  1. 三种引用类型 Local/Global/Weak,使用copy, move语义实现自动的内存管理(自动引用计数)
  2. 使用 variadic template 支持非常方便的 Function::call 语法
  3. 使用 Template Meta-Programing 实现直接绑定C++函数

现代语言特性,引用空指针安全(nullibility safety 请参考kotlin的概念)。

注:ScriptX要求C++17(或1z)以上的编译器支持,并需要打开异常特性,(可以关闭RTTI特性)。

3. 高性能

高性能是ScriptX设计上的重要指标。在实现过程中也充分体现了 Zero-Overhead 的C++思想。并在增加功能特性的时候通过相关的性能测试。

性能测试对比数据 测试指标:单次JS到C++函数调用耗时,微秒

测试环境:iMac i9-9900k 32G RAM @macOS 10.15

性能测试表示,在Release模式下,ScriptX可以达到几乎和原生绑定相同的性能。(由于ScriptX使用大量模板,请勿在Debug版进行性能测试)

4. 方便的异常处理

ScriptX通过一系列的技术手段实现了脚本的异常和C++异常相互打通的能力。在调用引擎API时无需判断返回值,可以使用异常统一处理,避免crash。

比如使用者可以在C++层catch住js代码抛的异常,并获取message和堆栈;也可以在native函数里抛一个C++异常(script::Exception) 并透传到js代码中去。

详见 ExceptionTest相关文档

5. 易用的API

易用的API => 开心的工程师 => 高效 => 高质量

ScriptX 设计的时候充分考虑到API的易用性,包括操作友好简单,不易出错,错误信息明显,便于定位问题等。在这样的指导思想之下ScriptX做了很多原生引擎做不了的事情。

比如:V8在destroy的时候是不执行GC的,导致很多绑定的native类不能释放。ScriptX做了额外的逻辑处理这个情况。

V8和JSCore要求在finalize回调中不能调用ScriptX的其他API,否则会crash,这也导致代码逻辑很难实现。ScriptX借助MessageQueue完美规避这个问题。

V8和JSCore的全局引用都必须在engine destroy之前全部释放掉,否则就会引起crash、不能destroy等问题。ScriptX则保证在Engine destroy的时候主动reset所有 Global / Weak 引用。

6. 简单高效的绑定API

当app作为宿主使用脚本引擎时,通常都是需要注入大量native 绑定的 函数/类 来为脚本逻辑提供能力。ScriptX 设计的ClassDeifine相关绑定API简单易用,并且可以支持直接绑定C++函数,极大的提升工作效率。

7. 可以与原生引擎API互操作

ScriptX再提供引擎封装的同时,也提供了一套工具方法实现原生类型和ScriptX类型的相互转换。

详见 InteroperateTest相关文档

代码质量

代码质量高标准要求

  1. 上百个测试用例,单测覆盖率达 90+%
  2. 圈复杂度仅有 1.18
  3. 借助clang-format保证代码格式统一。
  4. 使用clang-tidy发现潜在问题。
  5. 在clang和MSVC编译器上都打开了"warning as error"级别的错误信息。

代码目录结构

root
├── README.md
├── src
│   ├── Engine.h
│   └── ...
├── backend
│   ├── JavaScriptCore
│   ├── Lua
│   ├── Python
│   ├── QuickJs
│   ├── Ruby
│   ├── SpiderMonkey
│   ├── Template
│   ├── V8
│   ├── WKWebView
│   └── WebAssembly
├── docs
│   ├── Basics.md
│   └── ...
└── test
    ├── CMakeLists.txt
    └── src
        ├── Demo.cc
        └── ...
  1. src: 对外API,主要是头文件
  2. backend: 各种引擎后端的实现
  3. docs: 丰富的文档
  4. test: 各种单元测试

上手文档

ScriptX 中的一些重要类:

  1. ScriptEngine
  2. EngineScope
  3. Exception
  4. Value, Null, Object, String, Number, Boolean, Function, Array, ByteBuffer, Unsupported
  5. Local<Value>, Local<Null>, Local<Object>, Local<String>, Local<Number>, Local<Boolean>, Local<Function>, Local<Array>, Local<ByteBuffer>, Local<Unsupported>
  6. Global<T>, Weak<T>

在正式使用ScriptX之前,请花半个小时仔细阅读项目文档,并熟悉 ScriptX 中的若干概念。

Tencent is pleased to support the open source community by making ScriptX available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. ScriptX is licensed under the Apache License Version 2.0 except for the third-party components listed below. Terms of the Apache License Version 2.0: -------------------------------------------------------------------- Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Other dependencies and licenses: Open Source Software Licensed under the Boost Software License 1.0: -------------------------------------------------------------------- 1. utfpp Copyright 2006 Nemanja Trifunovic Terms of the Boost Software License 1.0: -------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

简介

暂无描述 展开 收起
C++ 等 6 种语言
BSL-1.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/jared-zheng/ScriptX.git
git@gitee.com:jared-zheng/ScriptX.git
jared-zheng
ScriptX
ScriptX
main

搜索帮助