diff --git a/.github/workflows/auto-test.yml b/.github/workflows/auto-test.yml index c4e9fcf91..0cb41ecab 100644 --- a/.github/workflows/auto-test.yml +++ b/.github/workflows/auto-test.yml @@ -161,6 +161,7 @@ jobs: $argvFixture = Join-Path $build 'Release/vas_rider_argv_fixture.exe' if (-not (Test-Path $argvFixture)) { throw 'Missing Rider native argument fixture' } "VAS_TEST_COMPILER=$compiler" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + "VAS_TEST_CONFIG=$env:GITHUB_WORKSPACE/sdk/samples/asbuild/bin/config.txt" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append "VAS_TEST_ARGV_FIXTURE=$argvFixture" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append - name: set up Java 25 uses: actions/setup-java@v4 diff --git a/App1/.vas/bin/vasbuild.exe b/App1/.vas/bin/vasbuild.exe index e65ecad42..192fbfeb8 100644 Binary files a/App1/.vas/bin/vasbuild.exe and b/App1/.vas/bin/vasbuild.exe differ diff --git a/App1/.vas/bin/vasrun.exe b/App1/.vas/bin/vasrun.exe index 236c619f9..38c3e6097 100644 Binary files a/App1/.vas/bin/vasrun.exe and b/App1/.vas/bin/vasrun.exe differ diff --git a/App1/.vas/vasbuild.config.txt b/App1/.vas/vasbuild.config.txt index bce3a74af..49761ab26 100644 --- a/App1/.vas/vasbuild.config.txt +++ b/App1/.vas/vasbuild.config.txt @@ -82,8 +82,6 @@ objmthd "array" "int findByRef(uint, const T&in) const" objmthd "array" "bool opEquals(const array&in) const" objmthd "array" "bool isEmpty() const" objmthd "array" "void sort(array::less&in, uint = 0, uint = uint ( - 1 ))" -objmthd "array" "uint get_length() const" -objmthd "array" "void set_length(uint)" // Type members objbeh "string" 2 "void string()" @@ -96,8 +94,6 @@ objmthd "string" "int opCmp(const string&in) const" objmthd "string" "string opAdd(const string&in) const" objmthd "string" "uint length() const" objmthd "string" "void resize(uint)" -objmthd "string" "uint get_length() const" -objmthd "string" "void set_length(uint)" objmthd "string" "bool isEmpty() const" objmthd "string" "uint8& opIndex(uint)" objmthd "string" "const uint8& opIndex(uint) const" @@ -214,7 +210,31 @@ func "int64 parseInt(const string&in, uint = 10, uint&out = 0)" func "uint64 parseUInt(const string&in, uint = 10, uint&out = 0)" func "double parseFloat(const string&in, uint&out = 0)" func "string join(const array&in, const string&in)" -func "void print(const string&in)" +formatfunc "void print(const string&in format, const ?&in ...)" +func "void print(int8)" +func "void print(uint8)" +func "void print(int16)" +func "void print(uint16)" +func "void print(int)" +func "void print(uint)" +func "void print(int64)" +func "void print(uint64)" +func "void print(float)" +func "void print(double)" +func "void print(bool)" +formatfunc "void println(const string&in format, const ?&in ...)" +func "void println()" +func "void println(int8)" +func "void println(uint8)" +func "void println(int16)" +func "void println(uint16)" +func "void println(int)" +func "void println(uint)" +func "void println(int64)" +func "void println(uint64)" +func "void println(float)" +func "void println(double)" +func "void println(bool)" func "string getInput()" func "array@ getCommandLineArgs()" func "int exec(const string&in)" diff --git a/CMakeLists.txt b/CMakeLists.txt index 26005c10a..8f14182af 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -185,6 +185,59 @@ if(BUILD_TESTING) NAME vasrun_executes_vas COMMAND $ "${VASBUILD_FIXTURE_DIR}/runnable.vas" ) + add_executable(vas_format_performance_test + tests/vasbuild/test_format_performance.cpp + sdk/add_on/scripthelper/scripthelper.cpp) + target_link_libraries(vas_format_performance_test PRIVATE angelscript) + vas_enable_cxx23(vas_format_performance_test) + if(MSVC) + target_compile_options(vas_format_performance_test PRIVATE "$<$:/EHsc>") + endif() + add_test(NAME vas_format_performance COMMAND vas_format_performance_test) + set_tests_properties(vas_format_performance PROPERTIES TIMEOUT 60) + add_executable(vas_module_performance_test + tests/vasbuild/test_module_performance.cpp + sdk/add_on/scriptbuilder/scriptbuilder.cpp) + target_link_libraries(vas_module_performance_test PRIVATE angelscript) + vas_enable_cxx23(vas_module_performance_test) + if(MSVC) + target_compile_options(vas_module_performance_test PRIVATE "$<$:/EHsc>") + endif() + file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/module-performance") + add_test(NAME vas_module_performance COMMAND vas_module_performance_test module-performance) + set_tests_properties(vas_module_performance PROPERTIES TIMEOUT 60 WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}") + add_test(NAME vas_modules + COMMAND ${CMAKE_COMMAND} + "-DVASBUILD=$" + "-DVASRUN=$" + "-DSOURCE_ROOT=${CMAKE_CURRENT_SOURCE_DIR}" + "-DTEST_ROOT=${CMAKE_CURRENT_BINARY_DIR}/modules" + -P "${CMAKE_CURRENT_SOURCE_DIR}/tests/vasbuild/assert_modules.cmake") + set_tests_properties(vas_modules PROPERTIES TIMEOUT 60) + add_test(NAME vas_arena_example + COMMAND ${CMAKE_COMMAND} + "-DVASBUILD=$" + "-DVASRUN=$" + "-DSOURCE_ROOT=${CMAKE_CURRENT_SOURCE_DIR}" + "-DTEST_ROOT=${CMAKE_CURRENT_BINARY_DIR}/arena-example" + -P "${CMAKE_CURRENT_SOURCE_DIR}/tests/vasbuild/assert_arena.cmake") + set_tests_properties(vas_arena_example PROPERTIES TIMEOUT 60) + add_test(NAME vas_print_primitives + COMMAND ${CMAKE_COMMAND} + "-DVASBUILD=$" + "-DVASRUN=$" + "-DSOURCE_ROOT=${CMAKE_CURRENT_SOURCE_DIR}" + "-DTEST_ROOT=${CMAKE_CURRENT_BINARY_DIR}/print-primitives" + -P "${CMAKE_CURRENT_SOURCE_DIR}/tests/vasbuild/assert_print_primitives.cmake") + set_tests_properties(vas_print_primitives PROPERTIES TIMEOUT 60) + add_test(NAME vas_println + COMMAND ${CMAKE_COMMAND} + "-DVASBUILD=$" + "-DVASRUN=$" + "-DSOURCE_ROOT=${CMAKE_CURRENT_SOURCE_DIR}" + "-DTEST_ROOT=${CMAKE_CURRENT_BINARY_DIR}/println" + -P "${CMAKE_CURRENT_SOURCE_DIR}/tests/vasbuild/assert_println.cmake") + set_tests_properties(vas_println PROPERTIES TIMEOUT 60) add_test( NAME vasrun_rejects_legacy_entry_extension COMMAND ${CMAKE_COMMAND} diff --git a/docs/ide-language-support.md b/docs/ide-language-support.md new file mode 100644 index 000000000..8f43fbe42 --- /dev/null +++ b/docs/ide-language-support.md @@ -0,0 +1,68 @@ +# 模块索引、补全与语义颜色 + +本次交付 Rider 0.5.9、VS Code 0.3.0、VS2026 0.3.0。模块索引保持独立源码模型,另提供即时结构诊断和可配置的后台编译诊断。 + +三端识别 `import Arena.Demo;`、`#include "Arena/Demo.vas"` 和角括号 include;支持跨文件声明导航、简单类型对象的成员与命名空间补全,并显示所有找到的宏定义候选。枚举值同时支持其命名空间导出及枚举类型限定导航。原有 `import int Fn(...) from "module";` 是函数声明,不被当成文件模块加载。 + +Rider 还将声明和宏名称接入 Go to Symbol / Search Everywhere,提供类型/函数/变量声明/宏语义颜色。VS Code 提供定义跳转、悬浮、文档符号与语义 token;VS 的 MEF 提供器接入真实原生补全窗口、F12、异步悬浮和类型/函数/宏颜色。VS 与 VS Code 共用词法语法资产,包括 import 模块名、宏定义和格式串占位符颜色。 + +## 输入、参数提示与错误标记 + +三端支持 `{}`、`()`、`[]`、双引号和单引号配对,右符号跳过、空符号对退格及块内换行缩进。注释、字符串内不会新增括号对。Rider 的数字分隔单引号不会变成空字符串。函数补全插入 `()` 并将光标放到需要参数的位置;已有左括号时不重复插入。输入 `(`、`,` 可显示参数提示;Rider 用 Ctrl+P、VS Code 用 Ctrl+Shift+Space、VS 用 Edit.ParameterInfo 手动调用。 + +未闭合括号、字符串/注释及非法字符通过编辑器诊断标红,不要求配置编译器。包含条件预处理分支时,结构检查不猜测活动分支,括号检查交给编译器。 + +后台编译器读取未保存的当前文件和模块依赖,在临时目录内编译;不保存或改写用户源码。再次编辑后,旧快照结果不会发布。此功能检查当前文件作为入口,并显示属于当前文件的错误;模块需要从依赖它的入口获取完整宿主/宏上下文,不等于完整工程的未保存语义服务。 + +- Rider:已信任项目,设置应用级 Compiler executable(或既有项目 builder),并提供匹配宿主 API 配置。此次修复应用级已配置而项目 builder 为空时后台诊断不启动的问题,依赖收集支持 import/角括号 include。 +- VS Code:已信任工作区,User/Remote 设置 `vas.compilerPath`,`vas.configFile` 指向宿主配置;`vas.liveDiagnostics` 默认 true,450 ms 防抖,可关闭。 +- VS2026:Tools → Options → VerseAngelScript → Toolchain 配置 Compiler executable,并启用 Live diagnostics(默认 false,用户明确开启);项目祖先目录需有 `.vas/vasbuild.config.txt`。源码模型 75 ms 防抖,编译再延迟 400 ms,全局串行检查。 + +后台检查有依赖数量/源码大小上限和进程超时;VS Code 每个文档最多一个检查进程,VS 全局最多一个,编辑后取消旧进程。自动检查不触发 Build Project。 + +## 项目文件与生效方式 + +Rider/NMake 的源码须属于解决方案项目项。部署示例已把 `src/Arena/*.vas`、`basics.vas` 与宏文件列入 `out/deployment/VASDemo/VASDemo.vcxproj`。新增模块用 Add Existing Item,或更新 `` 后重新加载项目;仅复制到目录不能保证 Rider 后端将它纳入工程索引。 + +安装当前源码打包的扩展并重启对应 IDE。旧包不含本次提供器,即使原生编译器已更新,也不会自动获得新语言服务。可用安装包集中复制到 `out/deployment/IDEExtensions/`。 + +## Rider 查找用法(0.5.9) + +Find Usages / Show Usages 的原生入口接入 VAS 只读搜索,使用平台单词索引筛选候选,再按 import/include 闭包、作用域、接收者和参数数确认唯一源码声明。包含宏/条件指令的已知调用不再因重命名覆盖检查而消失。Code Vision 用法计数及 VAS Callers/Callees 同步采用此查询。声明位置与调用位置都能发起原生查找;符号识别复用随 PSI 更新的声明快照,避免用法计数逐次重扫文件全文。真实 Solution Host 验证 `Arena/Demo.vas` 的 `RunBatch` 返回 `main.vas` 中的一个调用,并验证重载歧义不会成为误报。 + +此结果是源码中的候选用法,可能位于条件宏的非活动分支;尚不表示编译器选定的活动分支。重命名仍使用完整依赖覆盖预检,缺少预处理上下文或绑定歧义时拒绝修改;只读查找不会降低这个约束。 + +## 模型边界与缓存 + +编辑器使用源码声明模型,不等于完整编译器类型绑定。条件宏激活、`#undef`、宏展开生成声明、复杂表达式返回类型、继承成员与重载类型选择尚未建模;编辑器显示已找到的声明/宏候选,可能包含非活动分支。歧义导航保留多个候选或不跳转,不随意选同名文件。Rider 重命名仍使用完整覆盖预检,未将部分闭包候选用于重命名。VS Code/VS 没有跨文件重命名。 + +目录搜索使用局部路径、项目祖先/entry 根提示和 `VAS_INCLUDE_PATH`,不遍历整个磁盘。编辑提示不会代替编译器的 project descriptor 或实际 loaded-source 闭包。VS Code/VS 最多扫描 256 文件、4 MiB/文件、16 MiB 总源码;Rider 的依赖闭包限 256 文件、16 MiB 总源码。未实现的语义以编译结果为准。 + +VS Code 优先读取打开文档,包括未保存模块,编辑与文件通知使缓存失效。VS 后台读取已登记的打开缓冲区,用快照版本阻止旧结果发布,75 ms 合并连续编辑;磁盘外部改动在下一次补全/悬浮/F12请求重新扫描,纯着色期间不承诺实时检测外部文件。Rider 缓存依赖闭包与 PSI 候选,并复用每次 token 扫描的括号/作用域拓扑。 + +## 本机验证 + +- Rider Build 262 的真实 Solution Host:竞技场 9 文件闭包、声明/宏项目索引、跨模块导航和 Go to Symbol;原有重命名/作用域/循环依赖/Unicode 回归通过。Native TypedAction、Enter/Backspace、原生补全提交及应用级编译器/未保存模块快照通过实际宿主测试。 +- Windows VS Code 1.139.1:5 类符号实际输入/退格/右符号跳过、函数调用补全、参数提示、结构/编译器错误、漏分号、修正清除和未保存 import 快照;import/声明 F12、命名空间与宏补全、悬浮、文档符号、语义 token;未保存模块修改与恢复使旧定义正确失效。 +- Windows 实际 VS18:9 个真实编辑器测试通过,包含竞技场原生补全、宏补全、F12、语义颜色、Unicode、词法、注释/撤销及括号;新版实际输入测试还验证调用括号、参数提示、结构/原生编译器错误和修正后的清除。 + +这些是本机语言服务验证,不替代其他平台/最低宿主版本的 CI 矩阵或完整类型系统验收。可复现测试位于各扩展的 `test` / `src/test` 目录,证据位于 `out/verification/ide/`。 + +## 性能评估 + +下面只计声明扫描或依赖模型,排除 IDE 启动、界面渲染和完整编译。OS 文件缓存可能已预热。 + +| 测量 | 结果 | +| --- | --- | +| Rider,9 文件竞技场声明扫描,中位数 | 7.47 → 6.95 ms | +| Rider,1500 函数 / 4501 声明,中位数 | 413.12 → 16.10 ms,约 25.7 倍 | +| VS Code,9 文件无模型缓存,31 次中位数 / P95 | 4.84 / 7.36 ms | +| VS Code,复用缓存,中位数 / P95 | 0.98 / 1.34 ms | +| VS Code,main 文件语义查询,中位数 | 0.24 ms | +| VS,重新读取/解析 9 文件,31 次中位数 / P95 | 4.19 / 4.96 ms | +| VS Code,3857 字符文件的即时结构检查,101 次中位数 / P95 | 0.25 / 0.55 ms | +| VS Code,同一文件的输入上下文检查,中位数 / P95 | 0.19 / 0.30 ms | + +Rider 优化去掉了逐声明重复构造整个文件的作用域表及扫描前缀,复用单次扫描的括号配对、所在作用域、函数声明判定。优化对比时前后竞技场均保留 162 个声明,合成文件均保留 4501 个声明;之后补齐枚举值新增 3 个声明,不属于性能优化导致的变化;行为回归另行验证。计时是信息性评估,不用易抖动的毫秒阈值替代正确性测试。 + +复现入口:Rider `VasIndexPerformanceTest`(`vas.performance.phase` 控制证据文件后缀)、`node tools/vscode-extension/test/measureLanguage.js`、VS 核心测试程序 `--language`。 diff --git a/docs/ide-setup.md b/docs/ide-setup.md index c878b5a0e..5dba8aa76 100644 --- a/docs/ide-setup.md +++ b/docs/ide-setup.md @@ -1,20 +1,23 @@ # 三种 IDE 的安装与工程构建 -Rider、VS Code、Visual Studio 2026 当前源码均支持显式 **Build Project**:使用同一原生 `vasbuild` 读取根目录 `vas-project.json`,由用户确认编译单元,再构建已保存输入。这里介绍当前适配器的用法;语义补全及其前置模块暂缓,历史计划保留在 [IDE 路线图](ide-roadmap.md)。 +Rider、VS Code、Visual Studio 2026 当前源码均支持显式 **Build Project**:使用同一原生 `vasbuild` 读取根目录 `vas-project.json`,由用户确认编译单元,再构建已保存输入。当前源码还提供模块依赖导航、声明补全和语义颜色;历史计划保留在 [IDE 路线图](ide-roadmap.md)。 ## 当前能力与宿主范围 | 能力 | Rider | VS Code | Visual Studio 2026 | | --- | --- | --- | --- | -| `.vas` 编辑 | 词法高亮、注释、括号;已有启发式补全/导航/用法/重命名 | TextMate 高亮、注释、括号、缩进、代码片段 | 共用 VS Code 的词法/编辑配置,无代码片段注册 | +| `.vas` 编辑 | 词法与类型/函数/宏语义颜色、注释、括号 | TextMate 与语义 token、注释、括号、缩进、代码片段 | 共用 TextMate,另加类型/函数/宏语义颜色 | +| 模块与符号 | import/include 闭包、F12、Go to Symbol / Search Everywhere、宏候选 | import/include F12、文档符号、悬浮、宏候选 | import/include F12、异步悬浮、宏候选 | +| 输入与参数 | 符号配对、右符号跳过、退格/缩进、函数调用补全、参数提示 | 原生配对、代码片段调用补全与参数提示 | 原生配对、函数调用补全与 Edit.ParameterInfo | +| 补全 | 依赖声明、局部作用域、命名空间、简单对象成员;第二次调用扩展至工程索引 | 依赖声明、局部变量、命名空间、简单对象成员与运行时函数 | 原生补全窗口,依赖声明、命名空间、简单对象成员与运行时函数 | | 工程构建 | `Build VAS Project` | `VAS: Build Project` | `Build VAS Project...` | | 工程诊断 | `VAS Project Build` 工具窗口、已验证位置导航 | Problems、任务终端、已验证位置导航 | Error List、`VAS Project Build` Output、已验证位置导航 | -| 当前文件 | 既有 Build / Run、受信任项目中的后台编译诊断 | Build / Run,无后台编译诊断 | 无对应扩展命令 | -| 执行授权 | Rider 项目信任 + 应用级编译器设置 | Workspace Trust + User/Remote 编译器设置 | 每次对话框的明确操作授权;原生信任同步未验证 | +| 当前文件 | Build / Run、即时结构错误与受信任项目后台编译诊断 | Build / Run、即时结构错误与可配置后台编译诊断 | 即时结构错误与用户明确启用的后台编译诊断 | +| 执行授权 | Rider 项目信任 + 应用级编译器设置 | Workspace Trust + User/Remote 编译器设置 | 工程构建每次明确操作;后台编译需用户设置开启;原生信任同步未验证 | | 声明的宿主范围 | Rider 2026.2 / Build `262.*` | `engines.vscode: ^1.96.0` | Windows、VS 18.x、x64 | -| 本轮真实宿主 CI | Windows Rider Build 262 Solution Host | Linux/macOS/Windows × 1.96.4/stable | Windows 实际 VS18,Open Folder 和 `.sln` | +| 既有构建适配 CI 矩阵 | Windows Rider Build 262 Solution Host | Linux/macOS/Windows × 1.96.4/stable | Windows 实际 VS18,Open Folder 和 `.sln` | -Rider 编辑服务仍是启发式解析;逐次重命名预检不等于编译器绑定。另两端的词法资产不提供语义补全。三端均无 Run Project、完整未保存语义服务、LSP、DAP、UE SDK 或 C++ 功能对齐。Linux 工具/协议测试不能证明 Rider 或 VS2026 的其他平台宿主行为。 +三端采用源码声明模型,尚无完整编译器类型绑定、条件宏展开语义或跨平台宿主保证。Rider 保留保守重命名预检,VS Code/VS 不提供跨文件重命名。详细行为、性能与本机验证见 [语言服务说明](ide-language-support.md)。三端均无 Run Project、完整未保存语义诊断、LSP、DAP、UE SDK 或 C++ 功能对齐。 ## 先准备独立的原生工具 @@ -29,6 +32,14 @@ cmake --build --preset windows-msvc-v145-cxx23-release --target vasbuild vasrun 产物为 `out/build/windows-msvc-v145-cxx23/Release/vasbuild.exe` 与 `vasrun.exe`。只做项目构建时不需要 `vasrun`。 +默认 `vasrun` 宿主的 `print` 支持字符串、所有有符号/无符号整数类型、`float`、`double` 和 `bool`,可直接写 `print(72)` 或 `print(result2)`。布尔值输出 `true`/`false`;不会自动追加换行。使用离线编译器时,host API 配置须包含匹配的重载;仅更新插件或配置、仍使用旧 `vasrun`,无法运行数字参数调用。自定义宿主需自行注册这些重载。 + +`println("result = {}", result2)` 参考 [C++23 `std::println`](https://open-std.org/JTC1/SC22/WG21/docs/papers/2022/p2093r14.html) 的核心语义:先格式化,再向标准输出追加一个换行,不强制刷新。支持字符串及上述基本类型,支持 `{}`、`{0}`、`{{`/`}}`、宽度/对齐、进制、浮点精度和动态宽度/精度,如 `println("hex={:04X}, pi={:.2f}", 72, 3.14159)`。格式串本身已有换行时仍会再追加一个换行;参数中的花括号按普通数据输出。 + +VAS 另提供 `println(result2)` 和空参数 `println()` 作为便捷扩展(C++23 的 `std::println` 要求格式串)。格式化由固定版本的 {fmt} 实现,不使用现有的简易 `format` 函数;直接调用中的字面量格式串(含相邻字面量和括号)在编译期检查语法、参数索引、格式规格及动态宽度/精度的参数类型;不支持的参数类型也会在编译期拒绝。变量、拼接结果和 `const string` 变量不做内容常量传播,仍在运行期检查;负宽度等实际参数值错误报告为脚本异常。格式化失败不输出部分正文。此接口不提供 C++ 的 `FILE*`/`ostream` 重载,不能视为完整 ISO C++ 标准库实现。运行时、host API 配置和模板均须同步更新。 + +`print` 使用同一套格式化规则,但不追加换行。`value` 为整数时,`println("ABC + " + value + " ASDA")` 与 `println("ABC + {} ASDA", value)` 在无未转义花括号时输出相同,`print` 同样支持两种写法。`{}` 不会自动捕获作用域里的变量,字面量格式串省略实参会产生编译错误,动态格式串省略实参会产生脚本异常。两者的字符串参数均按格式串解释:字面花括号须写 `{{`/`}}`,原先 `print("{")` 的裸花括号写法应改为 `print("{{")` 或 `print("{}", "{")`;参数内容中的花括号无需转义。直接数字输出采用默认格式化(浮点数不再受原来的流输出六位精度限制)。 + Linux/macOS 的工具构建需要 CMake 3.21+、支持 C++23 的编译器及相应构建工具;以下使用单配置 Makefiles: ```sh @@ -52,7 +63,7 @@ cmake --build out/build/ide-tools --target vasbuild vasrun 先解压 Actions 下载的外层 ZIP,里面仅有原始安装 ZIP/VSIX、`manifest.json` 和 `SHA256SUMS`。核对 manifest 的源码 commit/tree、宿主和包 SHA-256,再按下方对应 IDE 安装**内层安装包**。PR 工作流可能构建合并 checkout;manifest 分别记录实际构建 commit 和 PR head,不能将两者混为一谈。`vs2026-editor-project-results` 是独立的测试证据包,不能安装。 -这些是 CI 开发产物,不是 Releases 或 Marketplace 发布;未更改扩展版本号,也没有新增签名流程。过期或找不到成功运行的产物时,可从所需提交自行打包。三端 Build Project 仍需单独构建并设置上述原生编译器。 +这些是 CI 开发产物,不是 Releases 或 Marketplace 发布;本次语言服务版本为 Rider 0.5.7、VS Code/VS2026 0.2.0,没有新增签名流程。过期或找不到成功运行的产物时,可从所需提交自行打包。三端 Build Project 仍需单独构建并设置上述原生编译器。 ### 从源码打包和安装 @@ -66,7 +77,7 @@ cmake --build out/build/ide-tools --target vasbuild vasrun 默认下载 Rider `2026.2.0.2`。使用已有安装时加 `-PriderPath='C:\Path\To\Rider-262'`,必须匹配 Build 262。ZIP 位于 `tools/rider-plugin/build/distributions/`。在 Rider **Settings → Plugins → 齿轮 → Install Plugin from Disk** 中选择本次生成的 ZIP,按提示重启。 -仓库 `plugins/rider/VerseAngelScript-Rider-Plugin-0.5.6.zip` 是较早的已检入安装包,不能当作当前源码产物;源码版本号仍为 `0.5.6`,同版本号不表示相同内容。当前适配能力应使用本次源码打包的 ZIP。[Rider 详细说明](../tools/rider-plugin/README.md) +仓库 `plugins/rider/VerseAngelScript-Rider-Plugin-0.5.6.zip` 是较早的已检入安装包,不能当作当前源码产物;当前源码版本为 `0.5.7`,支持模块/宏索引与语义颜色。当前适配能力应使用本次源码打包的 ZIP。[Rider 详细说明](../tools/rider-plugin/README.md) #### VS Code @@ -78,7 +89,7 @@ npm ci npm run package ``` -产物为 `tools/vscode-extension/verseangelscript-vscode-0.1.0.vsix`。在 VS Code 执行 **Extensions: Install from VSIX...**,选择该文件。[VS Code 详细说明](../tools/vscode-extension/README.md) +产物为 `tools/vscode-extension/verseangelscript-vscode-0.2.0.vsix`。在 VS Code 执行 **Extensions: Install from VSIX...**,选择该文件。[VS Code 详细说明](../tools/vscode-extension/README.md) #### Visual Studio 2026 @@ -138,6 +149,20 @@ Linux/macOS 将可执行文件换为 `./out/build/ide-tools/vasbuild` 即可。d 两次按钮操作仅授权本次 descriptor/build,不建立持久 workspace trust。公开 SDK 的原生 trust-state 查询与实际 MOTW(网络来源标记)提示/取消行为仍未验证,不能把打开文件夹当作已通过原生信任检查。取消只保证终止扩展拥有的直接编译器进程,不承诺终止其子孙进程。 +## 模块与宏示例 + +`import math;`、`#include "math.vas"` 与 `#include ` 共用原生依赖加载和去重;导入文件中的全部宏自动可见,并支持传递导出。查看 [可运行示例](../examples/modules/README.md) 和 [解析规则、宏语义与性能测量](modules-and-macros.md)。Rider 新语法需使用当前源码重新打包的插件。 + +更完整的 [模块化竞技场](../examples/arena/README.md) 按 Epic 风格组织九个 VAS 文件,演示类、接口、句柄、角色技能、战斗循环、排行榜、自检和批量模拟。默认宿主配置与运行器统一使用数组/字符串的 `length()` 方法,不注册运行器未提供的 `get_length/set_length` 属性访问器。 + +## 格式化函数注册与性能 + +默认配置使用 `formatfunc "void println(const string&in format, const ?&in ...)"`(`print` 同理)。编译器据此为这个具体宿主函数启用格式检查;普通 `func` 或脚本中的同名函数不受影响。自定义宿主可调用 `asIScriptFunction::SetFormatStringValidator` 注册检查回调,`WriteConfigToStream` 会保留标记。`ConfigEngineFromStream` 读取标记时必须提供回调,未提供会明确报错,避免静默丢失检查。原生宿主须用配套的新头文件和引擎库重新构建。 + +数值拼接去掉了临时数字字符串:整数在普通 locale 下使用栈上的十进制转换,浮点数和自定义 locale 使用栈缓冲流,保持原来的六位有效数字和 locale 语义。返回字符串一次预留空间;极端宿主数字格式可安全回退。连续 `+` 仍产生每个运算步骤的结果字符串,需要实际分配时仍有成本。格式化调用借用字符串参数,16 个以内参数使用栈存储,输出先写入 500 字节内联缓冲;超过容量自动扩容,不是语言参数/长度限制。较长输出优先使用 `println("ABC + {} ASDA", value)`,避免拼接中间串。 + +`vas_format_performance` 测试比较旧算法和实际新回调,并检查数值边界、浮点精度、locale、自定义长数字格式、注册元数据往返和同名函数隔离。Windows Release 的 10,000 次固定微基准中,80 字节前缀拼接 `int64` 最小值从每次 3 次堆分配降至 1 次;短字符串加整数的格式构造从每次 5 次降至 0 次。格式化数据不超过内联容量,数字是标准基本类型;该测量不含引擎编译、执行框架或标准输出 I/O,不能代表所有打印调用零分配。 + ## 保存、失效与常见问题 - **先保存再构建**:三端项目构建均以磁盘输入为准;未保存源码、manifest、所选 host config 及相关物理别名会阻止构建或结果发布。Rider 不自动保存;VS Code 自身任务流程可能按 `task.saveBeforeRun` 或旧版 Rerun 行为先保存。首次编译才发现的 dirty include 可能在产物已写出后使结果被拒绝,此产物不能代表未保存编辑内容 diff --git a/docs/modules-and-macros.md b/docs/modules-and-macros.md new file mode 100644 index 000000000..c023b7c6a --- /dev/null +++ b/docs/modules-and-macros.md @@ -0,0 +1,81 @@ +# 模块导入、宏与性能 + +VAS 的原生 `vasbuild` 和 `vasrun` 共用 `vas::ScriptBuilder` 预处理层。原有嵌入式 `CScriptBuilder` 保持独立;直接使用它的宿主需要切换到 VAS 包装层才能获得这里的模块和宏语义。 + +## 依赖语法 + +```cpp +import math; // math.vas +import utils.math; // utils/math.vas +#include "math.vas" +#include +``` + +模块导入必须位于文件作用域。上述形式最终都将依赖加入同一个编译单元,函数、类型、变量和宏的可见性一致,不自动建立命名空间。需要隔离符号时,在模块文件内显式声明 `namespace`。原来的函数绑定语法 `import int host(int) from "other";` 继续保留。 + +引用和去重规则: + +| 写法 | 查找规则 | +| --- | --- | +| `import math;`、双/单引号 include | 先尝试引用文件所在目录;不存在时查找入口目录和配置的搜索目录 | +| `` | 查找入口目录和配置的搜索目录,不优先查找嵌套引用文件所在目录 | +| 绝对路径 include | 直接解析指定路径 | + +默认搜索根包含编译入口目录。工具还读取 `VAS_INCLUDE_PATH`:Windows 用分号分隔,Linux/macOS 用冒号分隔;其中的相对目录基于入口目录。嵌入式宿主可使用 `AddSearchPath`,该 API 的相对路径基于进程工作目录。搜索根内有多个不同文件匹配时明确报歧义,不随机选一个;引号和 import 的本地匹配优先。 + +同一次构建按绝对路径、斜杠统一、词法 `.`/`..` 消解后的文件名去重,Windows 对 ASCII 路径字母忽略大小写。三种形式可交替引用、重复引用、循环引用,同一文件只处理一次。此规则不做物理符号链接身份识别。重新构建会清空宏、路径解析和文件去重缓存,重新读取输入,避免依赖修改后使用旧内容。 + +## 所有宏自动可见 + +```cpp +// math.vas +#define MATH_VERSION 1 +#define MATH_ADD(a, b) ((a) + (b)) + +// main.vas +import math; +println("版本:{},结果:{}", MATH_VERSION, MATH_ADD(50, 22)); +``` + +宏字典由本次编译单元共享,按照源码顺序处理。导入方在引用前定义的宏对依赖文件可见;依赖定义的全部宏在返回后对导入方可见,包括传递依赖的宏。没有单独的 `export` 标记。`#undef` 也作用于这个共享字典。 + +循环依赖不会重新处理文件,因此只能观察到进入循环前已经定义的宏,后面的定义不会提前可见。一个模块用不同宏配置多次导入,采用第一次导入的配置。当前是共享预处理环境和单次编译语义,没有独立模块产物或跨构建模块缓存。 + +同名、同参数名、同替换 token 序列的重复定义允许;空白差异忽略。不同定义是编译错误,并提供此前定义位置。普通字符串和注释内部不会展开宏。宏替换会保留 token 边界,避免 `+`、`+` 意外合成 `++`;支持对象宏、函数宏、嵌套调用和对象宏到函数宏的别名。 + +条件支持 `#if/#ifdef/#ifndef/#elif/#else/#endif`、`defined`、整数算术、位操作、比较和逻辑短路;未定义标识符按零处理。整数字面量遵循 VAS 的十进制和 `0x/0b/0o/0d` 前缀,支持数字分隔符。支持 `#define`、`#undef`、反斜杠续行和 `#error`;宿主的 `DefineWord` 作为值为 1 的宏参与判断。 + +当前不支持宏字符串化 `#`、token 拼接 `##` 和可变参数宏;这些写法会报错。宏展开中的字符串需用 `\n` 表达换行,带物理换行的宏字符串会明确被拒绝。普通源码的多行字符串保持原有支持。这是 VAS 的宏子集,不宣称完整 ISO C 预处理兼容。 + +展开深度最多 64,依赖和条件嵌套最多 128;每节预处理 token 和一次构建的展开工作量分别限制为 100 万,预处理后的单节最大 64 MiB。错误诊断会映射回原文件及 UTF-8 字节列;宏生成的格式串同样进入 `print/println` 编译期格式检查。JSONL 加载报告仍记录实际读取的原始文件字节和依赖事件。 + +## 性能验证 + +新增测试入口: + +```powershell +ctest --preset windows-msvc-v145-cxx23-release --output-on-failure +# 单独测量:在 out/build/windows-msvc-v145-cxx23 中运行 +.\Release\vas_module_performance_test.exe module-performance +``` + +Windows MSVC v145 Release 微基准采用一次预热、三次测量的中位数,双方都在 OS 文件缓存已预热的条件下测量。加载/预处理和引擎编译分别计时,以下是本机的一次结果: + +| 场景 | 原有 builder / 初版实现 | 优化后 | 验证 | +| --- | --- | --- | --- | +| 2,000 个普通函数,加载/预处理 | 原有 0.969 ms | 1.011 ms | 无宏/依赖文件走快速路径,不新增词法扫描 | +| 10,000 次重复引号 include | 原有 19.031 ms | 9.155 ms | 入口和依赖各读一次,共 2 次 | +| 10,000 次混合 import/引号/尖括号 | 不适用 | 9.170 ms | 三种写法合并去重,共 2 次读取 | +| 10,000 次函数宏调用 | 初版 26.911 ms | 16.516 ms | 替换结果为 30,000,与显式展开一致 | + +优化包括缓存规范路径及解析结果、哈希去重、读取前预留文件缓冲、借用原始 token 文本、预计算宏参数替换槽、减少临时容器和合并源码映射片段。普通无宏源码保留快速路径;本轮普通文件约增加 0.042 ms,未观察到有意义的编译时间差异,不宣称所有输入都更快。 + +宏仍有编译前处理成本:同一基准的显式展开源码加载约 3.778 ms,函数宏约 16.516 ms;其后引擎编译分别约 89.7/92.0 ms。不会把预处理成本描述为零。另一项断言比较含变量的函数宏和手写表达式生成的完整函数字节码,要求逐字相同,验证该例没有新增运行时指令。 + +时间取决于机器、输入和系统负载,不设容易波动的毫秒 CI 门槛。运行输出、重复文件读取次数、重新构建缓存失效、宏字节码一致性以及错误拒绝是硬断言。日志保存在本地 `out/verification/modules/`,未作为通用性能保证。 + +## 编辑器支持边界 + +Rider 新包识别模块导入和尖括号依赖,保留原函数 import 的词法结构;词法、依赖和符号扫描有单元测试。当前宏和条件编译下的静态依赖分析仍采取保守策略;配置的搜索根或宏环境无法证明时,不承诺完整重命名和导航。实际编译及宏诊断以原生工具为准。插件安装后需要重启 Rider;原生部署工具更新即可运行这些示例。 + +完整可运行代码见 [examples/modules](../examples/modules/README.md)。 diff --git a/examples/arena/Arena/Battle.vas b/examples/arena/Arena/Battle.vas new file mode 100644 index 000000000..55d9de981 --- /dev/null +++ b/examples/arena/Arena/Battle.vas @@ -0,0 +1,92 @@ +import Combatant; +import Skills; // Shared Combatant dependency is processed only once. + +namespace Arena +{ + class FBattleResult + { + string LeftName; + string RightName; + int32 LeftHealth; + int32 RightHealth; + int32 LeftDamageDealt; + int32 RightDamageDealt; + int32 LeftHealingDone; + int32 RightHealingDone; + int32 RoundCount = 0; + int32 WinnerIndex = -1; // -1: draw, 0: left wins, 1: right wins. + } + + void TakeTurn(FCombatant@ Actor, FCombatant@ Target, ICombatSkill@ Attack, ICombatSkill@ Heal, + FDeterministicRandom@ Random, bool bVerbose) + { + if (!Actor.IsAlive() || !Target.IsAlive()) + { + return; + } + ICombatSkill@ Selected = Attack; + if (Actor.Role == Medic && Actor.Health <= Actor.MaxHealth / 2) + { + @Selected = Heal; + } + int32 Amount = Selected.Execute(Actor, Target, Random); +#if VAS_ARENA_VERBOSE + if (bVerbose) + { + println(" {} {}:{},双方 HP = {} / {}", Actor.Name, Selected.GetLabel(), Amount, Actor.Health, Target.Health); + } +#endif + } + + FBattleResult@ SimulateBattle(FCombatant@ Left, FCombatant@ Right, uint32 Seed, bool bVerbose) + { + FDeterministicRandom Random(Seed); + // Create skills once per battle and reuse them inside the round loop. + FAttackSkill Attack; + FHealSkill Heal; + FBattleResult@ Result = FBattleResult(); + for (int32 Round = 1; Round <= VAS_ARENA_MAX_ROUNDS && Left.IsAlive() && Right.IsAlive(); ++Round) + { + Result.RoundCount = Round; +#if VAS_ARENA_VERBOSE + if (bVerbose) + { + println("第 {:02d} 回合", Round); + } +#endif + // Alternate initiative each round and check both combatants before every action. + if (Round % 2 == 1) + { + TakeTurn(Left, Right, Attack, Heal, Random, bVerbose); + TakeTurn(Right, Left, Attack, Heal, Random, bVerbose); + } + else + { + TakeTurn(Right, Left, Attack, Heal, Random, bVerbose); + TakeTurn(Left, Right, Attack, Heal, Random, bVerbose); + } + } + Result.LeftName = Left.Name; + Result.RightName = Right.Name; + Result.LeftHealth = Left.Health; + Result.RightHealth = Right.Health; + Result.LeftDamageDealt = Left.DamageDealt; + Result.RightDamageDealt = Right.DamageDealt; + Result.LeftHealingDone = Left.HealingDone; + Result.RightHealingDone = Right.HealingDone; + if (Left.IsAlive() && !Right.IsAlive()) + { + Result.WinnerIndex = 0; + } + if (Right.IsAlive() && !Left.IsAlive()) + { + Result.WinnerIndex = 1; + } + return Result; + } + + string GetWinnerLabel(FBattleResult@ Result) + { + return Result.WinnerIndex == 0 ? Result.LeftName : Result.WinnerIndex == 1 ? Result.RightName : "平局"; + } +} diff --git a/examples/arena/Arena/Checks.vas b/examples/arena/Arena/Checks.vas new file mode 100644 index 000000000..5086e9701 --- /dev/null +++ b/examples/arena/Arena/Checks.vas @@ -0,0 +1,93 @@ +import Report; + +namespace Arena +{ + class FSelfTestChecks + { + int32 Count = 0; + int32 Failures = 0; + + void Expect(bool bCondition, const string&in Description) + { + ++Count; + if (!bCondition) + { + ++Failures; + println("[FAIL] {}", Description); + } + } + } + + bool AreSelfTestsPassing() + { + FSelfTestChecks Checks; + Checks.Expect(Clamp(-5, 0, 10) == 0, "clamp 下界"); + Checks.Expect(Clamp(15, 0, 10) == 10, "clamp 上界"); + Checks.Expect(Clamp(7, 0, 10) == 7, "clamp 区间内"); + Checks.Expect(CreateCombatant(99) is null, "非法角色索引返回 null"); + FCombatant@ Combatant = CreateCombatant(0); + Checks.Expect(Combatant.ApplyDamage(-10) == 0 && Combatant.Health == 90, "负伤害不回血"); + Checks.Expect(Combatant.ApplyDamage(7) == 7 && Combatant.Health == 83, "实际伤害"); + Checks.Expect(Combatant.RestoreHealth(1000) == 7 && Combatant.Health == 90, "治疗封顶"); + Checks.Expect(Combatant.RestoreHealth(-10) == 0 && Combatant.Health == 90, "负治疗不扣血"); + Checks.Expect(Combatant.ApplyDamage(1000) == 90 && !Combatant.IsAlive(), "致命伤害封底"); + Checks.Expect(Combatant.RestoreHealth(18) == 0 && Combatant.Health == 0, "治疗不复活"); + + FDeterministicRandom FirstRandom(42); + FDeterministicRandom ReplayRandom(42); + FDeterministicRandom DifferentRandom(43); + bool bEqualSequence = true; + for (uint32 Index = 0; Index < 20; ++Index) + { + bEqualSequence = (FirstRandom.Next() == ReplayRandom.Next()) && bEqualSequence; + } + Checks.Expect(bEqualSequence, "相同种子生成相同序列"); + FDeterministicRandom InitialRandom(42); + Checks.Expect(InitialRandom.Next() != DifferentRandom.Next(), "不同种子改变序列"); + Checks.Expect(FirstRandom.NextBelow(0) == 0, "零范围随机数避免除零"); + + ICombatSkill@ Attack = FAttackSkill(); + ICombatSkill@ Heal = FHealSkill(); + FDeterministicRandom CriticalRandom(0); + FDeterministicRandom NormalRandom(1); + FCombatant@ Actor = CreateCombatant(0); + FCombatant@ Target = CreateCombatant(1); + Checks.Expect(Attack.Execute(Actor, Target, NormalRandom) == 12, "普通攻击扣除护甲"); + @Target = CreateCombatant(1); + Checks.Expect(Attack.Execute(Actor, Target, CriticalRandom) == 30, "暴击宏与接口调用"); + Actor.ApplyDamage(20); + Checks.Expect(Heal.Execute(Actor, Target, NormalRandom) == 18 && Actor.Health == 88, "治疗技能多态"); + Checks.Expect(Attack.Execute(null, Target, NormalRandom) == 0, "空句柄保护"); + Checks.Expect(Attack.Execute(Combatant, Target, NormalRandom) == 0, "倒下角色不能行动"); + + FBattleResult@ FirstResult = SimulateBattle(CreateCombatant(0), CreateCombatant(1), 42, false); + FBattleResult@ SecondResult = SimulateBattle(CreateCombatant(0), CreateCombatant(1), 42, false); + Checks.Expect( + FirstResult.WinnerIndex == SecondResult.WinnerIndex && + FirstResult.LeftHealth == SecondResult.LeftHealth && + FirstResult.RightHealth == SecondResult.RightHealth && + FirstResult.RoundCount == SecondResult.RoundCount && + FirstResult.LeftDamageDealt == SecondResult.LeftDamageDealt && + FirstResult.RightDamageDealt == SecondResult.RightDamageDealt, + "整场战斗可重放"); + Checks.Expect( + FirstResult.RoundCount > 0 && FirstResult.RoundCount <= VAS_ARENA_MAX_ROUNDS && + FirstResult.LeftHealth >= 0 && FirstResult.RightHealth >= 0, + "回合上限和 HP 范围"); + + FStanding Left("左"), Right("右"); + FBattleResult Result; + Result.WinnerIndex = 0; + Result.LeftDamageDealt = 17; + RecordResult(Left, Right, Result); + Checks.Expect(Left.GetPoints() == 3 && Left.Wins == 1 && Right.Losses == 1 && Left.DamageDealt == 17, + "胜负积分和伤害归档"); + Result.WinnerIndex = -1; + RecordResult(Left, Right, Result); + Checks.Expect(Left.GetPoints() == 4 && Right.GetPoints() == 1 && Left.Draws == 1 && Right.Draws == 1, + "平局积分归档"); + Checks.Expect(ShouldRankBefore(Left, Right), "排行榜积分优先"); + println("SELF_TEST passed={} failed={}", Checks.Count - Checks.Failures, Checks.Failures); + return Checks.Failures == 0; + } +} diff --git a/examples/arena/Arena/Combatant.vas b/examples/arena/Arena/Combatant.vas new file mode 100644 index 000000000..0abb767e8 --- /dev/null +++ b/examples/arena/Arena/Combatant.vas @@ -0,0 +1,70 @@ +import Config; +import Math; + +namespace Arena +{ + enum ECombatRole + { + Warrior, + Guardian, + Medic + } + + class FCombatant + { + string Name; + ECombatRole Role; + int32 MaxHealth; + int32 Health; + int32 Attack; + int32 Armor; + int32 DamageDealt = 0; + int32 HealingDone = 0; + + FCombatant(const string&in Label, ECombatRole Kind, int32 InitialHealth, int32 Power, int32 Defense) + { + Name = Label; + Role = Kind; + MaxHealth = InitialHealth; + Health = InitialHealth; + Attack = Power; + Armor = Defense; + } + + bool IsAlive() const + { + return Health > 0; + } + + // Return the actual change so excess damage and healing do not inflate statistics. + int32 ApplyDamage(int32 Amount) + { + int32 Actual = Clamp(Amount, 0, Health); + Health -= Actual; + return Actual; + } + + int32 RestoreHealth(int32 Amount) + { + if (!IsAlive()) + { + return 0; // Healing does not revive defeated combatants. + } + int32 Actual = Clamp(Amount, 0, MaxHealth - Health); + Health += Actual; + HealingDone += Actual; + return Actual; + } + } + + FCombatant@ CreateCombatant(uint32 Index) + { + switch (Index) + { + case 0: return FCombatant("剑士", Warrior, 90, 18, 2); + case 1: return FCombatant("守卫", Guardian, 110, 14, 6); + case 2: return FCombatant("医师", Medic, 82, 12, 3); + } + return null; + } +} diff --git a/examples/arena/Arena/Config.vas b/examples/arena/Arena/Config.vas new file mode 100644 index 000000000..78efad766 --- /dev/null +++ b/examples/arena/Arena/Config.vas @@ -0,0 +1,16 @@ +// Defaults are shared by the compilation unit and may be overridden by the entry point. +#ifndef VAS_ARENA_VERBOSE +#define VAS_ARENA_VERBOSE 1 +#endif +#ifndef VAS_ARENA_MAX_ROUNDS +#define VAS_ARENA_MAX_ROUNDS 12 +#endif +#define VAS_ARENA_VERSION "1.0" +#define VAS_ARENA_CRIT_PERCENT 25 +#define VAS_ARENA_CRITICAL_DAMAGE(Amount) ((Amount) * 2) +#if VAS_ARENA_MAX_ROUNDS < 1 || VAS_ARENA_MAX_ROUNDS > 100 +#error VAS_ARENA_MAX_ROUNDS 必须在 1..100 范围内 +#endif +#if VAS_ARENA_VERBOSE != 0 && VAS_ARENA_VERBOSE != 1 +#error VAS_ARENA_VERBOSE 只能是 0 或 1 +#endif diff --git a/examples/arena/Arena/Demo.vas b/examples/arena/Arena/Demo.vas new file mode 100644 index 000000000..da0e73488 --- /dev/null +++ b/examples/arena/Arena/Demo.vas @@ -0,0 +1,70 @@ +import Report; +import Checks; + +namespace Arena +{ + int32 RunDemo(bool bVerbose) + { + println("=== VAS 模块化竞技场 v{} ===", VAS_ARENA_VERSION); + println("配置:最多 {} 回合,暴击率 {}%,日志宏 = {}", VAS_ARENA_MAX_ROUNDS, VAS_ARENA_CRIT_PERCENT, VAS_ARENA_VERBOSE); + // Configuration macros are exported transitively; print accepts primitives and concatenation. + print("预览:暴击伤害 = "); + print(VAS_ARENA_CRITICAL_DAMAGE(18)); + println(" | " + "固定种子保证战斗可重放"); + if (!AreSelfTestsPassing()) + { + return 1; + } + + array Standings; + Standings.reserve(3); + for (uint32 Index = 0; Index < 3; ++Index) + { + Standings.insertLast(FStanding(CreateCombatant(Index).Name)); + } + uint32 MatchCount = 0; + for (uint32 Left = 0; Left < 3; ++Left) + { + for (uint32 Right = Left + 1; Right < 3; ++Right) + { + ++MatchCount; + println(); + println("[比赛 {}] {} vs {}", MatchCount, Standings[Left].Name, Standings[Right].Name); + FBattleResult@ Result = SimulateBattle(CreateCombatant(Left), CreateCombatant(Right), 42 + MatchCount, bVerbose); + RecordResult(Standings[Left], Standings[Right], Result); + println("战报:{},{} 回合,剩余 HP = {} / {}", + GetWinnerLabel(Result), Result.RoundCount, Result.LeftHealth, Result.RightHealth); + } + } + PrintStandings(Standings); + println("TOURNAMENT matches={} leader={} points={}", MatchCount, Standings[0].Name, Standings[0].GetPoints()); + return 0; + } + + void RunBatch(uint32 Count) + { + // Suppress round logs; create fresh combatants and change the seed for every battle. + uint32 Wins = 0; + uint32 Losses = 0; + uint32 Draws = 0; + uint64 Checksum = 0; + for (uint32 Index = 0; Index < Count; ++Index) + { + FBattleResult@ Result = SimulateBattle(CreateCombatant(0), CreateCombatant(1), 42 + Index, false); + if (Result.WinnerIndex == 0) + { + ++Wins; + } + else if (Result.WinnerIndex == 1) + { + ++Losses; + } + else + { + ++Draws; + } + Checksum += uint64(Result.LeftHealth * 1000 + Result.RightHealth + Result.RoundCount); + } + println("BATCH count={} wins={} losses={} draws={} checksum={}", Count, Wins, Losses, Draws, Checksum); + } +} diff --git a/examples/arena/Arena/Math.vas b/examples/arena/Arena/Math.vas new file mode 100644 index 000000000..e7dfe6425 --- /dev/null +++ b/examples/arena/Arena/Math.vas @@ -0,0 +1,29 @@ +namespace Arena +{ + int32 Clamp(int32 Value, int32 Lower, int32 Upper) + { + return Value < Lower ? Lower : Value > Upper ? Upper : Value; + } + + // A seeded generator for reproducible simulation, not cryptography. + class FDeterministicRandom + { + FDeterministicRandom(uint32 Seed) + { + State = Seed; + } + + uint32 Next() + { + State = State * uint32(1664525) + uint32(1013904223); + return State; + } + + uint32 NextBelow(uint32 Upper) + { + return Upper == 0 ? 0 : Next() % Upper; + } + + private uint32 State; + } +} diff --git a/examples/arena/Arena/Report.vas b/examples/arena/Arena/Report.vas new file mode 100644 index 000000000..bef894cb9 --- /dev/null +++ b/examples/arena/Arena/Report.vas @@ -0,0 +1,84 @@ +import Battle; + +namespace Arena +{ + class FStanding + { + string Name; + int32 Wins = 0; + int32 Draws = 0; + int32 Losses = 0; + int32 DamageDealt = 0; + int32 HealingDone = 0; + + FStanding(const string&in Label) + { + Name = Label; + } + int32 GetPoints() const + { + return Wins * 3 + Draws; + } + } + + void RecordResult(FStanding@ Left, FStanding@ Right, FBattleResult@ Result) + { + Left.DamageDealt += Result.LeftDamageDealt; + Right.DamageDealt += Result.RightDamageDealt; + Left.HealingDone += Result.LeftHealingDone; + Right.HealingDone += Result.RightHealingDone; + if (Result.WinnerIndex == 0) + { + ++Left.Wins; + ++Right.Losses; + } + else if (Result.WinnerIndex == 1) + { + ++Right.Wins; + ++Left.Losses; + } + else + { + ++Left.Draws; + ++Right.Draws; + } + } + + bool ShouldRankBefore(FStanding@ Left, FStanding@ Right) + { + if (Left.GetPoints() != Right.GetPoints()) + { + return Left.GetPoints() > Right.GetPoints(); + } + if (Left.DamageDealt != Right.DamageDealt) + { + return Left.DamageDealt > Right.DamageDealt; + } + return Left.Name < Right.Name; // Keep tied rankings deterministic. + } + + void PrintStandings(array&inout Standings) + { + // Insertion sort suits this small table; move handles instead of copying statistics. + for (uint32 Index = 1; Index < Standings.length(); ++Index) + { + FStanding@ Current = Standings[Index]; + uint32 InsertionIndex = Index; + while (InsertionIndex > 0 && ShouldRankBefore(Current, Standings[InsertionIndex - 1])) + { + @Standings[InsertionIndex] = Standings[InsertionIndex - 1]; + --InsertionIndex; + } + @Standings[InsertionIndex] = Current; + } + println(); + println("[排行榜:胜 3 分 / 平 1 分 / 负 0 分]"); + println("{:<8} {:>4} {:>4} {:>4} {:>4} {:>6} {:>6}", "角色", "积分", "胜", "平", "负", "伤害", "治疗"); + for (uint32 Index = 0; Index < Standings.length(); ++Index) + { + FStanding@ Row = Standings[Index]; + println("{:<8} {:>4d} {:>4d} {:>4d} {:>4d} {:>6d} {:>6d}", + Row.Name, Row.GetPoints(), Row.Wins, Row.Draws, Row.Losses, Row.DamageDealt, Row.HealingDone); + } + } +} diff --git a/examples/arena/Arena/Skills.vas b/examples/arena/Arena/Skills.vas new file mode 100644 index 000000000..ab1031c58 --- /dev/null +++ b/examples/arena/Arena/Skills.vas @@ -0,0 +1,52 @@ +import Combatant; + +namespace Arena +{ + interface ICombatSkill + { + string GetLabel() const; + int32 Execute(FCombatant@ Actor, FCombatant@ Target, FDeterministicRandom@ Random); + } + + // Invoke implementations through ICombatSkill@ to demonstrate dynamic dispatch. + class FAttackSkill : ICombatSkill + { + string GetLabel() const + { + return "攻击"; + } + + int32 Execute(FCombatant@ Actor, FCombatant@ Target, FDeterministicRandom@ Random) + { + if (Actor is null || Target is null || Random is null) + { + return 0; + } + if (!Actor.IsAlive() || !Target.IsAlive()) + { + return 0; + } + int32 Amount = Actor.Attack; + if (Random.NextBelow(100) < VAS_ARENA_CRIT_PERCENT) + { + Amount = VAS_ARENA_CRITICAL_DAMAGE(Amount); + } + int32 Actual = Target.ApplyDamage(Clamp(Amount - Target.Armor, 0, Target.Health)); + Actor.DamageDealt += Actual; + return Actual; + } + } + + class FHealSkill : ICombatSkill + { + string GetLabel() const + { + return "治疗"; + } + + int32 Execute(FCombatant@ Actor, FCombatant@ Target, FDeterministicRandom@ Random) + { + return Actor is null ? 0 : Actor.RestoreHealth(18); + } + } +} diff --git a/examples/arena/Measure-Arena.ps1 b/examples/arena/Measure-Arena.ps1 new file mode 100644 index 000000000..6e8e5018a --- /dev/null +++ b/examples/arena/Measure-Arena.ps1 @@ -0,0 +1,54 @@ +param( + [string]$Runner = (Join-Path $PSScriptRoot '../../out/build/windows-msvc-v145-cxx23/Release/vasrun.exe'), + [string]$Entry = (Join-Path $PSScriptRoot 'main.vas'), + [int[]]$BattleCounts = @(2000, 20000), + [ValidateRange(3, 15)] + [int]$Samples = 3 +) + +$ErrorActionPreference = 'Stop' +$Runner = (Resolve-Path -LiteralPath $Runner).Path +$Entry = (Resolve-Path -LiteralPath $Entry).Path + +foreach ($BattleCount in $BattleCounts) +{ + if ($BattleCount -lt 1 -or $BattleCount -gt 100000) + { + throw 'BattleCounts must be within 1..100000.' + } + + $ExpectedOutput = (& $Runner $Entry --batch $BattleCount | Out-String).Trim() + if ($LASTEXITCODE -ne 0) + { + throw "Arena warm-up failed: $ExpectedOutput" + } + + $Timings = @() + for ($Sample = 0; $Sample -lt $Samples; ++$Sample) + { + $Stopwatch = [System.Diagnostics.Stopwatch]::StartNew() + $Output = (& $Runner $Entry --batch $BattleCount | Out-String).Trim() + $Stopwatch.Stop() + if ($LASTEXITCODE -ne 0 -or $Output -cne $ExpectedOutput) + { + throw "Arena result changed during measurement: $Output" + } + $Timings += $Stopwatch.Elapsed.TotalMilliseconds + } + + $SortedTimings = @($Timings | Sort-Object) + $Middle = [int][Math]::Floor($Samples / 2) + $Median = $SortedTimings[$Middle] + if ($Samples % 2 -eq 0) + { + $Median = ($SortedTimings[$Middle - 1] + $Median) / 2 + } + [PSCustomObject]@{ + BattleCount = $BattleCount + Samples = $Samples + MedianMilliseconds = [Math]::Round($Median, 3) + MinMilliseconds = [Math]::Round($SortedTimings[0], 3) + MaxMilliseconds = [Math]::Round($SortedTimings[-1], 3) + Summary = $ExpectedOutput + } +} diff --git a/examples/arena/README.md b/examples/arena/README.md new file mode 100644 index 000000000..623ec04f1 --- /dev/null +++ b/examples/arena/README.md @@ -0,0 +1,82 @@ +# 模块化竞技场示例 + +从 `main.vas` 开始阅读。这是一套可运行的回合制模拟程序:剑士、守卫和医师两两比赛,攻击会受护甲和暴击影响,医师在低血量时治疗;奇偶回合交换先手,达到回合上限后判平局。每场使用新角色,比赛结果进入积分榜。 + +## 文件与阅读顺序 + +| 文件 | 内容 | +| --- | --- | +| `main.vas` | 宏配置、三种依赖写法、命令行参数与返回码 | +| `Arena/Config.vas` | 默认配置、对象宏、函数宏和编译期配置检查 | +| `Arena/Math.vas` | `FDeterministicRandom` 与数值边界函数 | +| `Arena/Combatant.vas` | `ECombatRole`、`FCombatant`、工厂与生命值规则 | +| `Arena/Skills.vas` | `ICombatSkill` 接口、攻击与治疗实现、句柄和多态 | +| `Arena/Battle.vas` | 技能选择、回合循环、先手切换与战斗结果 | +| `Arena/Report.vas` | 结果归档、同分排序、格式化排行榜 | +| `Arena/Checks.vas` | 23 项自检,失败会使程序返回非零 | +| `Arena/Demo.vas` | 三场循环赛与无逐回合输出的批量模拟 | + +`Demo → Report → Battle → Combatant → Config/Math`;`Battle → Skills → Combatant`。这些依赖包含菱形引用。入口另外混用 import、引号 include 和尖括号 include:原生加载报告应包含恰好 9 个不同源码文件,不会重复编译。 + +## Epic 风格在 VAS 中的约定 + +参照 [Epic Coding Standard](https://dev.epicgames.com/documentation/en-us/unreal-engine/epic-cplusplus-coding-standard-for-unreal-engine):类型、函数、字段和局部变量采用 PascalCase,普通类 `F` 前缀,接口 `I` 前缀,枚举 `E` 前缀,布尔变量 `b` 前缀;使用 Allman 大括号、Tab 缩进、显式 `int32/uint32`、一行一个变量声明,公共操作放在私有实现之前。布尔函数用 `IsAlive`、`ShouldRankBefore`、`AreSelfTestsPassing` 表达真/假含义。 + +这里使用 VAS 内建的 `string`、`array`、`@` 句柄和注册的宿主函数;`main()` 是运行器约定。宏使用项目对应的 `VAS_` 前缀,例如 `VAS_ARENA_MAX_ROUNDS`。脚本类使用 `F` 前缀,不引入 Unreal 的反射声明;代码注释使用英文,学习说明和终端输出保留中文。 + +## 运行 + +先按根目录 CMake preset 构建工具,再在仓库根目录执行: + +```powershell +# 完整战斗过程、自检和榜单 +& .\out\build\windows-msvc-v145-cxx23\Release\vasrun.exe .\examples\arena\main.vas + +# 简洁战报和榜单 +& .\out\build\windows-msvc-v145-cxx23\Release\vasrun.exe .\examples\arena\main.vas --quiet + +# 单独自检 +& .\out\build\windows-msvc-v145-cxx23\Release\vasrun.exe .\examples\arena\main.vas --self-test + +# 批量模拟,不输出逐回合日志 +& .\out\build\windows-msvc-v145-cxx23\Release\vasrun.exe .\examples\arena\main.vas --batch 2000 + +# 生成字节码 +& .\out\build\windows-msvc-v145-cxx23\Release\vasbuild.exe .\sdk\samples\asbuild\bin\config.txt .\examples\arena\main.vas .\out\build\windows-msvc-v145-cxx23\arena-demo.vasbc +``` + +自检输出 `SELF_TEST passed=23 failed=0`。默认循环赛的榜首是守卫,积分 4;完整简洁输出见 `expected-quiet.txt`。固定 2,000 场输出: + +```text +BATCH count=2000 wins=654 losses=1346 draws=0 checksum=9933226 +``` + +参数不合法时返回 2,自检失败返回 1,成功返回 0。批量场数限制为 1..100000。随机数用于教学和可重放模拟,不用于安全场景;按取模生成范围随机数存在微小分布偏差。循环赛固定种子和配对顺序,用于验证行为,不代表游戏平衡结论。 + +## 配置与扩展 + +在入口的 import 之前定义 `VAS_ARENA_VERBOSE 0` 可在编译期去掉逐回合日志;`--quiet` 是运行时关闭日志。两者都不改变随机数消耗和战斗结果。修改 `VAS_ARENA_MAX_ROUNDS` 可控制回合上限,允许 1..100;无效配置会触发 `#error`。依赖中的宏全部自动可见,入口能够使用传递导出的版本、暴击率和暴击函数宏。 + +可以从以下三个方向练习:增加 `ICombatSkill` 的新实现;在 `CreateCombatant` 中增加角色并扩展配对名单;增加榜单统计并补充自检。函数宏只对普通值表达式演示,不将带副作用的复杂调用放进宏参数。 + +## 性能与回归 + +技能对象在每场比赛创建一次,在回合循环内复用。排行榜只移动对象句柄,并预留三个条目的容量;它面向小名单采用插入排序。角色、随机数、技能和结果对象仍会产生每场创建成本;这里没有宣称零分配,也没有为了三个条目引入对象池。 + +可重复执行性能测量: + +```powershell +.\examples\arena\Measure-Arena.ps1 +``` + +脚本先预热,每组默认测量三次并输出中位数及最小/最大值,同时核对输出是否一致。测量包含进程启动、源码读取、预处理、编译和执行,不能当作纯 VM 战斗时间。只有一次最终汇总输出,不含逐回合日志的终端开销。 + +本机 Windows Release 的一轮端到端测量:2,000 场中位数约 37.8 ms,20,000 场约 215.3 ms;逐次结果与校验和一致。日志保存在本地 `out/verification/arena/performance.json`。这些数据用于观察这套例子的规模变化,不作为其他机器的性能保证。 + +```powershell +ctest --preset windows-msvc-v145-cxx23-release -R vas_arena_example --output-on-failure +``` + +集成回归验证四套宿主配置都能编译同一源码,运行器实际执行、自检、榜单快照、批量校验和、CLI 错误返回、9 文件依赖闭包、日志宏关闭后结果一致以及无效宏配置的编译失败。测试也覆盖数组/字符串的 `length()` API,避免宿主配置和运行器再次不一致。 + +本地部署工程的 `src/main.vas` 已切换到本例,旧的 print/println 基础示例保留为 `src/basics.vas`,两个编译单元都可通过原生 Build Project 构建。 diff --git a/examples/arena/expected-quiet.txt b/examples/arena/expected-quiet.txt new file mode 100644 index 000000000..780366230 --- /dev/null +++ b/examples/arena/expected-quiet.txt @@ -0,0 +1,20 @@ +=== VAS 模块化竞技场 v1.0 === +配置:最多 12 回合,暴击率 25%,日志宏 = 1 +预览:暴击伤害 = 36 | 固定种子保证战斗可重放 +SELF_TEST passed=23 failed=0 + +[比赛 1] 剑士 vs 守卫 +战报:守卫,6 回合,剩余 HP = 0 / 50 + +[比赛 2] 剑士 vs 医师 +战报:剑士,7 回合,剩余 HP = 70 / 0 + +[比赛 3] 守卫 vs 医师 +战报:平局,12 回合,剩余 HP = 50 / 44 + +[排行榜:胜 3 分 / 平 1 分 / 负 0 分] +角色 积分 胜 平 负 伤害 治疗 +守卫 4 1 1 0 236 0 +剑士 3 1 0 1 214 0 +医师 1 0 1 1 80 180 +TOURNAMENT matches=3 leader=守卫 points=4 diff --git a/examples/arena/main.vas b/examples/arena/main.vas new file mode 100644 index 000000000..3e3e9a3db --- /dev/null +++ b/examples/arena/main.vas @@ -0,0 +1,36 @@ +// Configure macros before import; dependencies share this environment. +#ifndef VAS_ARENA_VERBOSE +#define VAS_ARENA_VERBOSE 1 +#endif +import Arena.Demo; +#include "Arena/Demo.vas" +#include + +int32 main() +{ + array@ Args = getCommandLineArgs(); + if (Args.length() == 0) + { + return Arena::RunDemo(true); + } + if (Args.length() == 1 && Args[0] == "--quiet") + { + return Arena::RunDemo(false); + } + if (Args.length() == 1 && Args[0] == "--self-test") + { + return Arena::AreSelfTestsPassing() ? 0 : 1; + } + if (Args.length() == 2 && Args[0] == "--batch") + { + uint32 ParsedCharacters = 0; + uint64 Count = parseUInt(Args[1], 10, ParsedCharacters); + if (ParsedCharacters == Args[1].length() && Count >= 1 && Count <= 100000) + { + Arena::RunBatch(uint32(Count)); + return 0; + } + } + println("用法:vasrun main.vas [--quiet | --self-test | --batch 1..100000]"); + return 2; +} diff --git a/examples/modules/README.md b/examples/modules/README.md new file mode 100644 index 000000000..712efec77 --- /dev/null +++ b/examples/modules/README.md @@ -0,0 +1,30 @@ +# import、include 和宏示例 + +`main.vas` 同时演示 `print`、`println`、字符串拼接、格式化,以及以下三种依赖写法: + +```cpp +import math; +#include "math.vas" +#include +``` + +它们解析到同一个文件时,只加载、预处理和编译一次。`math.vas` 中的函数和全部宏自动可见;其依赖 `demo_constants.vas` 的宏也自动传递。入口预定义的 `DEMO_BASE` 会影响导入文件中的条件编译。 + +在仓库根目录运行已构建的 Windows Release 工具: + +```powershell +& .\out\build\windows-msvc-v145-cxx23\Release\vasrun.exe .\examples\modules\main.vas +& .\out\build\windows-msvc-v145-cxx23\Release\vasbuild.exe .\sdk\samples\asbuild\bin\config.txt .\examples\modules\main.vas .\out\build\windows-msvc-v145-cxx23\modules-demo.vasbc +``` + +模块部分的输出为: + +```text +[模块导入 / 宏自动导出] +来自 demo_constants:math v1 +函数宏:72 + 10 = 82 +传递导出的宏:DEMO_OFFSET = 110 +导入后的宏也能用于条件编译。 +``` + +例子中注释保留了格式参数缺失、类型不匹配和宏冲突的反例;单独取消对应注释,可以看到编译诊断。更多解析规则、宏语义和性能测量见 [模块与宏说明](../../docs/modules-and-macros.md)。 diff --git a/examples/modules/demo_constants.vas b/examples/modules/demo_constants.vas new file mode 100644 index 000000000..1ecbd0da4 --- /dev/null +++ b/examples/modules/demo_constants.vas @@ -0,0 +1,6 @@ +// 导入方预先定义的宏会影响这里;所有宏自动对导入方可见。 +#ifndef DEMO_BASE +#define DEMO_BASE 10 +#endif +#define DEMO_OFFSET (DEMO_BASE + 100) +#define MODULE_SOURCE "demo_constants" diff --git a/examples/modules/main.vas b/examples/modules/main.vas new file mode 100644 index 000000000..daa217946 --- /dev/null +++ b/examples/modules/main.vas @@ -0,0 +1,72 @@ +// 三种写法共用加载与去重:math 只编译一次。 +#define DEMO_BASE 10 +import math; +#include "math.vas" +#include + +void main() +{ + int result = add(20, 22); + int result2 = add(50, 22); + + println("=== VAS print / println 示例 ==="); + println(); + + // 1. println 自动换行,可以直接输出数字和布尔值。 + println("[直接输出]"); + println(72); + println(result2); + println(1.25); + println(true); + println(); + + // 2. print 不自动换行,连续调用的内容会接在同一行。 + print("[连续输出] result2 = "); + print(result2); + print(",这一句仍在同一行。"); + println(); + println(); + + // 3. 这里的整数变量用拼接和占位符写法,输出相同。 + // 格式化写法省去拼接中间串,较长内容优先用这一种。 + println("[字符串拼接 / 占位符]"); + println("ABC + " + result2 + " ASDA"); + println("ABC + {} ASDA", result2); + println("20 + 22 = {},50 + 22 = {}", result, result2); + + // print 也支持这两种写法,只是不追加换行。 + print("ABC + " + result2 + " ASDA"); + print(" | ABC + {} ASDA", result2); + println(); + println(); + + // 4. 格式规格:补零、十六进制、保留小数位、字符串对齐。 + println("[格式化]"); + println("十进制补零:{:04d},十六进制:{:04X}", result2, result2); + println("保留两位小数:{:.2f}", 3.14159); + println("右对齐:|{:>8}|", "VAS"); + println(); + + // 5. 格式串中的字面花括号需要转义,参数中的花括号不需要。 + println("[花括号]"); + println("字面花括号:{{value}}"); + println("参数内容:{}", "{value}"); + + // {} 必须传对应参数;不能省略 result2,也不会自动捕获变量。 + // 字面量格式错误会在编译期被拒绝,下面两句取消注释即可查看诊断。 + // println("result = {}"); + // println("result = {:d}", "text"); + println(); + println("[模块导入 / 宏自动导出]"); + println("来自 {}:{} v{}", MODULE_SOURCE, MATH_LABEL, MATH_VERSION); + println("函数宏:{} + {} = {}", result2, DEMO_BASE, MATH_ADD(result2, DEMO_BASE)); + println("传递导出的宏:DEMO_OFFSET = {}", DEMO_OFFSET); +#if defined(MATH_VERSION) && MATH_VERSION >= 1 + println("导入后的宏也能用于条件编译。"); +#else +#error math 模块的宏未导出 +#endif + // 同名同定义允许重复;不同定义会报错,并给出原定义位置。 + // #define MATH_VERSION 2 + println("=== 示例结束,result2 = {} ===", result2); +} diff --git a/examples/modules/math.vas b/examples/modules/math.vas new file mode 100644 index 000000000..aa18de757 --- /dev/null +++ b/examples/modules/math.vas @@ -0,0 +1,10 @@ +// math 的依赖宏也会自动传递给导入 math 的文件。 +import demo_constants; +#define MATH_VERSION 1 +#define MATH_LABEL "math" +#define MATH_ADD(left, right) ((left) + (right)) + +int add(int left, int right) +{ + return left + right; +} diff --git a/sdk/add_on/scripthelper/scripthelper.cpp b/sdk/add_on/scripthelper/scripthelper.cpp index b2af27a72..cb17f3e16 100644 --- a/sdk/add_on/scripthelper/scripthelper.cpp +++ b/sdk/add_on/scripthelper/scripthelper.cpp @@ -1,5 +1,6 @@ #include #include "scripthelper.h" +#include #include #include #include @@ -503,7 +504,7 @@ int WriteConfigToStream(asIScriptEngine *engine, ostream &strm) strm << "access " << hex << (unsigned int)(accessMask) << dec << "\n"; currAccessMask = accessMask; } - strm << "func \"" << Escape::Quotes(func->GetDeclaration()).c_str() << (func->IsProperty() ? " property" : "") << "\"\n"; + strm << (func->GetFormatStringValidator() ? "formatfunc \"" : "func \"") << Escape::Quotes(func->GetDeclaration()).c_str() << (func->IsProperty() ? " property" : "") << "\"\n"; } // Write global properties @@ -560,9 +561,12 @@ int WriteConfigToStream(asIScriptEngine *engine, ostream &strm) return 0; } -int ConfigEngineFromStream(asIScriptEngine *engine, istream &strm, const char *configFile, asIStringFactory *stringFactory) +int ConfigEngineFromStream(asIScriptEngine *engine, istream &strm, const char *configFile, asIStringFactory *stringFactory, + asFORMATSTRINGVALIDATOR_t formatValidator, void *formatValidatorParam) { int r; + std::vector checkedFunctions; + std::vector checkedLines; // Some helper functions for parsing the configuration struct in @@ -796,7 +800,7 @@ int ConfigEngineFromStream(asIScriptEngine *engine, istream &strm, const char *c return -1; } } - else if( token == "func" ) + else if( token == "func" || token == "formatfunc" ) { string decl; in::GetToken(engine, decl, config, pos); @@ -809,6 +813,17 @@ int ConfigEngineFromStream(asIScriptEngine *engine, istream &strm, const char *c engine->WriteMessage(configFile, in::GetLineNumber(config, pos), 0, asMSGTYPE_ERROR, "Failed to register global function"); return -1; } + if (token == "formatfunc" && !formatValidator) + { + engine->WriteMessage(configFile, in::GetLineNumber(config, pos), 0, asMSGTYPE_ERROR, + "formatfunc requires a compatible format string validator"); + return -1; + } + if (token == "formatfunc") + { + checkedFunctions.push_back(r); + checkedLines.push_back(in::GetLineNumber(config, pos)); + } } else if( token == "prop" ) { @@ -916,6 +931,13 @@ int ConfigEngineFromStream(asIScriptEngine *engine, istream &strm, const char *c } } + // The string factory may appear after global functions in exported configs. + for (size_t i = 0; i < checkedFunctions.size(); ++i) + if (engine->GetFunctionById(checkedFunctions[i])->SetFormatStringValidator(formatValidator, formatValidatorParam) < 0) + { + engine->WriteMessage(configFile, checkedLines[i], 0, asMSGTYPE_ERROR, "Invalid formatfunc signature"); + return -1; + } return 0; } diff --git a/sdk/add_on/scripthelper/scripthelper.h b/sdk/add_on/scripthelper/scripthelper.h index eb514ecea..b768fb18f 100644 --- a/sdk/add_on/scripthelper/scripthelper.h +++ b/sdk/add_on/scripthelper/scripthelper.h @@ -38,7 +38,8 @@ int WriteConfigToStream(asIScriptEngine *engine, std::ostream &strm); // Loads an interface from a text stream and configures the engine with it. This will not // set the correct function pointers, so it is not possible to use this engine to execute // scripts, but it can be used to compile scripts and save the byte code. -int ConfigEngineFromStream(asIScriptEngine *engine, std::istream &strm, const char *nameOfStream = "config", asIStringFactory *stringFactory = 0); +int ConfigEngineFromStream(asIScriptEngine *engine, std::istream &strm, const char *nameOfStream = "config", asIStringFactory *stringFactory = 0, + asFORMATSTRINGVALIDATOR_t formatValidator = 0, void *formatValidatorParam = 0); // Format the details of the script exception into a human readable text std::string GetExceptionInfo(asIScriptContext *ctx, bool showStack = false); diff --git a/sdk/add_on/scriptstdstring/scriptstdstring.cpp b/sdk/add_on/scriptstdstring/scriptstdstring.cpp index 0d18f1634..3a6609c4a 100644 --- a/sdk/add_on/scriptstdstring/scriptstdstring.cpp +++ b/sdk/add_on/scriptstdstring/scriptstdstring.cpp @@ -1,5 +1,6 @@ #include "scriptstdstring.h" #include // assert() +#include #include // std::stringstream #include // strstr() #include // snprintf() @@ -190,155 +191,122 @@ static bool StringIsEmpty(const string &str) } #if AS_NO_IMPL_OPS_WITH_STRING_AND_PRIMITIVE == 0 -static string &AssignUInt64ToString(asQWORD i, string &dest) +// A stream backed by stack storage keeps floating-point/locale semantics while +// avoiding ostringstream's growing buffer and the temporary stream.str() copy. +class NumericBuffer : public std::streambuf { - ostringstream stream; - stream << i; - dest = stream.str(); - return dest; -} - -static string &AddAssignUInt64ToString(asQWORD i, string &dest) -{ - ostringstream stream; - stream << i; - dest += stream.str(); - return dest; -} - -static string AddStringUInt64(const string &str, asQWORD i) -{ - ostringstream stream; - stream << i; - return str + stream.str(); -} - -static string AddInt64String(asINT64 i, const string &str) -{ - ostringstream stream; - stream << i; - return stream.str() + str; -} - -static string &AssignInt64ToString(asINT64 i, string &dest) -{ - ostringstream stream; - stream << i; - dest = stream.str(); - return dest; -} - -static string &AddAssignInt64ToString(asINT64 i, string &dest) -{ - ostringstream stream; - stream << i; - dest += stream.str(); - return dest; -} - -static string AddStringInt64(const string &str, asINT64 i) -{ - ostringstream stream; - stream << i; - return str + stream.str(); -} - -static string AddUInt64String(asQWORD i, const string &str) -{ - ostringstream stream; - stream << i; - return stream.str() + str; -} - -static string &AssignDoubleToString(double f, string &dest) -{ - ostringstream stream; - stream << f; - dest = stream.str(); - return dest; -} +public: + char storage[128]; + NumericBuffer() { setp(storage, storage + sizeof(storage)); } + size_t length() const { return size_t(pptr() - pbase()); } +}; -static string &AddAssignDoubleToString(double f, string &dest) +class NumericText { - ostringstream stream; - stream << f; - dest += stream.str(); - return dest; -} + NumericBuffer buffer; + string fallback; + const char *text; + size_t size; -static string &AssignFloatToString(float f, string &dest) -{ - ostringstream stream; - stream << f; - dest = stream.str(); - return dest; -} + template void FromStream(T value) + { + std::ostream stream(&buffer); + stream << value; + if (stream) + { + text = buffer.storage; + size = buffer.length(); + } + else + { + // A host's custom num_put facet may emit arbitrarily long text. + ostringstream full; + full << value; + fallback = full.str(); + text = fallback.data(); + size = fallback.size(); + } + } -static string &AddAssignFloatToString(float f, string &dest) -{ - ostringstream stream; - stream << f; - dest += stream.str(); - return dest; -} + void FromUnsigned(asQWORD value, bool negative) + { + char *end = buffer.storage + sizeof(buffer.storage), *begin = end; + do { *--begin = char('0' + value % 10); value /= 10; } while (value); + if (negative) *--begin = '-'; + text = begin; + size = size_t(end - begin); + } +public: + explicit NumericText(asQWORD value) + { + if (std::locale() == std::locale::classic()) FromUnsigned(value, false); + else FromStream(value); + } + explicit NumericText(asINT64 value) + { + if (std::locale() == std::locale::classic()) + FromUnsigned(value < 0 ? asQWORD(0) - asQWORD(value) : asQWORD(value), value < 0); + else FromStream(value); + } + explicit NumericText(float value) { FromStream(value); } + explicit NumericText(double value) { FromStream(value); } + explicit NumericText(bool value) : text(value ? "true" : "false"), size(value ? 4 : 5) {} + const char *data() const { return text; } + size_t length() const { return size; } +}; -static string &AssignBoolToString(bool b, string &dest) +template static string &AssignNumber(T value, string &dest) { - ostringstream stream; - stream << (b ? "true" : "false"); - dest = stream.str(); + NumericText text(value); + dest.assign(text.data(), text.length()); return dest; } -static string &AddAssignBoolToString(bool b, string &dest) +template static string &AppendNumber(T value, string &dest) { - ostringstream stream; - stream << (b ? "true" : "false"); - dest += stream.str(); + NumericText text(value); + dest.append(text.data(), text.length()); return dest; } -static string AddStringDouble(const string &str, double f) +template static string AddNumber(const string &str, T value, bool numberFirst) { - ostringstream stream; - stream << f; - return str + stream.str(); -} - -static string AddDoubleString(double f, const string &str) -{ - ostringstream stream; - stream << f; - return stream.str() + str; -} - -static string AddStringFloat(const string &str, float f) -{ - ostringstream stream; - stream << f; - return str + stream.str(); -} - -static string AddFloatString(float f, const string &str) -{ - ostringstream stream; - stream << f; - return stream.str() + str; -} - -static string AddStringBool(const string &str, bool b) -{ - ostringstream stream; - stream << (b ? "true" : "false"); - return str + stream.str(); -} + NumericText text(value); + string result; + // Check the total length before addition to avoid unsigned wraparound. + if (text.length() > result.max_size() - str.size()) throw std::length_error("string too long"); + result.reserve(str.size() + text.length()); + if (numberFirst) result.append(text.data(), text.length()); + result.append(str); + if (!numberFirst) result.append(text.data(), text.length()); + return result; +} + +static string &AssignUInt64ToString(asQWORD value, string &dest) { return AssignNumber(value, dest); } +static string &AddAssignUInt64ToString(asQWORD value, string &dest) { return AppendNumber(value, dest); } +static string AddStringUInt64(const string &str, asQWORD value) { return AddNumber(str, value, false); } +static string AddUInt64String(asQWORD value, const string &str) { return AddNumber(str, value, true); } + +static string &AssignInt64ToString(asINT64 value, string &dest) { return AssignNumber(value, dest); } +static string &AddAssignInt64ToString(asINT64 value, string &dest) { return AppendNumber(value, dest); } +static string AddStringInt64(const string &str, asINT64 value) { return AddNumber(str, value, false); } +static string AddInt64String(asINT64 value, const string &str) { return AddNumber(str, value, true); } + +static string &AssignDoubleToString(double value, string &dest) { return AssignNumber(value, dest); } +static string &AddAssignDoubleToString(double value, string &dest) { return AppendNumber(value, dest); } +static string AddStringDouble(const string &str, double value) { return AddNumber(str, value, false); } +static string AddDoubleString(double value, const string &str) { return AddNumber(str, value, true); } + +static string &AssignFloatToString(float value, string &dest) { return AssignNumber(value, dest); } +static string &AddAssignFloatToString(float value, string &dest) { return AppendNumber(value, dest); } +static string AddStringFloat(const string &str, float value) { return AddNumber(str, value, false); } +static string AddFloatString(float value, const string &str) { return AddNumber(str, value, true); } + +static string &AssignBoolToString(bool value, string &dest) { return AssignNumber(value, dest); } +static string &AddAssignBoolToString(bool value, string &dest) { return AppendNumber(value, dest); } +static string AddStringBool(const string &str, bool value) { return AddNumber(str, value, false); } +static string AddBoolString(bool value, const string &str) { return AddNumber(str, value, true); } -static string AddBoolString(bool b, const string &str) -{ - ostringstream stream; - stream << (b ? "true" : "false"); - return stream.str() + str; -} #endif static char *StringCharAt(unsigned int i, string &str) diff --git a/sdk/angelscript/include/angelscript.h b/sdk/angelscript/include/angelscript.h index c76fd185e..b2055e7e8 100644 --- a/sdk/angelscript/include/angelscript.h +++ b/sdk/angelscript/include/angelscript.h @@ -409,6 +409,11 @@ enum asEFuncType typedef void (*asFUNCTION_t)(); typedef void (*asGENFUNC_t)(asIScriptGeneric *); +// Host opt-in build-time validation. Null text denotes a non-literal format. +// Return a negative value and a NUL-terminated diagnostic to reject the call. +typedef int (*asFORMATSTRINGVALIDATOR_t)(const char *text, asUINT length, + const int *argumentTypes, asUINT argumentCount, + char *error, asUINT errorCapacity, void *userParam); typedef void *(*asALLOCFUNC_t)(size_t); typedef void (*asFREEFUNC_t)(void *); typedef void (*asCLEANENGINEFUNC_t)(asIScriptEngine *); @@ -1182,6 +1187,8 @@ class asIScriptFunction virtual bool IsExplicit() const = 0; virtual bool IsProperty() const = 0; virtual bool IsVariadic() const = 0; + virtual int SetFormatStringValidator(asFORMATSTRINGVALIDATOR_t validator, void *userParam = 0) = 0; + virtual asFORMATSTRINGVALIDATOR_t GetFormatStringValidator() const = 0; virtual asUINT GetParamCount() const = 0; virtual int GetParam(asUINT index, int *typeId, asDWORD *flags = 0, const char **name = 0, const char **defaultArg = 0) const = 0; virtual int GetReturnTypeId(asDWORD *flags = 0) const = 0; diff --git a/sdk/angelscript/source/as_compiler.cpp b/sdk/angelscript/source/as_compiler.cpp index 246fc8800..cf4e13e99 100644 --- a/sdk/angelscript/source/as_compiler.cpp +++ b/sdk/angelscript/source/as_compiler.cpp @@ -2589,7 +2589,8 @@ int asCCompiler::CompileDefaultAndNamedArgs(asCScriptNode *node, asCArraybc.GetVarsUsed(reservedVariables); // Make space for all the new arguments - args.SetLength(func->parameterTypes.GetLength()); + // The variadic marker is not an actual argument (not even with named args). + args.SetLength(func->parameterTypes.GetLength() - (func->IsVariadic() ? 1 : 0)); for( asUINT c = explicitArgs; c < args.GetLength(); c++ ) args[c] = 0; @@ -2622,7 +2623,7 @@ int asCCompiler::CompileDefaultAndNamedArgs(asCScriptNode *node, asCArrayparameterTypes.GetLength() - 1; n >= explicitArgs; n-- ) + for( int n = (int)args.GetLength() - 1; n >= explicitArgs; n-- ) { if( args[n] != 0 ) continue; if (n >= (int)func->defaultArgs.GetLength()) { asASSERT(func->IsVariadic()); continue; } @@ -12161,6 +12162,7 @@ int asCCompiler::CompileExpressionValue(asCScriptNode *node, asCExprContext *ctx // Mark the string as literal constant so the compiler knows it is allowed // to treat it differently than an ordinary constant string variable ctx->type.isConstant = true; + ctx->type.constantString = strPtr; // Mark the reference to the string constant as safe, so the compiler can // avoid making unnecessary temporary copies when passing the reference to @@ -15789,6 +15791,33 @@ int asCCompiler::MakeFunctionCall(asCExprContext *ctx, int funcId, asCObjectType asCScriptFunction* descr = builder->GetFunctionDescription(funcId); + if (descr->formatStringValidator && args.GetLength()) + { + asCArray types; + for (asUINT i = 1; i < args.GetLength(); ++i) + types.PushLast(engine->GetTypeIdFromDataType(args[i]->type.dataType)); + asCString literal; + const char *text = 0; + asUINT length = 0; + if (args[0]->type.constantString && engine->stringFactory && + engine->stringFactory->GetRawStringData(args[0]->type.constantString, 0, &length) >= 0) + { + literal.SetLength(length); + if (engine->stringFactory->GetRawStringData(args[0]->type.constantString, literal.AddressOf(), 0) < 0) + return -1; + text = literal.AddressOf(); + } + char diagnostic[512] = {0}; + if (descr->formatStringValidator(text, length, types.AddressOf(), types.GetLength(), + diagnostic, sizeof(diagnostic), descr->formatStringValidatorParam) < 0) + { + diagnostic[sizeof(diagnostic)-1] = 0; + asCString message = descr->name + ": " + (diagnostic[0] ? diagnostic : "invalid format call"); + Error(message, args[0]->exprNode ? args[0]->exprNode : node); + return -1; + } + } + // Store the expression node for error reporting if( ctx->exprNode == 0 ) ctx->exprNode = node; @@ -18189,6 +18218,7 @@ void asCCompiler::FilterConst(asCArray &funcs, bool removeConst) asCExprValue::asCExprValue() { + constantString = 0; isTemporary = false; stackOffset = 0; isConstant = false; @@ -18204,6 +18234,7 @@ asCExprValue::asCExprValue() void asCExprValue::Set(const asCDataType &dt) { dataType = dt; + constantString = 0; isTemporary = false; stackOffset = 0; isConstant = false; diff --git a/sdk/angelscript/source/as_compiler.h b/sdk/angelscript/source/as_compiler.h index 9169f508a..edafd5b67 100644 --- a/sdk/angelscript/source/as_compiler.h +++ b/sdk/angelscript/source/as_compiler.h @@ -93,6 +93,8 @@ struct asCExprValue bool IsNullConstant() const; bool IsVoid() const; + // Factory-owned literal; retained in this compiler's usedStringConstants. + const void *constantString; asCDataType dataType; bool isLValue : 1; // Can this value be updated in assignment, or increment operators, etc bool isTemporary : 1; diff --git a/sdk/angelscript/source/as_scriptfunction.cpp b/sdk/angelscript/source/as_scriptfunction.cpp index 4b87f1083..5420025fb 100644 --- a/sdk/angelscript/source/as_scriptfunction.cpp +++ b/sdk/angelscript/source/as_scriptfunction.cpp @@ -346,6 +346,8 @@ int asCScriptFunction::ParseListPattern(asSListPatternNode *&target, const char asCScriptFunction::asCScriptFunction(asCScriptEngine *engine, asCModule *mod, asEFuncType _funcType) { funcType = _funcType; + formatStringValidator = 0; + formatStringValidatorParam = 0; if( funcType == asFUNC_DELEGATE ) { // Delegates behave like object instances, rather than script code @@ -1873,6 +1875,18 @@ bool asCScriptFunction::IsProperty() const } // interface +int asCScriptFunction::SetFormatStringValidator(asFORMATSTRINGVALIDATOR_t validator, void *userParam) +{ + // Host metadata is never serialized into script bytecode. + if (funcType != asFUNC_SYSTEM || !IsVariadic() || parameterTypes.GetLength() == 0 || + !engine->stringType.GetTypeInfo() || + parameterTypes[0].GetTypeInfo() != engine->stringType.GetTypeInfo()) + return asINVALID_ARG; + formatStringValidator = validator; + formatStringValidatorParam = userParam; + return asSUCCESS; +} + bool asCScriptFunction::IsVariadic() const { return traits.GetTrait(asTRAIT_VARIADIC); diff --git a/sdk/angelscript/source/as_scriptfunction.h b/sdk/angelscript/source/as_scriptfunction.h index 01045a352..6caff9868 100644 --- a/sdk/angelscript/source/as_scriptfunction.h +++ b/sdk/angelscript/source/as_scriptfunction.h @@ -186,6 +186,8 @@ class asCScriptFunction : public asIScriptFunction bool IsExplicit() const; bool IsProperty() const; bool IsVariadic() const; + int SetFormatStringValidator(asFORMATSTRINGVALIDATOR_t validator, void *userParam = 0); + asFORMATSTRINGVALIDATOR_t GetFormatStringValidator() const { return formatStringValidator; } asUINT GetParamCount() const; int GetParam(asUINT index, int *typeId, asDWORD *flags = 0, const char **name = 0, const char **defaultArg = 0) const; int GetReturnTypeId(asDWORD *flags = 0) const; @@ -318,6 +320,8 @@ class asCScriptFunction : public asIScriptFunction asCModule *module; asCArray userData; + asFORMATSTRINGVALIDATOR_t formatStringValidator; + void *formatStringValidatorParam; // Function signature asCString name; diff --git a/sdk/samples/asbuild/bin/config.txt b/sdk/samples/asbuild/bin/config.txt index bce3a74af..49761ab26 100644 --- a/sdk/samples/asbuild/bin/config.txt +++ b/sdk/samples/asbuild/bin/config.txt @@ -82,8 +82,6 @@ objmthd "array" "int findByRef(uint, const T&in) const" objmthd "array" "bool opEquals(const array&in) const" objmthd "array" "bool isEmpty() const" objmthd "array" "void sort(array::less&in, uint = 0, uint = uint ( - 1 ))" -objmthd "array" "uint get_length() const" -objmthd "array" "void set_length(uint)" // Type members objbeh "string" 2 "void string()" @@ -96,8 +94,6 @@ objmthd "string" "int opCmp(const string&in) const" objmthd "string" "string opAdd(const string&in) const" objmthd "string" "uint length() const" objmthd "string" "void resize(uint)" -objmthd "string" "uint get_length() const" -objmthd "string" "void set_length(uint)" objmthd "string" "bool isEmpty() const" objmthd "string" "uint8& opIndex(uint)" objmthd "string" "const uint8& opIndex(uint) const" @@ -214,7 +210,31 @@ func "int64 parseInt(const string&in, uint = 10, uint&out = 0)" func "uint64 parseUInt(const string&in, uint = 10, uint&out = 0)" func "double parseFloat(const string&in, uint&out = 0)" func "string join(const array&in, const string&in)" -func "void print(const string&in)" +formatfunc "void print(const string&in format, const ?&in ...)" +func "void print(int8)" +func "void print(uint8)" +func "void print(int16)" +func "void print(uint16)" +func "void print(int)" +func "void print(uint)" +func "void print(int64)" +func "void print(uint64)" +func "void print(float)" +func "void print(double)" +func "void print(bool)" +formatfunc "void println(const string&in format, const ?&in ...)" +func "void println()" +func "void println(int8)" +func "void println(uint8)" +func "void println(int16)" +func "void println(uint16)" +func "void println(int)" +func "void println(uint)" +func "void println(int64)" +func "void println(uint64)" +func "void println(float)" +func "void println(double)" +func "void println(bool)" func "string getInput()" func "array@ getCommandLineArgs()" func "int exec(const string&in)" diff --git a/sdk/samples/asbuild/source/main.cpp b/sdk/samples/asbuild/source/main.cpp index f50e61a93..7777eea15 100644 --- a/sdk/samples/asbuild/source/main.cpp +++ b/sdk/samples/asbuild/source/main.cpp @@ -12,6 +12,7 @@ #include "../../common/vas_source_digest.h" #include "../../common/vas_build_report.h" #include "vas_project.h" +#include "../../common/vas_format.h" #if defined(_MSC_VER) #include #endif @@ -25,7 +26,6 @@ int SaveBytecode(asIScriptEngine *engine, const char *outputFile, bool reportMod const vas::Project *project, const vas::CompilationUnit *unit, const vector §ions); static bool IsVasScriptFile(const char *filename); static int ReportInvalidVasScriptExtension(asIScriptEngine *engine, const char *filename, const char *role); -static string ResolveIncludePath(const char *include, const char *from); static int VasIncludeCallback(const char *include, const char *from, CScriptBuilder *builder, void *userParam); void MessageCallback(const asSMessageInfo *msg, void *param) @@ -334,7 +334,7 @@ int ConfigureEngine(asIScriptEngine *engine, const char *configFile) } // Configure the engine with the information from the file - r = ConfigEngineFromStream(engine, strm, configFile, &stringFactory); + r = ConfigEngineFromStream(engine, strm, configFile, &stringFactory, vas::ValidateFormat, engine); if( r < 0 ) { engine->WriteMessage(configFile, 0, 0, asMSGTYPE_ERROR, "Configuration failed"); @@ -386,6 +386,7 @@ int CompileScript(asIScriptEngine *engine, const char *scriptFile, vas::BuildRep r = builder.StartNewModule(engine, "build"); if( r < 0 ) return -1; builder.SetIncludeCallback(VasIncludeCallback, &context); + builder.SetMappedMessageCallback(MessageCallback, report); r = builder.AddSectionFromFile(scriptFile); if( r < 0 ) return -1; @@ -434,29 +435,11 @@ static int ReportInvalidVasScriptExtension(asIScriptEngine *engine, const char * return asERROR; } -static string ResolveIncludePath(const char *include, const char *from) -{ - string includePath = include ? include : ""; - if( includePath.find_first_of("/\\") != 0 && includePath.find_first_of(":") == string::npos ) - { - string sourcePath = from ? from : ""; - string::size_type slash = sourcePath.find_last_of("/\\"); - if( slash != string::npos ) - sourcePath.resize(slash + 1); - else - sourcePath = ""; - - return sourcePath + includePath; - } - - return includePath; -} - static int VasIncludeCallback(const char *include, const char *from, CScriptBuilder *builder, void *userParam) { IncludeContext *context = static_cast(userParam); vas::BuildReport *report = context->report; - string resolvedInclude = ResolveIncludePath(include, from); + string resolvedInclude = static_cast(builder)->ResolveDependency(include, from); std::uint64_t attempt = 0; if( report ) { @@ -470,15 +453,17 @@ static int VasIncludeCallback(const char *include, const char *from, CScriptBuil report->Write(record); } - bool validExtension = IsVasScriptFile(resolvedInclude.c_str()); - int result = validExtension ? + bool resolved = !resolvedInclude.empty(); + if (!resolved) context->engine->WriteMessage(from, 0, 0, asMSGTYPE_ERROR, static_cast(builder)->GetResolutionError().c_str()); + bool validExtension = resolved && IsVasScriptFile(resolvedInclude.c_str()); + int result = !resolved ? -1 : validExtension ? static_cast(builder)->AddSectionFromFile(resolvedInclude.c_str()) : ReportInvalidVasScriptExtension(context->engine, resolvedInclude.c_str(), "included script"); if( report ) { vas::BuildReportRecord record = report->Record("include_result"); record.Number("attemptSeq", attempt); - record.Text("status", !validExtension ? "rejected" : result < 0 ? "failed" : result == 0 ? "skipped" : "loaded"); + record.Text("status", !resolved ? "failed" : !validExtension ? "rejected" : result < 0 ? "failed" : result == 0 ? "skipped" : "loaded"); report->Write(record); } return result; diff --git a/sdk/samples/asrun/source/main.cpp b/sdk/samples/asrun/source/main.cpp index 6c030e2bd..cc4199c3f 100644 --- a/sdk/samples/asrun/source/main.cpp +++ b/sdk/samples/asrun/source/main.cpp @@ -6,6 +6,7 @@ #include #include // stringstream +#include "../../common/vas_format.h" #include #include "../../../add_on/scriptbuilder/scriptbuilder.h" #include "../../../add_on/scriptstdstring/scriptstdstring.h" @@ -64,6 +65,30 @@ void MessageCallback(const asSMessageInfo *msg, void *param); asIScriptContext *RequestContextCallback(asIScriptEngine *engine, void *param); void ReturnContextCallback(asIScriptEngine *engine, asIScriptContext *ctx, void *param); void PrintString(const string &str); +static void PrintFormat(asIScriptGeneric *gen); +static void PrintlnFormat(asIScriptGeneric *gen); +static void PrintlnEmpty(); +template +static void PrintlnValue(T value) +{ + fmt::println("{}", value); +} +template +static void PrintlnSmallValue(asIScriptGeneric *gen) +{ + PrintlnValue(int(*static_cast(gen->GetAddressOfArg(0)))); +} +template +static void PrintValue(T value) +{ + fmt::print("{}", value); +} +template +static void PrintSmallValue(asIScriptGeneric *gen) +{ + // Read narrow values from their script storage, independent of native ABI extension. + PrintValue(int(*static_cast(gen->GetAddressOfArg(0)))); +} string GetInput(); int ExecSystemCmd(const string &cmd); int ExecSystemCmd(const string &str, string &out); @@ -72,7 +97,6 @@ void WaitForUser(); int PragmaCallback(const string &pragmaText, CScriptBuilder &builder, void *userParam); static bool IsVasScriptFile(const char *filename); static int ReportInvalidVasScriptExtension(asIScriptEngine *engine, const char *filename, const char *role); -static string ResolveIncludePath(const char *include, const char *from); static int VasIncludeCallback(const char *include, const char *from, CScriptBuilder *builder, void *userParam); // The command line arguments @@ -228,7 +252,33 @@ int ConfigureEngine(asIScriptEngine *engine) RegisterScriptSocket(engine); // Register a couple of extra functions for the scripts - r = engine->RegisterGlobalFunction("void print(const string &in)", asFUNCTION(PrintString), asCALL_CDECL); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void print(const string &in format, const ?&in ...)", asFUNCTION(PrintFormat), asCALL_GENERIC); assert( r >= 0 ); + { int checked = engine->GetFunctionById(r)->SetFormatStringValidator(vas::ValidateFormat, engine); assert(checked >= 0); (void)checked; } + r = engine->RegisterGlobalFunction("void print(int8)", asFUNCTION(PrintSmallValue), asCALL_GENERIC); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void print(uint8)", asFUNCTION(PrintSmallValue), asCALL_GENERIC); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void print(int16)", asFUNCTION(PrintSmallValue), asCALL_GENERIC); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void print(uint16)", asFUNCTION(PrintSmallValue), asCALL_GENERIC); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void print(int)", asFUNCTION(PrintValue), asCALL_CDECL); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void print(uint)", asFUNCTION(PrintValue), asCALL_CDECL); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void print(int64)", asFUNCTION(PrintValue), asCALL_CDECL); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void print(uint64)", asFUNCTION(PrintValue), asCALL_CDECL); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void print(float)", asFUNCTION(PrintValue), asCALL_CDECL); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void print(double)", asFUNCTION(PrintValue), asCALL_CDECL); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void print(bool)", asFUNCTION(PrintValue), asCALL_CDECL); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void println(const string &in format, const ?&in ...)", asFUNCTION(PrintlnFormat), asCALL_GENERIC); assert( r >= 0 ); + { int checked = engine->GetFunctionById(r)->SetFormatStringValidator(vas::ValidateFormat, engine); assert(checked >= 0); (void)checked; } + r = engine->RegisterGlobalFunction("void println()", asFUNCTION(PrintlnEmpty), asCALL_CDECL); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void println(int8)", asFUNCTION(PrintlnSmallValue), asCALL_GENERIC); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void println(uint8)", asFUNCTION(PrintlnSmallValue), asCALL_GENERIC); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void println(int16)", asFUNCTION(PrintlnSmallValue), asCALL_GENERIC); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void println(uint16)", asFUNCTION(PrintlnSmallValue), asCALL_GENERIC); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void println(int)", asFUNCTION(PrintlnValue), asCALL_CDECL); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void println(uint)", asFUNCTION(PrintlnValue), asCALL_CDECL); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void println(int64)", asFUNCTION(PrintlnValue), asCALL_CDECL); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void println(uint64)", asFUNCTION(PrintlnValue), asCALL_CDECL); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void println(float)", asFUNCTION(PrintlnValue), asCALL_CDECL); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void println(double)", asFUNCTION(PrintlnValue), asCALL_CDECL); assert( r >= 0 ); + r = engine->RegisterGlobalFunction("void println(bool)", asFUNCTION(PrintlnValue), asCALL_CDECL); assert( r >= 0 ); r = engine->RegisterGlobalFunction("string getInput()", asFUNCTION(GetInput), asCALL_CDECL); assert(r >= 0); r = engine->RegisterGlobalFunction("array @getCommandLineArgs()", asFUNCTION(GetCommandLineArgs), asCALL_CDECL); assert( r >= 0 ); r = engine->RegisterGlobalFunction("int exec(const string &in)", asFUNCTIONPR(ExecSystemCmd, (const string &), int), asCALL_CDECL); assert( r >= 0 ); @@ -380,6 +430,7 @@ int CompileScript(asIScriptEngine *engine, const char *scriptFile) // Compile the script r = builder.StartNewModule(engine, "script"); if( r < 0 ) return -1; + builder.SetMappedMessageCallback(MessageCallback, 0); r = builder.AddSectionFromFile(scriptFile); if( r < 0 ) return -1; @@ -419,28 +470,15 @@ static int ReportInvalidVasScriptExtension(asIScriptEngine *engine, const char * return asERROR; } -static string ResolveIncludePath(const char *include, const char *from) -{ - string includePath = include ? include : ""; - if( includePath.find_first_of("/\\") != 0 && includePath.find_first_of(":") == string::npos ) - { - string sourcePath = from ? from : ""; - string::size_type slash = sourcePath.find_last_of("/\\"); - if( slash != string::npos ) - sourcePath.resize(slash + 1); - else - sourcePath = ""; - - return sourcePath + includePath; - } - - return includePath; -} - static int VasIncludeCallback(const char *include, const char *from, CScriptBuilder *builder, void *userParam) { asIScriptEngine *engine = reinterpret_cast(userParam); - string resolvedInclude = ResolveIncludePath(include, from); + string resolvedInclude = static_cast(builder)->ResolveDependency(include, from); + if (resolvedInclude.empty()) + { + engine->WriteMessage(from, 0, 0, asMSGTYPE_ERROR, static_cast(builder)->GetResolutionError().c_str()); + return -1; + } if( !IsVasScriptFile(resolvedInclude.c_str()) ) return ReportInvalidVasScriptExtension(engine, resolvedInclude.c_str(), "included script"); @@ -560,6 +598,67 @@ int ExecuteScript(asIScriptEngine *engine, const char *scriptFile) return r; } +static void PrintlnEmpty() +{ + fmt::print("\n"); +} + +static void PrintFormatted(asIScriptGeneric *gen, bool newline) +{ + // Script arguments are dynamic: preserve their types for format specifiers. + try + { + vas::FormatArguments args(gen->GetArgCount() - 1); + const int stringType = gen->GetEngine()->GetTypeIdByDecl("string"); + for (asUINT index = 1; index < asUINT(gen->GetArgCount()); ++index) + { + void *value = gen->GetArgAddress(index); + const int type = gen->GetArgTypeId(index); + switch (type) + { + case asTYPEID_BOOL: args.set(int(index) - 1, *static_cast(value)); break; + case asTYPEID_INT8: args.set(int(index) - 1, int(*static_cast(value))); break; + case asTYPEID_UINT8: args.set(int(index) - 1, unsigned(*static_cast(value))); break; + case asTYPEID_INT16: args.set(int(index) - 1, int(*static_cast(value))); break; + case asTYPEID_UINT16: args.set(int(index) - 1, unsigned(*static_cast(value))); break; + case asTYPEID_INT32: args.set(int(index) - 1, *static_cast(value)); break; + case asTYPEID_UINT32: args.set(int(index) - 1, *static_cast(value)); break; + case asTYPEID_INT64: args.set(int(index) - 1, *static_cast(value)); break; + case asTYPEID_UINT64: args.set(int(index) - 1, *static_cast(value)); break; + case asTYPEID_FLOAT: args.set(int(index) - 1, *static_cast(value)); break; + case asTYPEID_DOUBLE: args.set(int(index) - 1, *static_cast(value)); break; + default: + if (type != stringType) + { + asGetActiveContext()->SetException(newline ? "println: unsupported argument type" : "print: unsupported argument type"); + return; + } + const string &str = *static_cast(value); + args.set(int(index) - 1, fmt::string_view(str.data(), str.size())); + } + } + // Complete formatting before output, so failures cannot print a partial line. + fmt::memory_buffer output; + const string &format = *static_cast(gen->GetArgAddress(0)); + vas::FormatTo(output, fmt::string_view(format.data(), format.size()), args, newline); + fmt::print("{}", fmt::string_view(output.data(), output.size())); + } + catch (const std::exception &error) + { + asGetActiveContext()->SetException((string(newline ? "println: " : "print: ") + error.what()).c_str()); + } +} + +static void PrintFormat(asIScriptGeneric *gen) +{ + PrintFormatted(gen, false); +} + +static void PrintlnFormat(asIScriptGeneric *gen) +{ + PrintFormatted(gen, true); +} + // This little function allows the script to print a string to the screen void PrintString(const string &str) { diff --git a/sdk/samples/asrun/vendor/fmt/LICENSE b/sdk/samples/asrun/vendor/fmt/LICENSE new file mode 100644 index 000000000..1cd1ef926 --- /dev/null +++ b/sdk/samples/asrun/vendor/fmt/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2012 - present, Victor Zverovich and {fmt} contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +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 AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +--- Optional exception to the license --- + +As an exception, if, as a result of your compiling your source code, portions +of this Software are embedded into a machine-executable object form of such +source code, you may redistribute such embedded portions in such object form +without including the above copyright and permission notices. diff --git a/sdk/samples/asrun/vendor/fmt/README.md b/sdk/samples/asrun/vendor/fmt/README.md new file mode 100644 index 000000000..f50d48dfa --- /dev/null +++ b/sdk/samples/asrun/vendor/fmt/README.md @@ -0,0 +1,16 @@ +# fmt 11.2.0 + +Unmodified args.h, base.h, format.h and format-inl.h from the official 11.2.0 tag: +https://github.com/fmtlib/fmt/tree/11.2.0/include/fmt + +LICENSE is copied unchanged from the same tag. Header-only, used by vasrun and vasbuild via samples/common/vas_format.h. +The type-only validator uses fmt parser internals; upgrades must rerun format validation tests. +The AngelScript core does not depend on fmt. +Builds are offline; no runtime DLL or network dependency. + +SHA-256: +args.h: cd2a4230a2b95db60f00673743769fe7372f0f708713520cab787173b5055187 +base.h: 13c8d953fb2d98dc955289dd166999bd22dbabfeba7f486b3693c2c6d9d627db +format-inl.h: 7ac4d4907568ac99c28461881595053d2e4045ee81c89d0bddb779c718ee736c +format.h: 9ac34739eb99d5fe220c96d59519bf8da9fb0108d1cf5badbed157187e4c3cfb +LICENSE: 07580f2a3b35709ce703d523f447b242f6dfec7582a8c0df102c7fa2849375f8 diff --git a/sdk/samples/asrun/vendor/fmt/args.h b/sdk/samples/asrun/vendor/fmt/args.h new file mode 100644 index 000000000..3ff478807 --- /dev/null +++ b/sdk/samples/asrun/vendor/fmt/args.h @@ -0,0 +1,220 @@ +// Formatting library for C++ - dynamic argument lists +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_ARGS_H_ +#define FMT_ARGS_H_ + +#ifndef FMT_MODULE +# include // std::reference_wrapper +# include // std::unique_ptr +# include +#endif + +#include "format.h" // std_string_view + +FMT_BEGIN_NAMESPACE +namespace detail { + +template struct is_reference_wrapper : std::false_type {}; +template +struct is_reference_wrapper> : std::true_type {}; + +template auto unwrap(const T& v) -> const T& { return v; } +template +auto unwrap(const std::reference_wrapper& v) -> const T& { + return static_cast(v); +} + +// node is defined outside dynamic_arg_list to workaround a C2504 bug in MSVC +// 2022 (v17.10.0). +// +// Workaround for clang's -Wweak-vtables. Unlike for regular classes, for +// templates it doesn't complain about inability to deduce single translation +// unit for placing vtable. So node is made a fake template. +template struct node { + virtual ~node() = default; + std::unique_ptr> next; +}; + +class dynamic_arg_list { + template struct typed_node : node<> { + T value; + + template + FMT_CONSTEXPR typed_node(const Arg& arg) : value(arg) {} + + template + FMT_CONSTEXPR typed_node(const basic_string_view& arg) + : value(arg.data(), arg.size()) {} + }; + + std::unique_ptr> head_; + + public: + template auto push(const Arg& arg) -> const T& { + auto new_node = std::unique_ptr>(new typed_node(arg)); + auto& value = new_node->value; + new_node->next = std::move(head_); + head_ = std::move(new_node); + return value; + } +}; +} // namespace detail + +/** + * A dynamic list of formatting arguments with storage. + * + * It can be implicitly converted into `fmt::basic_format_args` for passing + * into type-erased formatting functions such as `fmt::vformat`. + */ +template class dynamic_format_arg_store { + private: + using char_type = typename Context::char_type; + + template struct need_copy { + static constexpr detail::type mapped_type = + detail::mapped_type_constant::value; + + enum { + value = !(detail::is_reference_wrapper::value || + std::is_same>::value || + std::is_same>::value || + (mapped_type != detail::type::cstring_type && + mapped_type != detail::type::string_type && + mapped_type != detail::type::custom_type)) + }; + }; + + template + using stored_t = conditional_t< + std::is_convertible>::value && + !detail::is_reference_wrapper::value, + std::basic_string, T>; + + // Storage of basic_format_arg must be contiguous. + std::vector> data_; + std::vector> named_info_; + + // Storage of arguments not fitting into basic_format_arg must grow + // without relocation because items in data_ refer to it. + detail::dynamic_arg_list dynamic_args_; + + friend class basic_format_args; + + auto data() const -> const basic_format_arg* { + return named_info_.empty() ? data_.data() : data_.data() + 1; + } + + template void emplace_arg(const T& arg) { + data_.emplace_back(arg); + } + + template + void emplace_arg(const detail::named_arg& arg) { + if (named_info_.empty()) + data_.insert(data_.begin(), basic_format_arg(nullptr, 0)); + data_.emplace_back(detail::unwrap(arg.value)); + auto pop_one = [](std::vector>* data) { + data->pop_back(); + }; + std::unique_ptr>, decltype(pop_one)> + guard{&data_, pop_one}; + named_info_.push_back({arg.name, static_cast(data_.size() - 2u)}); + data_[0] = {named_info_.data(), named_info_.size()}; + guard.release(); + } + + public: + constexpr dynamic_format_arg_store() = default; + + operator basic_format_args() const { + return basic_format_args(data(), static_cast(data_.size()), + !named_info_.empty()); + } + + /** + * Adds an argument into the dynamic store for later passing to a formatting + * function. + * + * Note that custom types and string types (but not string views) are copied + * into the store dynamically allocating memory if necessary. + * + * **Example**: + * + * fmt::dynamic_format_arg_store store; + * store.push_back(42); + * store.push_back("abc"); + * store.push_back(1.5f); + * std::string result = fmt::vformat("{} and {} and {}", store); + */ + template void push_back(const T& arg) { + if (detail::const_check(need_copy::value)) + emplace_arg(dynamic_args_.push>(arg)); + else + emplace_arg(detail::unwrap(arg)); + } + + /** + * Adds a reference to the argument into the dynamic store for later passing + * to a formatting function. + * + * **Example**: + * + * fmt::dynamic_format_arg_store store; + * char band[] = "Rolling Stones"; + * store.push_back(std::cref(band)); + * band[9] = 'c'; // Changing str affects the output. + * std::string result = fmt::vformat("{}", store); + * // result == "Rolling Scones" + */ + template void push_back(std::reference_wrapper arg) { + static_assert( + need_copy::value, + "objects of built-in types and string views are always copied"); + emplace_arg(arg.get()); + } + + /** + * Adds named argument into the dynamic store for later passing to a + * formatting function. `std::reference_wrapper` is supported to avoid + * copying of the argument. The name is always copied into the store. + */ + template + void push_back(const detail::named_arg& arg) { + const char_type* arg_name = + dynamic_args_.push>(arg.name).c_str(); + if (detail::const_check(need_copy::value)) { + emplace_arg( + fmt::arg(arg_name, dynamic_args_.push>(arg.value))); + } else { + emplace_arg(fmt::arg(arg_name, arg.value)); + } + } + + /// Erase all elements from the store. + void clear() { + data_.clear(); + named_info_.clear(); + dynamic_args_ = {}; + } + + /// Reserves space to store at least `new_cap` arguments including + /// `new_cap_named` named arguments. + void reserve(size_t new_cap, size_t new_cap_named) { + FMT_ASSERT(new_cap >= new_cap_named, + "set of arguments includes set of named arguments"); + data_.reserve(new_cap); + named_info_.reserve(new_cap_named); + } + + /// Returns the number of elements in the store. + size_t size() const noexcept { return data_.size(); } +}; + +FMT_END_NAMESPACE + +#endif // FMT_ARGS_H_ diff --git a/sdk/samples/asrun/vendor/fmt/base.h b/sdk/samples/asrun/vendor/fmt/base.h new file mode 100644 index 000000000..87b3fd7cb --- /dev/null +++ b/sdk/samples/asrun/vendor/fmt/base.h @@ -0,0 +1,2989 @@ +// Formatting library for C++ - the base API for char/UTF-8 +// +// Copyright (c) 2012 - present, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_BASE_H_ +#define FMT_BASE_H_ + +#if defined(FMT_IMPORT_STD) && !defined(FMT_MODULE) +# define FMT_MODULE +#endif + +#ifndef FMT_MODULE +# include // CHAR_BIT +# include // FILE +# include // memcmp + +# include // std::enable_if +#endif + +// The fmt library version in the form major * 10000 + minor * 100 + patch. +#define FMT_VERSION 110200 + +// Detect compiler versions. +#if defined(__clang__) && !defined(__ibmxl__) +# define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__) +#else +# define FMT_CLANG_VERSION 0 +#endif +#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) +# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) +#else +# define FMT_GCC_VERSION 0 +#endif +#if defined(__ICL) +# define FMT_ICC_VERSION __ICL +#elif defined(__INTEL_COMPILER) +# define FMT_ICC_VERSION __INTEL_COMPILER +#else +# define FMT_ICC_VERSION 0 +#endif +#if defined(_MSC_VER) +# define FMT_MSC_VERSION _MSC_VER +#else +# define FMT_MSC_VERSION 0 +#endif + +// Detect standard library versions. +#ifdef _GLIBCXX_RELEASE +# define FMT_GLIBCXX_RELEASE _GLIBCXX_RELEASE +#else +# define FMT_GLIBCXX_RELEASE 0 +#endif +#ifdef _LIBCPP_VERSION +# define FMT_LIBCPP_VERSION _LIBCPP_VERSION +#else +# define FMT_LIBCPP_VERSION 0 +#endif + +#ifdef _MSVC_LANG +# define FMT_CPLUSPLUS _MSVC_LANG +#else +# define FMT_CPLUSPLUS __cplusplus +#endif + +// Detect __has_*. +#ifdef __has_feature +# define FMT_HAS_FEATURE(x) __has_feature(x) +#else +# define FMT_HAS_FEATURE(x) 0 +#endif +#ifdef __has_include +# define FMT_HAS_INCLUDE(x) __has_include(x) +#else +# define FMT_HAS_INCLUDE(x) 0 +#endif +#ifdef __has_builtin +# define FMT_HAS_BUILTIN(x) __has_builtin(x) +#else +# define FMT_HAS_BUILTIN(x) 0 +#endif +#ifdef __has_cpp_attribute +# define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x) +#else +# define FMT_HAS_CPP_ATTRIBUTE(x) 0 +#endif + +#define FMT_HAS_CPP14_ATTRIBUTE(attribute) \ + (FMT_CPLUSPLUS >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute)) + +#define FMT_HAS_CPP17_ATTRIBUTE(attribute) \ + (FMT_CPLUSPLUS >= 201703L && FMT_HAS_CPP_ATTRIBUTE(attribute)) + +// Detect C++14 relaxed constexpr. +#ifdef FMT_USE_CONSTEXPR +// Use the provided definition. +#elif FMT_GCC_VERSION >= 702 && FMT_CPLUSPLUS >= 201402L +// GCC only allows constexpr member functions in non-literal types since 7.2: +// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66297. +# define FMT_USE_CONSTEXPR 1 +#elif FMT_ICC_VERSION +# define FMT_USE_CONSTEXPR 0 // https://github.com/fmtlib/fmt/issues/1628 +#elif FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VERSION >= 1912 +# define FMT_USE_CONSTEXPR 1 +#else +# define FMT_USE_CONSTEXPR 0 +#endif +#if FMT_USE_CONSTEXPR +# define FMT_CONSTEXPR constexpr +#else +# define FMT_CONSTEXPR +#endif + +// Detect consteval, C++20 constexpr extensions and std::is_constant_evaluated. +#if !defined(__cpp_lib_is_constant_evaluated) +# define FMT_USE_CONSTEVAL 0 +#elif FMT_CPLUSPLUS < 201709L +# define FMT_USE_CONSTEVAL 0 +#elif FMT_GLIBCXX_RELEASE && FMT_GLIBCXX_RELEASE < 10 +# define FMT_USE_CONSTEVAL 0 +#elif FMT_LIBCPP_VERSION && FMT_LIBCPP_VERSION < 10000 +# define FMT_USE_CONSTEVAL 0 +#elif defined(__apple_build_version__) && __apple_build_version__ < 14000029L +# define FMT_USE_CONSTEVAL 0 // consteval is broken in Apple clang < 14. +#elif FMT_MSC_VERSION && FMT_MSC_VERSION < 1929 +# define FMT_USE_CONSTEVAL 0 // consteval is broken in MSVC VS2019 < 16.10. +#elif defined(__cpp_consteval) +# define FMT_USE_CONSTEVAL 1 +#elif FMT_GCC_VERSION >= 1002 || FMT_CLANG_VERSION >= 1101 +# define FMT_USE_CONSTEVAL 1 +#else +# define FMT_USE_CONSTEVAL 0 +#endif +#if FMT_USE_CONSTEVAL +# define FMT_CONSTEVAL consteval +# define FMT_CONSTEXPR20 constexpr +#else +# define FMT_CONSTEVAL +# define FMT_CONSTEXPR20 +#endif + +// Check if exceptions are disabled. +#ifdef FMT_USE_EXCEPTIONS +// Use the provided definition. +#elif defined(__GNUC__) && !defined(__EXCEPTIONS) +# define FMT_USE_EXCEPTIONS 0 +#elif defined(__clang__) && !defined(__cpp_exceptions) +# define FMT_USE_EXCEPTIONS 0 +#elif FMT_MSC_VERSION && !_HAS_EXCEPTIONS +# define FMT_USE_EXCEPTIONS 0 +#else +# define FMT_USE_EXCEPTIONS 1 +#endif +#if FMT_USE_EXCEPTIONS +# define FMT_TRY try +# define FMT_CATCH(x) catch (x) +#else +# define FMT_TRY if (true) +# define FMT_CATCH(x) if (false) +#endif + +#ifdef FMT_NO_UNIQUE_ADDRESS +// Use the provided definition. +#elif FMT_CPLUSPLUS < 202002L +// Not supported. +#elif FMT_HAS_CPP_ATTRIBUTE(no_unique_address) +# define FMT_NO_UNIQUE_ADDRESS [[no_unique_address]] +// VS2019 v16.10 and later except clang-cl (https://reviews.llvm.org/D110485). +#elif FMT_MSC_VERSION >= 1929 && !FMT_CLANG_VERSION +# define FMT_NO_UNIQUE_ADDRESS [[msvc::no_unique_address]] +#endif +#ifndef FMT_NO_UNIQUE_ADDRESS +# define FMT_NO_UNIQUE_ADDRESS +#endif + +#if FMT_HAS_CPP17_ATTRIBUTE(fallthrough) +# define FMT_FALLTHROUGH [[fallthrough]] +#elif defined(__clang__) +# define FMT_FALLTHROUGH [[clang::fallthrough]] +#elif FMT_GCC_VERSION >= 700 && \ + (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 520) +# define FMT_FALLTHROUGH [[gnu::fallthrough]] +#else +# define FMT_FALLTHROUGH +#endif + +// Disable [[noreturn]] on MSVC/NVCC because of bogus unreachable code warnings. +#if FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VERSION && !defined(__NVCC__) +# define FMT_NORETURN [[noreturn]] +#else +# define FMT_NORETURN +#endif + +#ifdef FMT_NODISCARD +// Use the provided definition. +#elif FMT_HAS_CPP17_ATTRIBUTE(nodiscard) +# define FMT_NODISCARD [[nodiscard]] +#else +# define FMT_NODISCARD +#endif + +#ifdef FMT_DEPRECATED +// Use the provided definition. +#elif FMT_HAS_CPP14_ATTRIBUTE(deprecated) +# define FMT_DEPRECATED [[deprecated]] +#else +# define FMT_DEPRECATED /* deprecated */ +#endif + +#if FMT_GCC_VERSION || FMT_CLANG_VERSION +# define FMT_VISIBILITY(value) __attribute__((visibility(value))) +#else +# define FMT_VISIBILITY(value) +#endif + +// Detect pragmas. +#define FMT_PRAGMA_IMPL(x) _Pragma(#x) +#if FMT_GCC_VERSION >= 504 && !defined(__NVCOMPILER) +// Workaround a _Pragma bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59884 +// and an nvhpc warning: https://github.com/fmtlib/fmt/pull/2582. +# define FMT_PRAGMA_GCC(x) FMT_PRAGMA_IMPL(GCC x) +#else +# define FMT_PRAGMA_GCC(x) +#endif +#if FMT_CLANG_VERSION +# define FMT_PRAGMA_CLANG(x) FMT_PRAGMA_IMPL(clang x) +#else +# define FMT_PRAGMA_CLANG(x) +#endif +#if FMT_MSC_VERSION +# define FMT_MSC_WARNING(...) __pragma(warning(__VA_ARGS__)) +#else +# define FMT_MSC_WARNING(...) +#endif + +// Enable minimal optimizations for more compact code in debug mode. +FMT_PRAGMA_GCC(push_options) +#if !defined(__OPTIMIZE__) && !defined(__CUDACC__) && !defined(FMT_MODULE) +FMT_PRAGMA_GCC(optimize("Og")) +# define FMT_GCC_OPTIMIZED +#endif +FMT_PRAGMA_CLANG(diagnostic push) + +#ifdef FMT_ALWAYS_INLINE +// Use the provided definition. +#elif FMT_GCC_VERSION || FMT_CLANG_VERSION +# define FMT_ALWAYS_INLINE inline __attribute__((always_inline)) +#else +# define FMT_ALWAYS_INLINE inline +#endif +// A version of FMT_ALWAYS_INLINE to prevent code bloat in debug mode. +#if defined(NDEBUG) || defined(FMT_GCC_OPTIMIZED) +# define FMT_INLINE FMT_ALWAYS_INLINE +#else +# define FMT_INLINE inline +#endif + +#ifndef FMT_BEGIN_NAMESPACE +# define FMT_BEGIN_NAMESPACE \ + namespace fmt { \ + inline namespace v11 { +# define FMT_END_NAMESPACE \ + } \ + } +#endif + +#ifndef FMT_EXPORT +# define FMT_EXPORT +# define FMT_BEGIN_EXPORT +# define FMT_END_EXPORT +#endif + +#ifdef _WIN32 +# define FMT_WIN32 1 +#else +# define FMT_WIN32 0 +#endif + +#if !defined(FMT_HEADER_ONLY) && FMT_WIN32 +# if defined(FMT_LIB_EXPORT) +# define FMT_API __declspec(dllexport) +# elif defined(FMT_SHARED) +# define FMT_API __declspec(dllimport) +# endif +#elif defined(FMT_LIB_EXPORT) || defined(FMT_SHARED) +# define FMT_API FMT_VISIBILITY("default") +#endif +#ifndef FMT_API +# define FMT_API +#endif + +#ifndef FMT_OPTIMIZE_SIZE +# define FMT_OPTIMIZE_SIZE 0 +#endif + +// FMT_BUILTIN_TYPE=0 may result in smaller library size at the cost of higher +// per-call binary size by passing built-in types through the extension API. +#ifndef FMT_BUILTIN_TYPES +# define FMT_BUILTIN_TYPES 1 +#endif + +#define FMT_APPLY_VARIADIC(expr) \ + using unused = int[]; \ + (void)unused { 0, (expr, 0)... } + +FMT_BEGIN_NAMESPACE + +// Implementations of enable_if_t and other metafunctions for older systems. +template +using enable_if_t = typename std::enable_if::type; +template +using conditional_t = typename std::conditional::type; +template using bool_constant = std::integral_constant; +template +using remove_reference_t = typename std::remove_reference::type; +template +using remove_const_t = typename std::remove_const::type; +template +using remove_cvref_t = typename std::remove_cv>::type; +template +using make_unsigned_t = typename std::make_unsigned::type; +template +using underlying_t = typename std::underlying_type::type; +template using decay_t = typename std::decay::type; +using nullptr_t = decltype(nullptr); + +#if (FMT_GCC_VERSION && FMT_GCC_VERSION < 500) || FMT_MSC_VERSION +// A workaround for gcc 4.9 & MSVC v141 to make void_t work in a SFINAE context. +template struct void_t_impl { + using type = void; +}; +template using void_t = typename void_t_impl::type; +#else +template using void_t = void; +#endif + +struct monostate { + constexpr monostate() {} +}; + +// An enable_if helper to be used in template parameters which results in much +// shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed +// to workaround a bug in MSVC 2019 (see #1140 and #1186). +#ifdef FMT_DOC +# define FMT_ENABLE_IF(...) +#else +# define FMT_ENABLE_IF(...) fmt::enable_if_t<(__VA_ARGS__), int> = 0 +#endif + +template constexpr auto min_of(T a, T b) -> T { + return a < b ? a : b; +} +template constexpr auto max_of(T a, T b) -> T { + return a > b ? a : b; +} + +namespace detail { +// Suppresses "unused variable" warnings with the method described in +// https://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/. +// (void)var does not work on many Intel compilers. +template FMT_CONSTEXPR void ignore_unused(const T&...) {} + +constexpr auto is_constant_evaluated(bool default_value = false) noexcept + -> bool { +// Workaround for incompatibility between clang 14 and libstdc++ consteval-based +// std::is_constant_evaluated: https://github.com/fmtlib/fmt/issues/3247. +#if FMT_CPLUSPLUS >= 202002L && FMT_GLIBCXX_RELEASE >= 12 && \ + (FMT_CLANG_VERSION >= 1400 && FMT_CLANG_VERSION < 1500) + ignore_unused(default_value); + return __builtin_is_constant_evaluated(); +#elif defined(__cpp_lib_is_constant_evaluated) + ignore_unused(default_value); + return std::is_constant_evaluated(); +#else + return default_value; +#endif +} + +// Suppresses "conditional expression is constant" warnings. +template FMT_ALWAYS_INLINE constexpr auto const_check(T val) -> T { + return val; +} + +FMT_NORETURN FMT_API void assert_fail(const char* file, int line, + const char* message); + +#if defined(FMT_ASSERT) +// Use the provided definition. +#elif defined(NDEBUG) +// FMT_ASSERT is not empty to avoid -Wempty-body. +# define FMT_ASSERT(condition, message) \ + fmt::detail::ignore_unused((condition), (message)) +#else +# define FMT_ASSERT(condition, message) \ + ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \ + ? (void)0 \ + : fmt::detail::assert_fail(__FILE__, __LINE__, (message))) +#endif + +#ifdef FMT_USE_INT128 +// Use the provided definition. +#elif defined(__SIZEOF_INT128__) && !defined(__NVCC__) && \ + !(FMT_CLANG_VERSION && FMT_MSC_VERSION) +# define FMT_USE_INT128 1 +using int128_opt = __int128_t; // An optional native 128-bit integer. +using uint128_opt = __uint128_t; +inline auto map(int128_opt x) -> int128_opt { return x; } +inline auto map(uint128_opt x) -> uint128_opt { return x; } +#else +# define FMT_USE_INT128 0 +#endif +#if !FMT_USE_INT128 +enum class int128_opt {}; +enum class uint128_opt {}; +// Reduce template instantiations. +inline auto map(int128_opt) -> monostate { return {}; } +inline auto map(uint128_opt) -> monostate { return {}; } +#endif + +#ifndef FMT_USE_BITINT +# define FMT_USE_BITINT (FMT_CLANG_VERSION >= 1500) +#endif + +#if FMT_USE_BITINT +FMT_PRAGMA_CLANG(diagnostic ignored "-Wbit-int-extension") +template using bitint = _BitInt(N); +template using ubitint = unsigned _BitInt(N); +#else +template struct bitint {}; +template struct ubitint {}; +#endif // FMT_USE_BITINT + +// Casts a nonnegative integer to unsigned. +template +FMT_CONSTEXPR auto to_unsigned(Int value) -> make_unsigned_t { + FMT_ASSERT(std::is_unsigned::value || value >= 0, "negative value"); + return static_cast>(value); +} + +template +using unsigned_char = conditional_t; + +// A heuristic to detect std::string and std::[experimental::]string_view. +// It is mainly used to avoid dependency on <[experimental/]string_view>. +template +struct is_std_string_like : std::false_type {}; +template +struct is_std_string_like().find_first_of( + typename T::value_type(), 0))>> + : std::is_convertible().data()), + const typename T::value_type*> {}; + +// Check if the literal encoding is UTF-8. +enum { is_utf8_enabled = "\u00A7"[1] == '\xA7' }; +enum { use_utf8 = !FMT_WIN32 || is_utf8_enabled }; + +#ifndef FMT_UNICODE +# define FMT_UNICODE 1 +#endif + +static_assert(!FMT_UNICODE || use_utf8, + "Unicode support requires compiling with /utf-8"); + +template constexpr const char* narrow(const T*) { return nullptr; } +constexpr FMT_ALWAYS_INLINE const char* narrow(const char* s) { return s; } + +template +FMT_CONSTEXPR auto compare(const Char* s1, const Char* s2, std::size_t n) + -> int { + if (!is_constant_evaluated() && sizeof(Char) == 1) return memcmp(s1, s2, n); + for (; n != 0; ++s1, ++s2, --n) { + if (*s1 < *s2) return -1; + if (*s1 > *s2) return 1; + } + return 0; +} + +namespace adl { +using namespace std; + +template +auto invoke_back_inserter() + -> decltype(back_inserter(std::declval())); +} // namespace adl + +template +struct is_back_insert_iterator : std::false_type {}; + +template +struct is_back_insert_iterator< + It, bool_constant()), + It>::value>> : std::true_type {}; + +// Extracts a reference to the container from *insert_iterator. +template +inline FMT_CONSTEXPR20 auto get_container(OutputIt it) -> + typename OutputIt::container_type& { + struct accessor : OutputIt { + FMT_CONSTEXPR20 accessor(OutputIt base) : OutputIt(base) {} + using OutputIt::container; + }; + return *accessor(it).container; +} +} // namespace detail + +// Parsing-related public API and forward declarations. +FMT_BEGIN_EXPORT + +/** + * An implementation of `std::basic_string_view` for pre-C++17. It provides a + * subset of the API. `fmt::basic_string_view` is used for format strings even + * if `std::basic_string_view` is available to prevent issues when a library is + * compiled with a different `-std` option than the client code (which is not + * recommended). + */ +template class basic_string_view { + private: + const Char* data_; + size_t size_; + + public: + using value_type = Char; + using iterator = const Char*; + + constexpr basic_string_view() noexcept : data_(nullptr), size_(0) {} + + /// Constructs a string view object from a C string and a size. + constexpr basic_string_view(const Char* s, size_t count) noexcept + : data_(s), size_(count) {} + + constexpr basic_string_view(nullptr_t) = delete; + + /// Constructs a string view object from a C string. +#if FMT_GCC_VERSION + FMT_ALWAYS_INLINE +#endif + FMT_CONSTEXPR20 basic_string_view(const Char* s) : data_(s) { +#if FMT_HAS_BUILTIN(__builtin_strlen) || FMT_GCC_VERSION || FMT_CLANG_VERSION + if (std::is_same::value && !detail::is_constant_evaluated()) { + size_ = __builtin_strlen(detail::narrow(s)); // strlen is not costexpr. + return; + } +#endif + size_t len = 0; + while (*s++) ++len; + size_ = len; + } + + /// Constructs a string view from a `std::basic_string` or a + /// `std::basic_string_view` object. + template ::value&& std::is_same< + typename S::value_type, Char>::value)> + FMT_CONSTEXPR basic_string_view(const S& s) noexcept + : data_(s.data()), size_(s.size()) {} + + /// Returns a pointer to the string data. + constexpr auto data() const noexcept -> const Char* { return data_; } + + /// Returns the string size. + constexpr auto size() const noexcept -> size_t { return size_; } + + constexpr auto begin() const noexcept -> iterator { return data_; } + constexpr auto end() const noexcept -> iterator { return data_ + size_; } + + constexpr auto operator[](size_t pos) const noexcept -> const Char& { + return data_[pos]; + } + + FMT_CONSTEXPR void remove_prefix(size_t n) noexcept { + data_ += n; + size_ -= n; + } + + FMT_CONSTEXPR auto starts_with(basic_string_view sv) const noexcept + -> bool { + return size_ >= sv.size_ && detail::compare(data_, sv.data_, sv.size_) == 0; + } + FMT_CONSTEXPR auto starts_with(Char c) const noexcept -> bool { + return size_ >= 1 && *data_ == c; + } + FMT_CONSTEXPR auto starts_with(const Char* s) const -> bool { + return starts_with(basic_string_view(s)); + } + + FMT_CONSTEXPR auto compare(basic_string_view other) const -> int { + int result = + detail::compare(data_, other.data_, min_of(size_, other.size_)); + if (result != 0) return result; + return size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1); + } + + FMT_CONSTEXPR friend auto operator==(basic_string_view lhs, + basic_string_view rhs) -> bool { + return lhs.compare(rhs) == 0; + } + friend auto operator!=(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) != 0; + } + friend auto operator<(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) < 0; + } + friend auto operator<=(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) <= 0; + } + friend auto operator>(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) > 0; + } + friend auto operator>=(basic_string_view lhs, basic_string_view rhs) -> bool { + return lhs.compare(rhs) >= 0; + } +}; + +using string_view = basic_string_view; + +// DEPRECATED! Will be merged with is_char and moved to detail. +template struct is_xchar : std::false_type {}; +template <> struct is_xchar : std::true_type {}; +template <> struct is_xchar : std::true_type {}; +template <> struct is_xchar : std::true_type {}; +#ifdef __cpp_char8_t +template <> struct is_xchar : std::true_type {}; +#endif + +// Specifies if `T` is a character (code unit) type. +template struct is_char : is_xchar {}; +template <> struct is_char : std::true_type {}; + +template class basic_appender; +using appender = basic_appender; + +// Checks whether T is a container with contiguous storage. +template struct is_contiguous : std::false_type {}; + +class context; +template class generic_context; +template class parse_context; + +// Longer aliases for C++20 compatibility. +template using basic_format_parse_context = parse_context; +using format_parse_context = parse_context; +template +using basic_format_context = + conditional_t::value, context, + generic_context>; +using format_context = context; + +template +using buffered_context = + conditional_t::value, context, + generic_context, Char>>; + +template class basic_format_arg; +template class basic_format_args; + +// A separate type would result in shorter symbols but break ABI compatibility +// between clang and gcc on ARM (#1919). +using format_args = basic_format_args; + +// A formatter for objects of type T. +template +struct formatter { + // A deleted default constructor indicates a disabled formatter. + formatter() = delete; +}; + +/// Reports a format error at compile time or, via a `format_error` exception, +/// at runtime. +// This function is intentionally not constexpr to give a compile-time error. +FMT_NORETURN FMT_API void report_error(const char* message); + +enum class presentation_type : unsigned char { + // Common specifiers: + none = 0, + debug = 1, // '?' + string = 2, // 's' (string, bool) + + // Integral, bool and character specifiers: + dec = 3, // 'd' + hex, // 'x' or 'X' + oct, // 'o' + bin, // 'b' or 'B' + chr, // 'c' + + // String and pointer specifiers: + pointer = 3, // 'p' + + // Floating-point specifiers: + exp = 1, // 'e' or 'E' (1 since there is no FP debug presentation) + fixed, // 'f' or 'F' + general, // 'g' or 'G' + hexfloat // 'a' or 'A' +}; + +enum class align { none, left, right, center, numeric }; +enum class sign { none, minus, plus, space }; +enum class arg_id_kind { none, index, name }; + +// Basic format specifiers for built-in and string types. +class basic_specs { + private: + // Data is arranged as follows: + // + // 0 1 2 3 + // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + // |type |align| w | p | s |u|#|L| f | unused | + // +-----+-----+---+---+---+-+-+-+-----+---------------------------+ + // + // w - dynamic width info + // p - dynamic precision info + // s - sign + // u - uppercase (e.g. 'X' for 'x') + // # - alternate form ('#') + // L - localized + // f - fill size + // + // Bitfields are not used because of compiler bugs such as gcc bug 61414. + enum : unsigned { + type_mask = 0x00007, + align_mask = 0x00038, + width_mask = 0x000C0, + precision_mask = 0x00300, + sign_mask = 0x00C00, + uppercase_mask = 0x01000, + alternate_mask = 0x02000, + localized_mask = 0x04000, + fill_size_mask = 0x38000, + + align_shift = 3, + width_shift = 6, + precision_shift = 8, + sign_shift = 10, + fill_size_shift = 15, + + max_fill_size = 4 + }; + + unsigned data_ = 1 << fill_size_shift; + static_assert(sizeof(basic_specs::data_) * CHAR_BIT >= 18, ""); + + // Character (code unit) type is erased to prevent template bloat. + char fill_data_[max_fill_size] = {' '}; + + FMT_CONSTEXPR void set_fill_size(size_t size) { + data_ = (data_ & ~fill_size_mask) | + (static_cast(size) << fill_size_shift); + } + + public: + constexpr auto type() const -> presentation_type { + return static_cast(data_ & type_mask); + } + FMT_CONSTEXPR void set_type(presentation_type t) { + data_ = (data_ & ~type_mask) | static_cast(t); + } + + constexpr auto align() const -> align { + return static_cast((data_ & align_mask) >> align_shift); + } + FMT_CONSTEXPR void set_align(fmt::align a) { + data_ = (data_ & ~align_mask) | (static_cast(a) << align_shift); + } + + constexpr auto dynamic_width() const -> arg_id_kind { + return static_cast((data_ & width_mask) >> width_shift); + } + FMT_CONSTEXPR void set_dynamic_width(arg_id_kind w) { + data_ = (data_ & ~width_mask) | (static_cast(w) << width_shift); + } + + FMT_CONSTEXPR auto dynamic_precision() const -> arg_id_kind { + return static_cast((data_ & precision_mask) >> + precision_shift); + } + FMT_CONSTEXPR void set_dynamic_precision(arg_id_kind p) { + data_ = (data_ & ~precision_mask) | + (static_cast(p) << precision_shift); + } + + constexpr bool dynamic() const { + return (data_ & (width_mask | precision_mask)) != 0; + } + + constexpr auto sign() const -> sign { + return static_cast((data_ & sign_mask) >> sign_shift); + } + FMT_CONSTEXPR void set_sign(fmt::sign s) { + data_ = (data_ & ~sign_mask) | (static_cast(s) << sign_shift); + } + + constexpr auto upper() const -> bool { return (data_ & uppercase_mask) != 0; } + FMT_CONSTEXPR void set_upper() { data_ |= uppercase_mask; } + + constexpr auto alt() const -> bool { return (data_ & alternate_mask) != 0; } + FMT_CONSTEXPR void set_alt() { data_ |= alternate_mask; } + FMT_CONSTEXPR void clear_alt() { data_ &= ~alternate_mask; } + + constexpr auto localized() const -> bool { + return (data_ & localized_mask) != 0; + } + FMT_CONSTEXPR void set_localized() { data_ |= localized_mask; } + + constexpr auto fill_size() const -> size_t { + return (data_ & fill_size_mask) >> fill_size_shift; + } + + template ::value)> + constexpr auto fill() const -> const Char* { + return fill_data_; + } + template ::value)> + constexpr auto fill() const -> const Char* { + return nullptr; + } + + template constexpr auto fill_unit() const -> Char { + using uchar = unsigned char; + return static_cast(static_cast(fill_data_[0]) | + (static_cast(fill_data_[1]) << 8) | + (static_cast(fill_data_[2]) << 16)); + } + + FMT_CONSTEXPR void set_fill(char c) { + fill_data_[0] = c; + set_fill_size(1); + } + + template + FMT_CONSTEXPR void set_fill(basic_string_view s) { + auto size = s.size(); + set_fill_size(size); + if (size == 1) { + unsigned uchar = static_cast>(s[0]); + fill_data_[0] = static_cast(uchar); + fill_data_[1] = static_cast(uchar >> 8); + fill_data_[2] = static_cast(uchar >> 16); + return; + } + FMT_ASSERT(size <= max_fill_size, "invalid fill"); + for (size_t i = 0; i < size; ++i) + fill_data_[i & 3] = static_cast(s[i]); + } + + FMT_CONSTEXPR void copy_fill_from(const basic_specs& specs) { + set_fill_size(specs.fill_size()); + for (size_t i = 0; i < max_fill_size; ++i) + fill_data_[i] = specs.fill_data_[i]; + } +}; + +// Format specifiers for built-in and string types. +struct format_specs : basic_specs { + int width; + int precision; + + constexpr format_specs() : width(0), precision(-1) {} +}; + +/** + * Parsing context consisting of a format string range being parsed and an + * argument counter for automatic indexing. + */ +template class parse_context { + private: + basic_string_view fmt_; + int next_arg_id_; + + enum { use_constexpr_cast = !FMT_GCC_VERSION || FMT_GCC_VERSION >= 1200 }; + + FMT_CONSTEXPR void do_check_arg_id(int arg_id); + + public: + using char_type = Char; + using iterator = const Char*; + + constexpr explicit parse_context(basic_string_view fmt, + int next_arg_id = 0) + : fmt_(fmt), next_arg_id_(next_arg_id) {} + + /// Returns an iterator to the beginning of the format string range being + /// parsed. + constexpr auto begin() const noexcept -> iterator { return fmt_.begin(); } + + /// Returns an iterator past the end of the format string range being parsed. + constexpr auto end() const noexcept -> iterator { return fmt_.end(); } + + /// Advances the begin iterator to `it`. + FMT_CONSTEXPR void advance_to(iterator it) { + fmt_.remove_prefix(detail::to_unsigned(it - begin())); + } + + /// Reports an error if using the manual argument indexing; otherwise returns + /// the next argument index and switches to the automatic indexing. + FMT_CONSTEXPR auto next_arg_id() -> int { + if (next_arg_id_ < 0) { + report_error("cannot switch from manual to automatic argument indexing"); + return 0; + } + int id = next_arg_id_++; + do_check_arg_id(id); + return id; + } + + /// Reports an error if using the automatic argument indexing; otherwise + /// switches to the manual indexing. + FMT_CONSTEXPR void check_arg_id(int id) { + if (next_arg_id_ > 0) { + report_error("cannot switch from automatic to manual argument indexing"); + return; + } + next_arg_id_ = -1; + do_check_arg_id(id); + } + FMT_CONSTEXPR void check_arg_id(basic_string_view) { + next_arg_id_ = -1; + } + FMT_CONSTEXPR void check_dynamic_spec(int arg_id); +}; + +FMT_END_EXPORT + +namespace detail { + +// Constructs fmt::basic_string_view from types implicitly convertible +// to it, deducing Char. Explicitly convertible types such as the ones returned +// from FMT_STRING are intentionally excluded. +template ::value)> +constexpr auto to_string_view(const Char* s) -> basic_string_view { + return s; +} +template ::value)> +constexpr auto to_string_view(const T& s) + -> basic_string_view { + return s; +} +template +constexpr auto to_string_view(basic_string_view s) + -> basic_string_view { + return s; +} + +template +struct has_to_string_view : std::false_type {}; +// detail:: is intentional since to_string_view is not an extension point. +template +struct has_to_string_view< + T, void_t()))>> + : std::true_type {}; + +/// String's character (code unit) type. detail:: is intentional to prevent ADL. +template ()))> +using char_t = typename V::value_type; + +enum class type { + none_type, + // Integer types should go first, + int_type, + uint_type, + long_long_type, + ulong_long_type, + int128_type, + uint128_type, + bool_type, + char_type, + last_integer_type = char_type, + // followed by floating-point types. + float_type, + double_type, + long_double_type, + last_numeric_type = long_double_type, + cstring_type, + string_type, + pointer_type, + custom_type +}; + +// Maps core type T to the corresponding type enum constant. +template +struct type_constant : std::integral_constant {}; + +#define FMT_TYPE_CONSTANT(Type, constant) \ + template \ + struct type_constant \ + : std::integral_constant {} + +FMT_TYPE_CONSTANT(int, int_type); +FMT_TYPE_CONSTANT(unsigned, uint_type); +FMT_TYPE_CONSTANT(long long, long_long_type); +FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type); +FMT_TYPE_CONSTANT(int128_opt, int128_type); +FMT_TYPE_CONSTANT(uint128_opt, uint128_type); +FMT_TYPE_CONSTANT(bool, bool_type); +FMT_TYPE_CONSTANT(Char, char_type); +FMT_TYPE_CONSTANT(float, float_type); +FMT_TYPE_CONSTANT(double, double_type); +FMT_TYPE_CONSTANT(long double, long_double_type); +FMT_TYPE_CONSTANT(const Char*, cstring_type); +FMT_TYPE_CONSTANT(basic_string_view, string_type); +FMT_TYPE_CONSTANT(const void*, pointer_type); + +constexpr auto is_integral_type(type t) -> bool { + return t > type::none_type && t <= type::last_integer_type; +} +constexpr auto is_arithmetic_type(type t) -> bool { + return t > type::none_type && t <= type::last_numeric_type; +} + +constexpr auto set(type rhs) -> int { return 1 << static_cast(rhs); } +constexpr auto in(type t, int set) -> bool { + return ((set >> static_cast(t)) & 1) != 0; +} + +// Bitsets of types. +enum { + sint_set = + set(type::int_type) | set(type::long_long_type) | set(type::int128_type), + uint_set = set(type::uint_type) | set(type::ulong_long_type) | + set(type::uint128_type), + bool_set = set(type::bool_type), + char_set = set(type::char_type), + float_set = set(type::float_type) | set(type::double_type) | + set(type::long_double_type), + string_set = set(type::string_type), + cstring_set = set(type::cstring_type), + pointer_set = set(type::pointer_type) +}; + +struct view {}; + +template +struct is_view : std::false_type {}; +template +struct is_view> : std::is_base_of {}; + +template struct named_arg; +template struct is_named_arg : std::false_type {}; +template struct is_static_named_arg : std::false_type {}; + +template +struct is_named_arg> : std::true_type {}; + +template struct named_arg : view { + const Char* name; + const T& value; + + named_arg(const Char* n, const T& v) : name(n), value(v) {} + static_assert(!is_named_arg::value, "nested named arguments"); +}; + +template constexpr auto count() -> int { return B ? 1 : 0; } +template constexpr auto count() -> int { + return (B1 ? 1 : 0) + count(); +} + +template constexpr auto count_named_args() -> int { + return count::value...>(); +} +template constexpr auto count_static_named_args() -> int { + return count::value...>(); +} + +template struct named_arg_info { + const Char* name; + int id; +}; + +// named_args is non-const to suppress a bogus -Wmaybe-uninitalized in gcc 13. +template +FMT_CONSTEXPR void check_for_duplicate(named_arg_info* named_args, + int named_arg_index, + basic_string_view arg_name) { + for (int i = 0; i < named_arg_index; ++i) { + if (named_args[i].name == arg_name) report_error("duplicate named arg"); + } +} + +template ::value)> +void init_named_arg(named_arg_info*, int& arg_index, int&, const T&) { + ++arg_index; +} +template ::value)> +void init_named_arg(named_arg_info* named_args, int& arg_index, + int& named_arg_index, const T& arg) { + check_for_duplicate(named_args, named_arg_index, arg.name); + named_args[named_arg_index++] = {arg.name, arg_index++}; +} + +template ::value)> +FMT_CONSTEXPR void init_static_named_arg(named_arg_info*, int& arg_index, + int&) { + ++arg_index; +} +template ::value)> +FMT_CONSTEXPR void init_static_named_arg(named_arg_info* named_args, + int& arg_index, int& named_arg_index) { + check_for_duplicate(named_args, named_arg_index, T::name); + named_args[named_arg_index++] = {T::name, arg_index++}; +} + +// To minimize the number of types we need to deal with, long is translated +// either to int or to long long depending on its size. +enum { long_short = sizeof(long) == sizeof(int) && FMT_BUILTIN_TYPES }; +using long_type = conditional_t; +using ulong_type = conditional_t; + +template +using format_as_result = + remove_cvref_t()))>; +template +using format_as_member_result = + remove_cvref_t::format_as(std::declval()))>; + +template +struct use_format_as : std::false_type {}; +// format_as member is only used to avoid injection into the std namespace. +template +struct use_format_as_member : std::false_type {}; + +// Only map owning types because mapping views can be unsafe. +template +struct use_format_as< + T, bool_constant>::value>> + : std::true_type {}; +template +struct use_format_as_member< + T, bool_constant>::value>> + : std::true_type {}; + +template > +using use_formatter = + bool_constant<(std::is_class::value || std::is_enum::value || + std::is_union::value || std::is_array::value) && + !has_to_string_view::value && !is_named_arg::value && + !use_format_as::value && !use_format_as_member::value>; + +template > +auto has_formatter_impl(T* p, buffered_context* ctx = nullptr) + -> decltype(formatter().format(*p, *ctx), std::true_type()); +template auto has_formatter_impl(...) -> std::false_type; + +// T can be const-qualified to check if it is const-formattable. +template constexpr auto has_formatter() -> bool { + return decltype(has_formatter_impl(static_cast(nullptr)))::value; +} + +// Maps formatting argument types to natively supported types or user-defined +// types with formatters. Returns void on errors to be SFINAE-friendly. +template struct type_mapper { + static auto map(signed char) -> int; + static auto map(unsigned char) -> unsigned; + static auto map(short) -> int; + static auto map(unsigned short) -> unsigned; + static auto map(int) -> int; + static auto map(unsigned) -> unsigned; + static auto map(long) -> long_type; + static auto map(unsigned long) -> ulong_type; + static auto map(long long) -> long long; + static auto map(unsigned long long) -> unsigned long long; + static auto map(int128_opt) -> int128_opt; + static auto map(uint128_opt) -> uint128_opt; + static auto map(bool) -> bool; + + template + static auto map(bitint) -> conditional_t; + template + static auto map(ubitint) + -> conditional_t; + + template ::value)> + static auto map(T) -> conditional_t< + std::is_same::value || std::is_same::value, Char, void>; + + static auto map(float) -> float; + static auto map(double) -> double; + static auto map(long double) -> long double; + + static auto map(Char*) -> const Char*; + static auto map(const Char*) -> const Char*; + template , + FMT_ENABLE_IF(!std::is_pointer::value)> + static auto map(const T&) -> conditional_t::value, + basic_string_view, void>; + + static auto map(void*) -> const void*; + static auto map(const void*) -> const void*; + static auto map(volatile void*) -> const void*; + static auto map(const volatile void*) -> const void*; + static auto map(nullptr_t) -> const void*; + template ::value || + std::is_member_pointer::value)> + static auto map(const T&) -> void; + + template ::value)> + static auto map(const T& x) -> decltype(map(format_as(x))); + template ::value)> + static auto map(const T& x) -> decltype(map(formatter::format_as(x))); + + template ::value)> + static auto map(T&) -> conditional_t(), T&, void>; + + template ::value)> + static auto map(const T& named_arg) -> decltype(map(named_arg.value)); +}; + +// detail:: is used to workaround a bug in MSVC 2017. +template +using mapped_t = decltype(detail::type_mapper::map(std::declval())); + +// A type constant after applying type_mapper. +template +using mapped_type_constant = type_constant, Char>; + +template ::value> +using stored_type_constant = std::integral_constant< + type, Context::builtin_types || TYPE == type::int_type ? TYPE + : type::custom_type>; +// A parse context with extra data used only in compile-time checks. +template +class compile_parse_context : public parse_context { + private: + int num_args_; + const type* types_; + using base = parse_context; + + public: + FMT_CONSTEXPR explicit compile_parse_context(basic_string_view fmt, + int num_args, const type* types, + int next_arg_id = 0) + : base(fmt, next_arg_id), num_args_(num_args), types_(types) {} + + constexpr auto num_args() const -> int { return num_args_; } + constexpr auto arg_type(int id) const -> type { return types_[id]; } + + FMT_CONSTEXPR auto next_arg_id() -> int { + int id = base::next_arg_id(); + if (id >= num_args_) report_error("argument not found"); + return id; + } + + FMT_CONSTEXPR void check_arg_id(int id) { + base::check_arg_id(id); + if (id >= num_args_) report_error("argument not found"); + } + using base::check_arg_id; + + FMT_CONSTEXPR void check_dynamic_spec(int arg_id) { + ignore_unused(arg_id); + if (arg_id < num_args_ && types_ && !is_integral_type(types_[arg_id])) + report_error("width/precision is not integer"); + } +}; + +// An argument reference. +template union arg_ref { + FMT_CONSTEXPR arg_ref(int idx = 0) : index(idx) {} + FMT_CONSTEXPR arg_ref(basic_string_view n) : name(n) {} + + int index; + basic_string_view name; +}; + +// Format specifiers with width and precision resolved at formatting rather +// than parsing time to allow reusing the same parsed specifiers with +// different sets of arguments (precompilation of format strings). +template struct dynamic_format_specs : format_specs { + arg_ref width_ref; + arg_ref precision_ref; +}; + +// Converts a character to ASCII. Returns '\0' on conversion failure. +template ::value)> +constexpr auto to_ascii(Char c) -> char { + return c <= 0xff ? static_cast(c) : '\0'; +} + +// Returns the number of code units in a code point or 1 on error. +template +FMT_CONSTEXPR auto code_point_length(const Char* begin) -> int { + if (const_check(sizeof(Char) != 1)) return 1; + auto c = static_cast(*begin); + return static_cast((0x3a55000000000000ull >> (2 * (c >> 3))) & 3) + 1; +} + +// Parses the range [begin, end) as an unsigned integer. This function assumes +// that the range is non-empty and the first character is a digit. +template +FMT_CONSTEXPR auto parse_nonnegative_int(const Char*& begin, const Char* end, + int error_value) noexcept -> int { + FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', ""); + unsigned value = 0, prev = 0; + auto p = begin; + do { + prev = value; + value = value * 10 + unsigned(*p - '0'); + ++p; + } while (p != end && '0' <= *p && *p <= '9'); + auto num_digits = p - begin; + begin = p; + int digits10 = static_cast(sizeof(int) * CHAR_BIT * 3 / 10); + if (num_digits <= digits10) return static_cast(value); + // Check for overflow. + unsigned max = INT_MAX; + return num_digits == digits10 + 1 && + prev * 10ull + unsigned(p[-1] - '0') <= max + ? static_cast(value) + : error_value; +} + +FMT_CONSTEXPR inline auto parse_align(char c) -> align { + switch (c) { + case '<': return align::left; + case '>': return align::right; + case '^': return align::center; + } + return align::none; +} + +template constexpr auto is_name_start(Char c) -> bool { + return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '_'; +} + +template +FMT_CONSTEXPR auto parse_arg_id(const Char* begin, const Char* end, + Handler&& handler) -> const Char* { + Char c = *begin; + if (c >= '0' && c <= '9') { + int index = 0; + if (c != '0') + index = parse_nonnegative_int(begin, end, INT_MAX); + else + ++begin; + if (begin == end || (*begin != '}' && *begin != ':')) + report_error("invalid format string"); + else + handler.on_index(index); + return begin; + } + if (FMT_OPTIMIZE_SIZE > 1 || !is_name_start(c)) { + report_error("invalid format string"); + return begin; + } + auto it = begin; + do { + ++it; + } while (it != end && (is_name_start(*it) || ('0' <= *it && *it <= '9'))); + handler.on_name({begin, to_unsigned(it - begin)}); + return it; +} + +template struct dynamic_spec_handler { + parse_context& ctx; + arg_ref& ref; + arg_id_kind& kind; + + FMT_CONSTEXPR void on_index(int id) { + ref = id; + kind = arg_id_kind::index; + ctx.check_arg_id(id); + ctx.check_dynamic_spec(id); + } + FMT_CONSTEXPR void on_name(basic_string_view id) { + ref = id; + kind = arg_id_kind::name; + ctx.check_arg_id(id); + } +}; + +template struct parse_dynamic_spec_result { + const Char* end; + arg_id_kind kind; +}; + +// Parses integer | "{" [arg_id] "}". +template +FMT_CONSTEXPR auto parse_dynamic_spec(const Char* begin, const Char* end, + int& value, arg_ref& ref, + parse_context& ctx) + -> parse_dynamic_spec_result { + FMT_ASSERT(begin != end, ""); + auto kind = arg_id_kind::none; + if ('0' <= *begin && *begin <= '9') { + int val = parse_nonnegative_int(begin, end, -1); + if (val == -1) report_error("number is too big"); + value = val; + } else { + if (*begin == '{') { + ++begin; + if (begin != end) { + Char c = *begin; + if (c == '}' || c == ':') { + int id = ctx.next_arg_id(); + ref = id; + kind = arg_id_kind::index; + ctx.check_dynamic_spec(id); + } else { + begin = parse_arg_id(begin, end, + dynamic_spec_handler{ctx, ref, kind}); + } + } + if (begin != end && *begin == '}') return {++begin, kind}; + } + report_error("invalid format string"); + } + return {begin, kind}; +} + +template +FMT_CONSTEXPR auto parse_width(const Char* begin, const Char* end, + format_specs& specs, arg_ref& width_ref, + parse_context& ctx) -> const Char* { + auto result = parse_dynamic_spec(begin, end, specs.width, width_ref, ctx); + specs.set_dynamic_width(result.kind); + return result.end; +} + +template +FMT_CONSTEXPR auto parse_precision(const Char* begin, const Char* end, + format_specs& specs, + arg_ref& precision_ref, + parse_context& ctx) -> const Char* { + ++begin; + if (begin == end) { + report_error("invalid precision"); + return begin; + } + auto result = + parse_dynamic_spec(begin, end, specs.precision, precision_ref, ctx); + specs.set_dynamic_precision(result.kind); + return result.end; +} + +enum class state { start, align, sign, hash, zero, width, precision, locale }; + +// Parses standard format specifiers. +template +FMT_CONSTEXPR auto parse_format_specs(const Char* begin, const Char* end, + dynamic_format_specs& specs, + parse_context& ctx, type arg_type) + -> const Char* { + auto c = '\0'; + if (end - begin > 1) { + auto next = to_ascii(begin[1]); + c = parse_align(next) == align::none ? to_ascii(*begin) : '\0'; + } else { + if (begin == end) return begin; + c = to_ascii(*begin); + } + + struct { + state current_state = state::start; + FMT_CONSTEXPR void operator()(state s, bool valid = true) { + if (current_state >= s || !valid) + report_error("invalid format specifier"); + current_state = s; + } + } enter_state; + + using pres = presentation_type; + constexpr auto integral_set = sint_set | uint_set | bool_set | char_set; + struct { + const Char*& begin; + format_specs& specs; + type arg_type; + + FMT_CONSTEXPR auto operator()(pres pres_type, int set) -> const Char* { + if (!in(arg_type, set)) report_error("invalid format specifier"); + specs.set_type(pres_type); + return begin + 1; + } + } parse_presentation_type{begin, specs, arg_type}; + + for (;;) { + switch (c) { + case '<': + case '>': + case '^': + enter_state(state::align); + specs.set_align(parse_align(c)); + ++begin; + break; + case '+': + case ' ': + specs.set_sign(c == ' ' ? sign::space : sign::plus); + FMT_FALLTHROUGH; + case '-': + enter_state(state::sign, in(arg_type, sint_set | float_set)); + ++begin; + break; + case '#': + enter_state(state::hash, is_arithmetic_type(arg_type)); + specs.set_alt(); + ++begin; + break; + case '0': + enter_state(state::zero); + if (!is_arithmetic_type(arg_type)) + report_error("format specifier requires numeric argument"); + if (specs.align() == align::none) { + // Ignore 0 if align is specified for compatibility with std::format. + specs.set_align(align::numeric); + specs.set_fill('0'); + } + ++begin; + break; + // clang-format off + case '1': case '2': case '3': case '4': case '5': + case '6': case '7': case '8': case '9': case '{': + // clang-format on + enter_state(state::width); + begin = parse_width(begin, end, specs, specs.width_ref, ctx); + break; + case '.': + enter_state(state::precision, + in(arg_type, float_set | string_set | cstring_set)); + begin = parse_precision(begin, end, specs, specs.precision_ref, ctx); + break; + case 'L': + enter_state(state::locale, is_arithmetic_type(arg_type)); + specs.set_localized(); + ++begin; + break; + case 'd': return parse_presentation_type(pres::dec, integral_set); + case 'X': specs.set_upper(); FMT_FALLTHROUGH; + case 'x': return parse_presentation_type(pres::hex, integral_set); + case 'o': return parse_presentation_type(pres::oct, integral_set); + case 'B': specs.set_upper(); FMT_FALLTHROUGH; + case 'b': return parse_presentation_type(pres::bin, integral_set); + case 'E': specs.set_upper(); FMT_FALLTHROUGH; + case 'e': return parse_presentation_type(pres::exp, float_set); + case 'F': specs.set_upper(); FMT_FALLTHROUGH; + case 'f': return parse_presentation_type(pres::fixed, float_set); + case 'G': specs.set_upper(); FMT_FALLTHROUGH; + case 'g': return parse_presentation_type(pres::general, float_set); + case 'A': specs.set_upper(); FMT_FALLTHROUGH; + case 'a': return parse_presentation_type(pres::hexfloat, float_set); + case 'c': + if (arg_type == type::bool_type) report_error("invalid format specifier"); + return parse_presentation_type(pres::chr, integral_set); + case 's': + return parse_presentation_type(pres::string, + bool_set | string_set | cstring_set); + case 'p': + return parse_presentation_type(pres::pointer, pointer_set | cstring_set); + case '?': + return parse_presentation_type(pres::debug, + char_set | string_set | cstring_set); + case '}': return begin; + default: { + if (*begin == '}') return begin; + // Parse fill and alignment. + auto fill_end = begin + code_point_length(begin); + if (end - fill_end <= 0) { + report_error("invalid format specifier"); + return begin; + } + if (*begin == '{') { + report_error("invalid fill character '{'"); + return begin; + } + auto alignment = parse_align(to_ascii(*fill_end)); + enter_state(state::align, alignment != align::none); + specs.set_fill( + basic_string_view(begin, to_unsigned(fill_end - begin))); + specs.set_align(alignment); + begin = fill_end + 1; + } + } + if (begin == end) return begin; + c = to_ascii(*begin); + } +} + +template +FMT_CONSTEXPR FMT_INLINE auto parse_replacement_field(const Char* begin, + const Char* end, + Handler&& handler) + -> const Char* { + ++begin; + if (begin == end) { + handler.on_error("invalid format string"); + return end; + } + int arg_id = 0; + switch (*begin) { + case '}': + handler.on_replacement_field(handler.on_arg_id(), begin); + return begin + 1; + case '{': handler.on_text(begin, begin + 1); return begin + 1; + case ':': arg_id = handler.on_arg_id(); break; + default: { + struct id_adapter { + Handler& handler; + int arg_id; + + FMT_CONSTEXPR void on_index(int id) { arg_id = handler.on_arg_id(id); } + FMT_CONSTEXPR void on_name(basic_string_view id) { + arg_id = handler.on_arg_id(id); + } + } adapter = {handler, 0}; + begin = parse_arg_id(begin, end, adapter); + arg_id = adapter.arg_id; + Char c = begin != end ? *begin : Char(); + if (c == '}') { + handler.on_replacement_field(arg_id, begin); + return begin + 1; + } + if (c != ':') { + handler.on_error("missing '}' in format string"); + return end; + } + break; + } + } + begin = handler.on_format_specs(arg_id, begin + 1, end); + if (begin == end || *begin != '}') + return handler.on_error("unknown format specifier"), end; + return begin + 1; +} + +template +FMT_CONSTEXPR void parse_format_string(basic_string_view fmt, + Handler&& handler) { + auto begin = fmt.data(), end = begin + fmt.size(); + auto p = begin; + while (p != end) { + auto c = *p++; + if (c == '{') { + handler.on_text(begin, p - 1); + begin = p = parse_replacement_field(p - 1, end, handler); + } else if (c == '}') { + if (p == end || *p != '}') + return handler.on_error("unmatched '}' in format string"); + handler.on_text(begin, p); + begin = ++p; + } + } + handler.on_text(begin, end); +} + +// Checks char specs and returns true iff the presentation type is char-like. +FMT_CONSTEXPR inline auto check_char_specs(const format_specs& specs) -> bool { + auto type = specs.type(); + if (type != presentation_type::none && type != presentation_type::chr && + type != presentation_type::debug) { + return false; + } + if (specs.align() == align::numeric || specs.sign() != sign::none || + specs.alt()) { + report_error("invalid format specifier for char"); + } + return true; +} + +// A base class for compile-time strings. +struct compile_string {}; + +template +FMT_VISIBILITY("hidden") // Suppress an ld warning on macOS (#3769). +FMT_CONSTEXPR auto invoke_parse(parse_context& ctx) -> const Char* { + using mapped_type = remove_cvref_t>; + constexpr bool formattable = + std::is_constructible>::value; + if (!formattable) return ctx.begin(); // Error is reported in the value ctor. + using formatted_type = conditional_t; + return formatter().parse(ctx); +} + +template struct arg_pack {}; + +template +class format_string_checker { + private: + type types_[max_of(1, NUM_ARGS)]; + named_arg_info named_args_[max_of(1, NUM_NAMED_ARGS)]; + compile_parse_context context_; + + using parse_func = auto (*)(parse_context&) -> const Char*; + parse_func parse_funcs_[max_of(1, NUM_ARGS)]; + + public: + template + FMT_CONSTEXPR explicit format_string_checker(basic_string_view fmt, + arg_pack) + : types_{mapped_type_constant::value...}, + named_args_{}, + context_(fmt, NUM_ARGS, types_), + parse_funcs_{&invoke_parse...} { + int arg_index = 0, named_arg_index = 0; + FMT_APPLY_VARIADIC( + init_static_named_arg(named_args_, arg_index, named_arg_index)); + ignore_unused(arg_index, named_arg_index); + } + + FMT_CONSTEXPR void on_text(const Char*, const Char*) {} + + FMT_CONSTEXPR auto on_arg_id() -> int { return context_.next_arg_id(); } + FMT_CONSTEXPR auto on_arg_id(int id) -> int { + context_.check_arg_id(id); + return id; + } + FMT_CONSTEXPR auto on_arg_id(basic_string_view id) -> int { + for (int i = 0; i < NUM_NAMED_ARGS; ++i) { + if (named_args_[i].name == id) return named_args_[i].id; + } + if (!DYNAMIC_NAMES) on_error("argument not found"); + return -1; + } + + FMT_CONSTEXPR void on_replacement_field(int id, const Char* begin) { + on_format_specs(id, begin, begin); // Call parse() on empty specs. + } + + FMT_CONSTEXPR auto on_format_specs(int id, const Char* begin, const Char* end) + -> const Char* { + context_.advance_to(begin); + if (id >= 0 && id < NUM_ARGS) return parse_funcs_[id](context_); + + // If id is out of range, it means we do not know the type and cannot parse + // the format at compile time. Instead, skip over content until we finish + // the format spec, accounting for any nested replacements. + for (int bracket_count = 0; + begin != end && (bracket_count > 0 || *begin != '}'); ++begin) { + if (*begin == '{') + ++bracket_count; + else if (*begin == '}') + --bracket_count; + } + return begin; + } + + FMT_NORETURN FMT_CONSTEXPR void on_error(const char* message) { + report_error(message); + } +}; + +/// A contiguous memory buffer with an optional growing ability. It is an +/// internal class and shouldn't be used directly, only via `memory_buffer`. +template class buffer { + private: + T* ptr_; + size_t size_; + size_t capacity_; + + using grow_fun = void (*)(buffer& buf, size_t capacity); + grow_fun grow_; + + protected: + // Don't initialize ptr_ since it is not accessed to save a few cycles. + FMT_MSC_WARNING(suppress : 26495) + FMT_CONSTEXPR buffer(grow_fun grow, size_t sz) noexcept + : size_(sz), capacity_(sz), grow_(grow) {} + + constexpr buffer(grow_fun grow, T* p = nullptr, size_t sz = 0, + size_t cap = 0) noexcept + : ptr_(p), size_(sz), capacity_(cap), grow_(grow) {} + + FMT_CONSTEXPR20 ~buffer() = default; + buffer(buffer&&) = default; + + /// Sets the buffer data and capacity. + FMT_CONSTEXPR void set(T* buf_data, size_t buf_capacity) noexcept { + ptr_ = buf_data; + capacity_ = buf_capacity; + } + + public: + using value_type = T; + using const_reference = const T&; + + buffer(const buffer&) = delete; + void operator=(const buffer&) = delete; + + auto begin() noexcept -> T* { return ptr_; } + auto end() noexcept -> T* { return ptr_ + size_; } + + auto begin() const noexcept -> const T* { return ptr_; } + auto end() const noexcept -> const T* { return ptr_ + size_; } + + /// Returns the size of this buffer. + constexpr auto size() const noexcept -> size_t { return size_; } + + /// Returns the capacity of this buffer. + constexpr auto capacity() const noexcept -> size_t { return capacity_; } + + /// Returns a pointer to the buffer data (not null-terminated). + FMT_CONSTEXPR auto data() noexcept -> T* { return ptr_; } + FMT_CONSTEXPR auto data() const noexcept -> const T* { return ptr_; } + + /// Clears this buffer. + FMT_CONSTEXPR void clear() { size_ = 0; } + + // Tries resizing the buffer to contain `count` elements. If T is a POD type + // the new elements may not be initialized. + FMT_CONSTEXPR void try_resize(size_t count) { + try_reserve(count); + size_ = min_of(count, capacity_); + } + + // Tries increasing the buffer capacity to `new_capacity`. It can increase the + // capacity by a smaller amount than requested but guarantees there is space + // for at least one additional element either by increasing the capacity or by + // flushing the buffer if it is full. + FMT_CONSTEXPR void try_reserve(size_t new_capacity) { + if (new_capacity > capacity_) grow_(*this, new_capacity); + } + + FMT_CONSTEXPR void push_back(const T& value) { + try_reserve(size_ + 1); + ptr_[size_++] = value; + } + + /// Appends data to the end of the buffer. + template +// Workaround for MSVC2019 to fix error C2893: Failed to specialize function +// template 'void fmt::v11::detail::buffer::append(const U *,const U *)'. +#if !FMT_MSC_VERSION || FMT_MSC_VERSION >= 1940 + FMT_CONSTEXPR20 +#endif + void + append(const U* begin, const U* end) { + while (begin != end) { + auto count = to_unsigned(end - begin); + try_reserve(size_ + count); + auto free_cap = capacity_ - size_; + if (free_cap < count) count = free_cap; + // A loop is faster than memcpy on small sizes. + T* out = ptr_ + size_; + for (size_t i = 0; i < count; ++i) out[i] = begin[i]; + size_ += count; + begin += count; + } + } + + template FMT_CONSTEXPR auto operator[](Idx index) -> T& { + return ptr_[index]; + } + template + FMT_CONSTEXPR auto operator[](Idx index) const -> const T& { + return ptr_[index]; + } +}; + +struct buffer_traits { + constexpr explicit buffer_traits(size_t) {} + constexpr auto count() const -> size_t { return 0; } + constexpr auto limit(size_t size) const -> size_t { return size; } +}; + +class fixed_buffer_traits { + private: + size_t count_ = 0; + size_t limit_; + + public: + constexpr explicit fixed_buffer_traits(size_t limit) : limit_(limit) {} + constexpr auto count() const -> size_t { return count_; } + FMT_CONSTEXPR auto limit(size_t size) -> size_t { + size_t n = limit_ > count_ ? limit_ - count_ : 0; + count_ += size; + return min_of(size, n); + } +}; + +// A buffer that writes to an output iterator when flushed. +template +class iterator_buffer : public Traits, public buffer { + private: + OutputIt out_; + enum { buffer_size = 256 }; + T data_[buffer_size]; + + static FMT_CONSTEXPR void grow(buffer& buf, size_t) { + if (buf.size() == buffer_size) static_cast(buf).flush(); + } + + void flush() { + auto size = this->size(); + this->clear(); + const T* begin = data_; + const T* end = begin + this->limit(size); + while (begin != end) *out_++ = *begin++; + } + + public: + explicit iterator_buffer(OutputIt out, size_t n = buffer_size) + : Traits(n), buffer(grow, data_, 0, buffer_size), out_(out) {} + iterator_buffer(iterator_buffer&& other) noexcept + : Traits(other), + buffer(grow, data_, 0, buffer_size), + out_(other.out_) {} + ~iterator_buffer() { + // Don't crash if flush fails during unwinding. + FMT_TRY { flush(); } + FMT_CATCH(...) {} + } + + auto out() -> OutputIt { + flush(); + return out_; + } + auto count() const -> size_t { return Traits::count() + this->size(); } +}; + +template +class iterator_buffer : public fixed_buffer_traits, + public buffer { + private: + T* out_; + enum { buffer_size = 256 }; + T data_[buffer_size]; + + static FMT_CONSTEXPR void grow(buffer& buf, size_t) { + if (buf.size() == buf.capacity()) + static_cast(buf).flush(); + } + + void flush() { + size_t n = this->limit(this->size()); + if (this->data() == out_) { + out_ += n; + this->set(data_, buffer_size); + } + this->clear(); + } + + public: + explicit iterator_buffer(T* out, size_t n = buffer_size) + : fixed_buffer_traits(n), buffer(grow, out, 0, n), out_(out) {} + iterator_buffer(iterator_buffer&& other) noexcept + : fixed_buffer_traits(other), + buffer(static_cast(other)), + out_(other.out_) { + if (this->data() != out_) { + this->set(data_, buffer_size); + this->clear(); + } + } + ~iterator_buffer() { flush(); } + + auto out() -> T* { + flush(); + return out_; + } + auto count() const -> size_t { + return fixed_buffer_traits::count() + this->size(); + } +}; + +template class iterator_buffer : public buffer { + public: + explicit iterator_buffer(T* out, size_t = 0) + : buffer([](buffer&, size_t) {}, out, 0, ~size_t()) {} + + auto out() -> T* { return &*this->end(); } +}; + +template +class container_buffer : public buffer { + private: + using value_type = typename Container::value_type; + + static FMT_CONSTEXPR void grow(buffer& buf, size_t capacity) { + auto& self = static_cast(buf); + self.container.resize(capacity); + self.set(&self.container[0], capacity); + } + + public: + Container& container; + + explicit container_buffer(Container& c) + : buffer(grow, c.size()), container(c) {} +}; + +// A buffer that writes to a container with the contiguous storage. +template +class iterator_buffer< + OutputIt, + enable_if_t::value && + is_contiguous::value, + typename OutputIt::container_type::value_type>> + : public container_buffer { + private: + using base = container_buffer; + + public: + explicit iterator_buffer(typename OutputIt::container_type& c) : base(c) {} + explicit iterator_buffer(OutputIt out, size_t = 0) + : base(get_container(out)) {} + + auto out() -> OutputIt { return OutputIt(this->container); } +}; + +// A buffer that counts the number of code units written discarding the output. +template class counting_buffer : public buffer { + private: + enum { buffer_size = 256 }; + T data_[buffer_size]; + size_t count_ = 0; + + static FMT_CONSTEXPR void grow(buffer& buf, size_t) { + if (buf.size() != buffer_size) return; + static_cast(buf).count_ += buf.size(); + buf.clear(); + } + + public: + FMT_CONSTEXPR counting_buffer() : buffer(grow, data_, 0, buffer_size) {} + + constexpr auto count() const noexcept -> size_t { + return count_ + this->size(); + } +}; + +template +struct is_back_insert_iterator> : std::true_type {}; + +template +struct has_back_insert_iterator_container_append : std::false_type {}; +template +struct has_back_insert_iterator_container_append< + OutputIt, InputIt, + void_t()) + .append(std::declval(), + std::declval()))>> : std::true_type {}; + +// An optimized version of std::copy with the output value type (T). +template ::value&& + has_back_insert_iterator_container_append< + OutputIt, InputIt>::value)> +FMT_CONSTEXPR20 auto copy(InputIt begin, InputIt end, OutputIt out) + -> OutputIt { + get_container(out).append(begin, end); + return out; +} + +template ::value && + !has_back_insert_iterator_container_append< + OutputIt, InputIt>::value)> +FMT_CONSTEXPR20 auto copy(InputIt begin, InputIt end, OutputIt out) + -> OutputIt { + auto& c = get_container(out); + c.insert(c.end(), begin, end); + return out; +} + +template ::value)> +FMT_CONSTEXPR auto copy(InputIt begin, InputIt end, OutputIt out) -> OutputIt { + while (begin != end) *out++ = static_cast(*begin++); + return out; +} + +template +FMT_CONSTEXPR auto copy(basic_string_view s, OutputIt out) -> OutputIt { + return copy(s.begin(), s.end(), out); +} + +template +struct is_buffer_appender : std::false_type {}; +template +struct is_buffer_appender< + It, bool_constant< + is_back_insert_iterator::value && + std::is_base_of, + typename It::container_type>::value>> + : std::true_type {}; + +// Maps an output iterator to a buffer. +template ::value)> +auto get_buffer(OutputIt out) -> iterator_buffer { + return iterator_buffer(out); +} +template ::value)> +auto get_buffer(OutputIt out) -> buffer& { + return get_container(out); +} + +template +auto get_iterator(Buf& buf, OutputIt) -> decltype(buf.out()) { + return buf.out(); +} +template +auto get_iterator(buffer&, OutputIt out) -> OutputIt { + return out; +} + +// This type is intentionally undefined, only used for errors. +template struct type_is_unformattable_for; + +template struct string_value { + const Char* data; + size_t size; + auto str() const -> basic_string_view { return {data, size}; } +}; + +template struct custom_value { + using char_type = typename Context::char_type; + void* value; + void (*format)(void* arg, parse_context& parse_ctx, Context& ctx); +}; + +template struct named_arg_value { + const named_arg_info* data; + size_t size; +}; + +struct custom_tag {}; + +#if !FMT_BUILTIN_TYPES +# define FMT_BUILTIN , monostate +#else +# define FMT_BUILTIN +#endif + +// A formatting argument value. +template class value { + public: + using char_type = typename Context::char_type; + + union { + monostate no_value; + int int_value; + unsigned uint_value; + long long long_long_value; + unsigned long long ulong_long_value; + int128_opt int128_value; + uint128_opt uint128_value; + bool bool_value; + char_type char_value; + float float_value; + double double_value; + long double long_double_value; + const void* pointer; + string_value string; + custom_value custom; + named_arg_value named_args; + }; + + constexpr FMT_INLINE value() : no_value() {} + constexpr FMT_INLINE value(signed char x) : int_value(x) {} + constexpr FMT_INLINE value(unsigned char x FMT_BUILTIN) : uint_value(x) {} + constexpr FMT_INLINE value(signed short x) : int_value(x) {} + constexpr FMT_INLINE value(unsigned short x FMT_BUILTIN) : uint_value(x) {} + constexpr FMT_INLINE value(int x) : int_value(x) {} + constexpr FMT_INLINE value(unsigned x FMT_BUILTIN) : uint_value(x) {} + FMT_CONSTEXPR FMT_INLINE value(long x FMT_BUILTIN) : value(long_type(x)) {} + FMT_CONSTEXPR FMT_INLINE value(unsigned long x FMT_BUILTIN) + : value(ulong_type(x)) {} + constexpr FMT_INLINE value(long long x FMT_BUILTIN) : long_long_value(x) {} + constexpr FMT_INLINE value(unsigned long long x FMT_BUILTIN) + : ulong_long_value(x) {} + FMT_INLINE value(int128_opt x FMT_BUILTIN) : int128_value(x) {} + FMT_INLINE value(uint128_opt x FMT_BUILTIN) : uint128_value(x) {} + constexpr FMT_INLINE value(bool x FMT_BUILTIN) : bool_value(x) {} + + template + constexpr FMT_INLINE value(bitint x FMT_BUILTIN) : long_long_value(x) { + static_assert(N <= 64, "unsupported _BitInt"); + } + template + constexpr FMT_INLINE value(ubitint x FMT_BUILTIN) : ulong_long_value(x) { + static_assert(N <= 64, "unsupported _BitInt"); + } + + template ::value)> + constexpr FMT_INLINE value(T x FMT_BUILTIN) : char_value(x) { + static_assert( + std::is_same::value || std::is_same::value, + "mixing character types is disallowed"); + } + + constexpr FMT_INLINE value(float x FMT_BUILTIN) : float_value(x) {} + constexpr FMT_INLINE value(double x FMT_BUILTIN) : double_value(x) {} + FMT_INLINE value(long double x FMT_BUILTIN) : long_double_value(x) {} + + FMT_CONSTEXPR FMT_INLINE value(char_type* x FMT_BUILTIN) { + string.data = x; + if (is_constant_evaluated()) string.size = 0; + } + FMT_CONSTEXPR FMT_INLINE value(const char_type* x FMT_BUILTIN) { + string.data = x; + if (is_constant_evaluated()) string.size = 0; + } + template , + FMT_ENABLE_IF(!std::is_pointer::value)> + FMT_CONSTEXPR value(const T& x FMT_BUILTIN) { + static_assert(std::is_same::value, + "mixing character types is disallowed"); + auto sv = to_string_view(x); + string.data = sv.data(); + string.size = sv.size(); + } + FMT_INLINE value(void* x FMT_BUILTIN) : pointer(x) {} + FMT_INLINE value(const void* x FMT_BUILTIN) : pointer(x) {} + FMT_INLINE value(volatile void* x FMT_BUILTIN) + : pointer(const_cast(x)) {} + FMT_INLINE value(const volatile void* x FMT_BUILTIN) + : pointer(const_cast(x)) {} + FMT_INLINE value(nullptr_t) : pointer(nullptr) {} + + template ::value || + std::is_member_pointer::value)> + value(const T&) { + // Formatting of arbitrary pointers is disallowed. If you want to format a + // pointer cast it to `void*` or `const void*`. In particular, this forbids + // formatting of `[const] volatile char*` printed as bool by iostreams. + static_assert(sizeof(T) == 0, + "formatting of non-void pointers is disallowed"); + } + + template ::value)> + value(const T& x) : value(format_as(x)) {} + template ::value)> + value(const T& x) : value(formatter::format_as(x)) {} + + template ::value)> + value(const T& named_arg) : value(named_arg.value) {} + + template ::value || !FMT_BUILTIN_TYPES)> + FMT_CONSTEXPR20 FMT_INLINE value(T& x) : value(x, custom_tag()) {} + + FMT_ALWAYS_INLINE value(const named_arg_info* args, size_t size) + : named_args{args, size} {} + + private: + template ())> + FMT_CONSTEXPR value(T& x, custom_tag) { + using value_type = remove_const_t; + // T may overload operator& e.g. std::vector::reference in libc++. + if (!is_constant_evaluated()) { + custom.value = + const_cast(&reinterpret_cast(x)); + } else { + custom.value = nullptr; +#if defined(__cpp_if_constexpr) + if constexpr (std::is_same*>::value) + custom.value = const_cast(&x); +#endif + } + custom.format = format_custom>; + } + + template ())> + FMT_CONSTEXPR value(const T&, custom_tag) { + // Cannot format an argument; to make type T formattable provide a + // formatter specialization: https://fmt.dev/latest/api.html#udt. + type_is_unformattable_for _; + } + + // Formats an argument of a custom type, such as a user-defined class. + template + static void format_custom(void* arg, parse_context& parse_ctx, + Context& ctx) { + auto f = Formatter(); + parse_ctx.advance_to(f.parse(parse_ctx)); + using qualified_type = + conditional_t(), const T, T>; + // format must be const for compatibility with std::format and compilation. + const auto& cf = f; + ctx.advance_to(cf.format(*static_cast(arg), ctx)); + } +}; + +enum { packed_arg_bits = 4 }; +// Maximum number of arguments with packed types. +enum { max_packed_args = 62 / packed_arg_bits }; +enum : unsigned long long { is_unpacked_bit = 1ULL << 63 }; +enum : unsigned long long { has_named_args_bit = 1ULL << 62 }; + +template +struct is_output_iterator : std::false_type {}; + +template <> struct is_output_iterator : std::true_type {}; + +template +struct is_output_iterator< + It, T, + enable_if_t&>()++), + T>::value>> : std::true_type {}; + +#ifndef FMT_USE_LOCALE +# define FMT_USE_LOCALE (FMT_OPTIMIZE_SIZE <= 1) +#endif + +// A type-erased reference to an std::locale to avoid a heavy include. +class locale_ref { +#if FMT_USE_LOCALE + private: + const void* locale_; // A type-erased pointer to std::locale. + + public: + constexpr locale_ref() : locale_(nullptr) {} + template locale_ref(const Locale& loc); + + inline explicit operator bool() const noexcept { return locale_ != nullptr; } +#endif // FMT_USE_LOCALE + + public: + template auto get() const -> Locale; +}; + +template constexpr auto encode_types() -> unsigned long long { + return 0; +} + +template +constexpr auto encode_types() -> unsigned long long { + return static_cast(stored_type_constant::value) | + (encode_types() << packed_arg_bits); +} + +template +constexpr auto make_descriptor() -> unsigned long long { + return NUM_ARGS <= max_packed_args ? encode_types() + : is_unpacked_bit | NUM_ARGS; +} + +template +using arg_t = conditional_t, + basic_format_arg>; + +template +struct named_arg_store { + // args_[0].named_args points to named_args to avoid bloating format_args. + arg_t args[1 + NUM_ARGS]; + named_arg_info named_args[NUM_NAMED_ARGS]; + + template + FMT_CONSTEXPR FMT_ALWAYS_INLINE named_arg_store(T&... values) + : args{{named_args, NUM_NAMED_ARGS}, values...} { + int arg_index = 0, named_arg_index = 0; + FMT_APPLY_VARIADIC( + init_named_arg(named_args, arg_index, named_arg_index, values)); + } + + named_arg_store(named_arg_store&& rhs) { + args[0] = {named_args, NUM_NAMED_ARGS}; + for (size_t i = 1; i < sizeof(args) / sizeof(*args); ++i) + args[i] = rhs.args[i]; + for (size_t i = 0; i < NUM_NAMED_ARGS; ++i) + named_args[i] = rhs.named_args[i]; + } + + named_arg_store(const named_arg_store& rhs) = delete; + named_arg_store& operator=(const named_arg_store& rhs) = delete; + named_arg_store& operator=(named_arg_store&& rhs) = delete; + operator const arg_t*() const { return args + 1; } +}; + +// An array of references to arguments. It can be implicitly converted to +// `basic_format_args` for passing into type-erased formatting functions +// such as `vformat`. It is a plain struct to reduce binary size in debug mode. +template +struct format_arg_store { + // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning. + using type = + conditional_t[max_of(1, NUM_ARGS)], + named_arg_store>; + type args; +}; + +// TYPE can be different from type_constant, e.g. for __float128. +template struct native_formatter { + private: + dynamic_format_specs specs_; + + public: + using nonlocking = void; + + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + if (ctx.begin() == ctx.end() || *ctx.begin() == '}') return ctx.begin(); + auto end = parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, TYPE); + if (const_check(TYPE == type::char_type)) check_char_specs(specs_); + return end; + } + + template + FMT_CONSTEXPR void set_debug_format(bool set = true) { + specs_.set_type(set ? presentation_type::debug : presentation_type::none); + } + + FMT_PRAGMA_CLANG(diagnostic ignored "-Wundefined-inline") + template + FMT_CONSTEXPR auto format(const T& val, FormatContext& ctx) const + -> decltype(ctx.out()); +}; + +template +struct locking + : bool_constant::value == type::custom_type> {}; +template +struct locking>::nonlocking>> + : std::false_type {}; + +template FMT_CONSTEXPR inline auto is_locking() -> bool { + return locking::value; +} +template +FMT_CONSTEXPR inline auto is_locking() -> bool { + return locking::value || is_locking(); +} + +FMT_API void vformat_to(buffer& buf, string_view fmt, format_args args, + locale_ref loc = {}); + +#if FMT_WIN32 +FMT_API void vprint_mojibake(FILE*, string_view, format_args, bool); +#else // format_args is passed by reference since it is defined later. +inline void vprint_mojibake(FILE*, string_view, const format_args&, bool) {} +#endif +} // namespace detail + +// The main public API. + +template +FMT_CONSTEXPR void parse_context::do_check_arg_id(int arg_id) { + // Argument id is only checked at compile time during parsing because + // formatting has its own validation. + if (detail::is_constant_evaluated() && use_constexpr_cast) { + auto ctx = static_cast*>(this); + if (arg_id >= ctx->num_args()) report_error("argument not found"); + } +} + +template +FMT_CONSTEXPR void parse_context::check_dynamic_spec(int arg_id) { + using detail::compile_parse_context; + if (detail::is_constant_evaluated() && use_constexpr_cast) + static_cast*>(this)->check_dynamic_spec(arg_id); +} + +FMT_BEGIN_EXPORT + +// An output iterator that appends to a buffer. It is used instead of +// back_insert_iterator to reduce symbol sizes and avoid dependency. +template class basic_appender { + protected: + detail::buffer* container; + + public: + using container_type = detail::buffer; + + FMT_CONSTEXPR basic_appender(detail::buffer& buf) : container(&buf) {} + + FMT_CONSTEXPR20 auto operator=(T c) -> basic_appender& { + container->push_back(c); + return *this; + } + FMT_CONSTEXPR20 auto operator*() -> basic_appender& { return *this; } + FMT_CONSTEXPR20 auto operator++() -> basic_appender& { return *this; } + FMT_CONSTEXPR20 auto operator++(int) -> basic_appender { return *this; } +}; + +// A formatting argument. Context is a template parameter for the compiled API +// where output can be unbuffered. +template class basic_format_arg { + private: + detail::value value_; + detail::type type_; + + friend class basic_format_args; + + using char_type = typename Context::char_type; + + public: + class handle { + private: + detail::custom_value custom_; + + public: + explicit handle(detail::custom_value custom) : custom_(custom) {} + + void format(parse_context& parse_ctx, Context& ctx) const { + custom_.format(custom_.value, parse_ctx, ctx); + } + }; + + constexpr basic_format_arg() : type_(detail::type::none_type) {} + basic_format_arg(const detail::named_arg_info* args, size_t size) + : value_(args, size) {} + template + basic_format_arg(T&& val) + : value_(val), type_(detail::stored_type_constant::value) {} + + constexpr explicit operator bool() const noexcept { + return type_ != detail::type::none_type; + } + auto type() const -> detail::type { return type_; } + + /** + * Visits an argument dispatching to the appropriate visit method based on + * the argument type. For example, if the argument type is `double` then + * `vis(value)` will be called with the value of type `double`. + */ + template + FMT_CONSTEXPR FMT_INLINE auto visit(Visitor&& vis) const -> decltype(vis(0)) { + using detail::map; + switch (type_) { + case detail::type::none_type: break; + case detail::type::int_type: return vis(value_.int_value); + case detail::type::uint_type: return vis(value_.uint_value); + case detail::type::long_long_type: return vis(value_.long_long_value); + case detail::type::ulong_long_type: return vis(value_.ulong_long_value); + case detail::type::int128_type: return vis(map(value_.int128_value)); + case detail::type::uint128_type: return vis(map(value_.uint128_value)); + case detail::type::bool_type: return vis(value_.bool_value); + case detail::type::char_type: return vis(value_.char_value); + case detail::type::float_type: return vis(value_.float_value); + case detail::type::double_type: return vis(value_.double_value); + case detail::type::long_double_type: return vis(value_.long_double_value); + case detail::type::cstring_type: return vis(value_.string.data); + case detail::type::string_type: return vis(value_.string.str()); + case detail::type::pointer_type: return vis(value_.pointer); + case detail::type::custom_type: return vis(handle(value_.custom)); + } + return vis(monostate()); + } + + auto format_custom(const char_type* parse_begin, + parse_context& parse_ctx, Context& ctx) + -> bool { + if (type_ != detail::type::custom_type) return false; + parse_ctx.advance_to(parse_begin); + value_.custom.format(value_.custom.value, parse_ctx, ctx); + return true; + } +}; + +/** + * A view of a collection of formatting arguments. To avoid lifetime issues it + * should only be used as a parameter type in type-erased functions such as + * `vformat`: + * + * void vlog(fmt::string_view fmt, fmt::format_args args); // OK + * fmt::format_args args = fmt::make_format_args(); // Dangling reference + */ +template class basic_format_args { + private: + // A descriptor that contains information about formatting arguments. + // If the number of arguments is less or equal to max_packed_args then + // argument types are passed in the descriptor. This reduces binary code size + // per formatting function call. + unsigned long long desc_; + union { + // If is_packed() returns true then argument values are stored in values_; + // otherwise they are stored in args_. This is done to improve cache + // locality and reduce compiled code size since storing larger objects + // may require more code (at least on x86-64) even if the same amount of + // data is actually copied to stack. It saves ~10% on the bloat test. + const detail::value* values_; + const basic_format_arg* args_; + }; + + constexpr auto is_packed() const -> bool { + return (desc_ & detail::is_unpacked_bit) == 0; + } + constexpr auto has_named_args() const -> bool { + return (desc_ & detail::has_named_args_bit) != 0; + } + + FMT_CONSTEXPR auto type(int index) const -> detail::type { + int shift = index * detail::packed_arg_bits; + unsigned mask = (1 << detail::packed_arg_bits) - 1; + return static_cast((desc_ >> shift) & mask); + } + + template + using store = + detail::format_arg_store; + + public: + using format_arg = basic_format_arg; + + constexpr basic_format_args() : desc_(0), args_(nullptr) {} + + /// Constructs a `basic_format_args` object from `format_arg_store`. + template + constexpr FMT_ALWAYS_INLINE basic_format_args( + const store& s) + : desc_(DESC | (NUM_NAMED_ARGS != 0 ? +detail::has_named_args_bit : 0)), + values_(s.args) {} + + template detail::max_packed_args)> + constexpr basic_format_args(const store& s) + : desc_(DESC | (NUM_NAMED_ARGS != 0 ? +detail::has_named_args_bit : 0)), + args_(s.args) {} + + /// Constructs a `basic_format_args` object from a dynamic list of arguments. + constexpr basic_format_args(const format_arg* args, int count, + bool has_named = false) + : desc_(detail::is_unpacked_bit | detail::to_unsigned(count) | + (has_named ? +detail::has_named_args_bit : 0)), + args_(args) {} + + /// Returns the argument with the specified id. + FMT_CONSTEXPR auto get(int id) const -> format_arg { + auto arg = format_arg(); + if (!is_packed()) { + if (id < max_size()) arg = args_[id]; + return arg; + } + if (static_cast(id) >= detail::max_packed_args) return arg; + arg.type_ = type(id); + if (arg.type_ != detail::type::none_type) arg.value_ = values_[id]; + return arg; + } + + template + auto get(basic_string_view name) const -> format_arg { + int id = get_id(name); + return id >= 0 ? get(id) : format_arg(); + } + + template + FMT_CONSTEXPR auto get_id(basic_string_view name) const -> int { + if (!has_named_args()) return -1; + const auto& named_args = + (is_packed() ? values_[-1] : args_[-1].value_).named_args; + for (size_t i = 0; i < named_args.size; ++i) { + if (named_args.data[i].name == name) return named_args.data[i].id; + } + return -1; + } + + auto max_size() const -> int { + unsigned long long max_packed = detail::max_packed_args; + return static_cast(is_packed() ? max_packed + : desc_ & ~detail::is_unpacked_bit); + } +}; + +// A formatting context. +class context { + private: + appender out_; + format_args args_; + FMT_NO_UNIQUE_ADDRESS detail::locale_ref loc_; + + public: + /// The character type for the output. + using char_type = char; + + using iterator = appender; + using format_arg = basic_format_arg; + using parse_context_type FMT_DEPRECATED = parse_context<>; + template using formatter_type FMT_DEPRECATED = formatter; + enum { builtin_types = FMT_BUILTIN_TYPES }; + + /// Constructs a `context` object. References to the arguments are stored + /// in the object so make sure they have appropriate lifetimes. + FMT_CONSTEXPR context(iterator out, format_args args, + detail::locale_ref loc = {}) + : out_(out), args_(args), loc_(loc) {} + context(context&&) = default; + context(const context&) = delete; + void operator=(const context&) = delete; + + FMT_CONSTEXPR auto arg(int id) const -> format_arg { return args_.get(id); } + inline auto arg(string_view name) const -> format_arg { + return args_.get(name); + } + FMT_CONSTEXPR auto arg_id(string_view name) const -> int { + return args_.get_id(name); + } + auto args() const -> const format_args& { return args_; } + + // Returns an iterator to the beginning of the output range. + FMT_CONSTEXPR auto out() const -> iterator { return out_; } + + // Advances the begin iterator to `it`. + FMT_CONSTEXPR void advance_to(iterator) {} + + FMT_CONSTEXPR auto locale() const -> detail::locale_ref { return loc_; } +}; + +template struct runtime_format_string { + basic_string_view str; +}; + +/** + * Creates a runtime format string. + * + * **Example**: + * + * // Check format string at runtime instead of compile-time. + * fmt::print(fmt::runtime("{:d}"), "I am not a number"); + */ +inline auto runtime(string_view s) -> runtime_format_string<> { return {{s}}; } + +/// A compile-time format string. Use `format_string` in the public API to +/// prevent type deduction. +template struct fstring { + private: + static constexpr int num_static_named_args = + detail::count_static_named_args(); + + using checker = detail::format_string_checker< + char, static_cast(sizeof...(T)), num_static_named_args, + num_static_named_args != detail::count_named_args()>; + + using arg_pack = detail::arg_pack; + + public: + string_view str; + using t = fstring; + + // Reports a compile-time error if S is not a valid format string for T. + template + FMT_CONSTEVAL FMT_ALWAYS_INLINE fstring(const char (&s)[N]) : str(s, N - 1) { + using namespace detail; + static_assert(count<(is_view>::value && + std::is_reference::value)...>() == 0, + "passing views as lvalues is disallowed"); + if (FMT_USE_CONSTEVAL) parse_format_string(s, checker(s, arg_pack())); +#ifdef FMT_ENFORCE_COMPILE_STRING + static_assert( + FMT_USE_CONSTEVAL && sizeof(s) != 0, + "FMT_ENFORCE_COMPILE_STRING requires format strings to use FMT_STRING"); +#endif + } + template ::value)> + FMT_CONSTEVAL FMT_ALWAYS_INLINE fstring(const S& s) : str(s) { + auto sv = string_view(str); + if (FMT_USE_CONSTEVAL) + detail::parse_format_string(sv, checker(sv, arg_pack())); +#ifdef FMT_ENFORCE_COMPILE_STRING + static_assert( + FMT_USE_CONSTEVAL && sizeof(s) != 0, + "FMT_ENFORCE_COMPILE_STRING requires format strings to use FMT_STRING"); +#endif + } + template ::value&& + std::is_same::value)> + FMT_ALWAYS_INLINE fstring(const S&) : str(S()) { + FMT_CONSTEXPR auto sv = string_view(S()); + FMT_CONSTEXPR int unused = + (parse_format_string(sv, checker(sv, arg_pack())), 0); + detail::ignore_unused(unused); + } + fstring(runtime_format_string<> fmt) : str(fmt.str) {} + + // Returning by reference generates better code in debug mode. + FMT_ALWAYS_INLINE operator const string_view&() const { return str; } + auto get() const -> string_view { return str; } +}; + +template using format_string = typename fstring::t; + +template +using is_formattable = bool_constant::value, int*, T>, Char>, + void>::value>; +#ifdef __cpp_concepts +template +concept formattable = is_formattable, Char>::value; +#endif + +template +using has_formatter FMT_DEPRECATED = std::is_constructible>; + +// A formatter specialization for natively supported types. +template +struct formatter::value != + detail::type::custom_type>> + : detail::native_formatter::value> { +}; + +/** + * Constructs an object that stores references to arguments and can be + * implicitly converted to `format_args`. `Context` can be omitted in which case + * it defaults to `context`. See `arg` for lifetime considerations. + */ +// Take arguments by lvalue references to avoid some lifetime issues, e.g. +// auto args = make_format_args(std::string()); +template (), + unsigned long long DESC = detail::make_descriptor()> +constexpr FMT_ALWAYS_INLINE auto make_format_args(T&... args) + -> detail::format_arg_store { + // Suppress warnings for pathological types convertible to detail::value. + FMT_PRAGMA_GCC(diagnostic ignored "-Wconversion") + return {{args...}}; +} + +template +using vargs = + detail::format_arg_store(), + detail::make_descriptor()>; + +/** + * Returns a named argument to be used in a formatting function. + * It should only be used in a call to a formatting function. + * + * **Example**: + * + * fmt::print("The answer is {answer}.", fmt::arg("answer", 42)); + */ +template +inline auto arg(const Char* name, const T& arg) -> detail::named_arg { + return {name, arg}; +} + +/// Formats a string and writes the output to `out`. +template , + char>::value)> +auto vformat_to(OutputIt&& out, string_view fmt, format_args args) + -> remove_cvref_t { + auto&& buf = detail::get_buffer(out); + detail::vformat_to(buf, fmt, args, {}); + return detail::get_iterator(buf, out); +} + +/** + * Formats `args` according to specifications in `fmt`, writes the result to + * the output iterator `out` and returns the iterator past the end of the output + * range. `format_to` does not append a terminating null character. + * + * **Example**: + * + * auto out = std::vector(); + * fmt::format_to(std::back_inserter(out), "{}", 42); + */ +template , + char>::value)> +FMT_INLINE auto format_to(OutputIt&& out, format_string fmt, T&&... args) + -> remove_cvref_t { + return vformat_to(out, fmt.str, vargs{{args...}}); +} + +template struct format_to_n_result { + /// Iterator past the end of the output range. + OutputIt out; + /// Total (not truncated) output size. + size_t size; +}; + +template ::value)> +auto vformat_to_n(OutputIt out, size_t n, string_view fmt, format_args args) + -> format_to_n_result { + using traits = detail::fixed_buffer_traits; + auto buf = detail::iterator_buffer(out, n); + detail::vformat_to(buf, fmt, args, {}); + return {buf.out(), buf.count()}; +} + +/** + * Formats `args` according to specifications in `fmt`, writes up to `n` + * characters of the result to the output iterator `out` and returns the total + * (not truncated) output size and the iterator past the end of the output + * range. `format_to_n` does not append a terminating null character. + */ +template ::value)> +FMT_INLINE auto format_to_n(OutputIt out, size_t n, format_string fmt, + T&&... args) -> format_to_n_result { + return vformat_to_n(out, n, fmt.str, vargs{{args...}}); +} + +struct format_to_result { + /// Pointer to just after the last successful write in the array. + char* out; + /// Specifies if the output was truncated. + bool truncated; + + FMT_CONSTEXPR operator char*() const { + // Report truncation to prevent silent data loss. + if (truncated) report_error("output is truncated"); + return out; + } +}; + +template +auto vformat_to(char (&out)[N], string_view fmt, format_args args) + -> format_to_result { + auto result = vformat_to_n(out, N, fmt, args); + return {result.out, result.size > N}; +} + +template +FMT_INLINE auto format_to(char (&out)[N], format_string fmt, T&&... args) + -> format_to_result { + auto result = vformat_to_n(out, N, fmt.str, vargs{{args...}}); + return {result.out, result.size > N}; +} + +/// Returns the number of chars in the output of `format(fmt, args...)`. +template +FMT_NODISCARD FMT_INLINE auto formatted_size(format_string fmt, + T&&... args) -> size_t { + auto buf = detail::counting_buffer<>(); + detail::vformat_to(buf, fmt.str, vargs{{args...}}, {}); + return buf.count(); +} + +FMT_API void vprint(string_view fmt, format_args args); +FMT_API void vprint(FILE* f, string_view fmt, format_args args); +FMT_API void vprintln(FILE* f, string_view fmt, format_args args); +FMT_API void vprint_buffered(FILE* f, string_view fmt, format_args args); + +/** + * Formats `args` according to specifications in `fmt` and writes the output + * to `stdout`. + * + * **Example**: + * + * fmt::print("The answer is {}.", 42); + */ +template +FMT_INLINE void print(format_string fmt, T&&... args) { + vargs va = {{args...}}; + if (detail::const_check(!detail::use_utf8)) + return detail::vprint_mojibake(stdout, fmt.str, va, false); + return detail::is_locking() ? vprint_buffered(stdout, fmt.str, va) + : vprint(fmt.str, va); +} + +/** + * Formats `args` according to specifications in `fmt` and writes the + * output to the file `f`. + * + * **Example**: + * + * fmt::print(stderr, "Don't {}!", "panic"); + */ +template +FMT_INLINE void print(FILE* f, format_string fmt, T&&... args) { + vargs va = {{args...}}; + if (detail::const_check(!detail::use_utf8)) + return detail::vprint_mojibake(f, fmt.str, va, false); + return detail::is_locking() ? vprint_buffered(f, fmt.str, va) + : vprint(f, fmt.str, va); +} + +/// Formats `args` according to specifications in `fmt` and writes the output +/// to the file `f` followed by a newline. +template +FMT_INLINE void println(FILE* f, format_string fmt, T&&... args) { + vargs va = {{args...}}; + return detail::const_check(detail::use_utf8) + ? vprintln(f, fmt.str, va) + : detail::vprint_mojibake(f, fmt.str, va, true); +} + +/// Formats `args` according to specifications in `fmt` and writes the output +/// to `stdout` followed by a newline. +template +FMT_INLINE void println(format_string fmt, T&&... args) { + return fmt::println(stdout, fmt, static_cast(args)...); +} + +FMT_END_EXPORT +FMT_PRAGMA_CLANG(diagnostic pop) +FMT_PRAGMA_GCC(pop_options) +FMT_END_NAMESPACE + +#ifdef FMT_HEADER_ONLY +# include "format.h" +#endif +#endif // FMT_BASE_H_ diff --git a/sdk/samples/asrun/vendor/fmt/format-inl.h b/sdk/samples/asrun/vendor/fmt/format-inl.h new file mode 100644 index 000000000..a1e016611 --- /dev/null +++ b/sdk/samples/asrun/vendor/fmt/format-inl.h @@ -0,0 +1,1948 @@ +// Formatting library for C++ - implementation +// +// Copyright (c) 2012 - 2016, Victor Zverovich +// All rights reserved. +// +// For the license information refer to format.h. + +#ifndef FMT_FORMAT_INL_H_ +#define FMT_FORMAT_INL_H_ + +#ifndef FMT_MODULE +# include +# include // errno +# include +# include +# include +#endif + +#if defined(_WIN32) && !defined(FMT_USE_WRITE_CONSOLE) +# include // _isatty +#endif + +#include "format.h" + +#if FMT_USE_LOCALE +# include +#endif + +#ifndef FMT_FUNC +# define FMT_FUNC +#endif + +FMT_BEGIN_NAMESPACE +namespace detail { + +FMT_FUNC void assert_fail(const char* file, int line, const char* message) { + // Use unchecked std::fprintf to avoid triggering another assertion when + // writing to stderr fails. + fprintf(stderr, "%s:%d: assertion failed: %s", file, line, message); + abort(); +} + +FMT_FUNC void format_error_code(detail::buffer& out, int error_code, + string_view message) noexcept { + // Report error code making sure that the output fits into + // inline_buffer_size to avoid dynamic memory allocation and potential + // bad_alloc. + out.try_resize(0); + static const char SEP[] = ": "; + static const char ERROR_STR[] = "error "; + // Subtract 2 to account for terminating null characters in SEP and ERROR_STR. + size_t error_code_size = sizeof(SEP) + sizeof(ERROR_STR) - 2; + auto abs_value = static_cast>(error_code); + if (detail::is_negative(error_code)) { + abs_value = 0 - abs_value; + ++error_code_size; + } + error_code_size += detail::to_unsigned(detail::count_digits(abs_value)); + auto it = appender(out); + if (message.size() <= inline_buffer_size - error_code_size) + fmt::format_to(it, FMT_STRING("{}{}"), message, SEP); + fmt::format_to(it, FMT_STRING("{}{}"), ERROR_STR, error_code); + FMT_ASSERT(out.size() <= inline_buffer_size, ""); +} + +FMT_FUNC void do_report_error(format_func func, int error_code, + const char* message) noexcept { + memory_buffer full_message; + func(full_message, error_code, message); + // Don't use fwrite_all because the latter may throw. + if (std::fwrite(full_message.data(), full_message.size(), 1, stderr) > 0) + std::fputc('\n', stderr); +} + +// A wrapper around fwrite that throws on error. +inline void fwrite_all(const void* ptr, size_t count, FILE* stream) { + size_t written = std::fwrite(ptr, 1, count, stream); + if (written < count) + FMT_THROW(system_error(errno, FMT_STRING("cannot write to file"))); +} + +#if FMT_USE_LOCALE +using std::locale; +using std::numpunct; +using std::use_facet; + +template +locale_ref::locale_ref(const Locale& loc) : locale_(&loc) { + static_assert(std::is_same::value, ""); +} +#else +struct locale {}; +template struct numpunct { + auto grouping() const -> std::string { return "\03"; } + auto thousands_sep() const -> Char { return ','; } + auto decimal_point() const -> Char { return '.'; } +}; +template Facet use_facet(locale) { return {}; } +#endif // FMT_USE_LOCALE + +template auto locale_ref::get() const -> Locale { + static_assert(std::is_same::value, ""); +#if FMT_USE_LOCALE + if (locale_) return *static_cast(locale_); +#endif + return locale(); +} + +template +FMT_FUNC auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result { + auto&& facet = use_facet>(loc.get()); + auto grouping = facet.grouping(); + auto thousands_sep = grouping.empty() ? Char() : facet.thousands_sep(); + return {std::move(grouping), thousands_sep}; +} +template +FMT_FUNC auto decimal_point_impl(locale_ref loc) -> Char { + return use_facet>(loc.get()).decimal_point(); +} + +#if FMT_USE_LOCALE +FMT_FUNC auto write_loc(appender out, loc_value value, + const format_specs& specs, locale_ref loc) -> bool { + auto locale = loc.get(); + // We cannot use the num_put facet because it may produce output in + // a wrong encoding. + using facet = format_facet; + if (std::has_facet(locale)) + return use_facet(locale).put(out, value, specs); + return facet(locale).put(out, value, specs); +} +#endif +} // namespace detail + +FMT_FUNC void report_error(const char* message) { +#if FMT_USE_EXCEPTIONS + // Use FMT_THROW instead of throw to avoid bogus unreachable code warnings + // from MSVC. + FMT_THROW(format_error(message)); +#else + fputs(message, stderr); + abort(); +#endif +} + +template typename Locale::id format_facet::id; + +template format_facet::format_facet(Locale& loc) { + auto& np = detail::use_facet>(loc); + grouping_ = np.grouping(); + if (!grouping_.empty()) separator_ = std::string(1, np.thousands_sep()); +} + +#if FMT_USE_LOCALE +template <> +FMT_API FMT_FUNC auto format_facet::do_put( + appender out, loc_value val, const format_specs& specs) const -> bool { + return val.visit( + detail::loc_writer<>{out, specs, separator_, grouping_, decimal_point_}); +} +#endif + +FMT_FUNC auto vsystem_error(int error_code, string_view fmt, format_args args) + -> std::system_error { + auto ec = std::error_code(error_code, std::generic_category()); + return std::system_error(ec, vformat(fmt, args)); +} + +namespace detail { + +template +inline auto operator==(basic_fp x, basic_fp y) -> bool { + return x.f == y.f && x.e == y.e; +} + +// Compilers should be able to optimize this into the ror instruction. +FMT_CONSTEXPR inline auto rotr(uint32_t n, uint32_t r) noexcept -> uint32_t { + r &= 31; + return (n >> r) | (n << (32 - r)); +} +FMT_CONSTEXPR inline auto rotr(uint64_t n, uint32_t r) noexcept -> uint64_t { + r &= 63; + return (n >> r) | (n << (64 - r)); +} + +// Implementation of Dragonbox algorithm: https://github.com/jk-jeon/dragonbox. +namespace dragonbox { +// Computes upper 64 bits of multiplication of a 32-bit unsigned integer and a +// 64-bit unsigned integer. +inline auto umul96_upper64(uint32_t x, uint64_t y) noexcept -> uint64_t { + return umul128_upper64(static_cast(x) << 32, y); +} + +// Computes lower 128 bits of multiplication of a 64-bit unsigned integer and a +// 128-bit unsigned integer. +inline auto umul192_lower128(uint64_t x, uint128_fallback y) noexcept + -> uint128_fallback { + uint64_t high = x * y.high(); + uint128_fallback high_low = umul128(x, y.low()); + return {high + high_low.high(), high_low.low()}; +} + +// Computes lower 64 bits of multiplication of a 32-bit unsigned integer and a +// 64-bit unsigned integer. +inline auto umul96_lower64(uint32_t x, uint64_t y) noexcept -> uint64_t { + return x * y; +} + +// Various fast log computations. +inline auto floor_log10_pow2_minus_log10_4_over_3(int e) noexcept -> int { + FMT_ASSERT(e <= 2936 && e >= -2985, "too large exponent"); + return (e * 631305 - 261663) >> 21; +} + +FMT_INLINE_VARIABLE constexpr struct div_small_pow10_infos_struct { + uint32_t divisor; + int shift_amount; +} div_small_pow10_infos[] = {{10, 16}, {100, 16}}; + +// Replaces n by floor(n / pow(10, N)) returning true if and only if n is +// divisible by pow(10, N). +// Precondition: n <= pow(10, N + 1). +template +auto check_divisibility_and_divide_by_pow10(uint32_t& n) noexcept -> bool { + // The numbers below are chosen such that: + // 1. floor(n/d) = floor(nm / 2^k) where d=10 or d=100, + // 2. nm mod 2^k < m if and only if n is divisible by d, + // where m is magic_number, k is shift_amount + // and d is divisor. + // + // Item 1 is a common technique of replacing division by a constant with + // multiplication, see e.g. "Division by Invariant Integers Using + // Multiplication" by Granlund and Montgomery (1994). magic_number (m) is set + // to ceil(2^k/d) for large enough k. + // The idea for item 2 originates from Schubfach. + constexpr auto info = div_small_pow10_infos[N - 1]; + FMT_ASSERT(n <= info.divisor * 10, "n is too large"); + constexpr uint32_t magic_number = + (1u << info.shift_amount) / info.divisor + 1; + n *= magic_number; + const uint32_t comparison_mask = (1u << info.shift_amount) - 1; + bool result = (n & comparison_mask) < magic_number; + n >>= info.shift_amount; + return result; +} + +// Computes floor(n / pow(10, N)) for small n and N. +// Precondition: n <= pow(10, N + 1). +template auto small_division_by_pow10(uint32_t n) noexcept -> uint32_t { + constexpr auto info = div_small_pow10_infos[N - 1]; + FMT_ASSERT(n <= info.divisor * 10, "n is too large"); + constexpr uint32_t magic_number = + (1u << info.shift_amount) / info.divisor + 1; + return (n * magic_number) >> info.shift_amount; +} + +// Computes floor(n / 10^(kappa + 1)) (float) +inline auto divide_by_10_to_kappa_plus_1(uint32_t n) noexcept -> uint32_t { + // 1374389535 = ceil(2^37/100) + return static_cast((static_cast(n) * 1374389535) >> 37); +} +// Computes floor(n / 10^(kappa + 1)) (double) +inline auto divide_by_10_to_kappa_plus_1(uint64_t n) noexcept -> uint64_t { + // 2361183241434822607 = ceil(2^(64+7)/1000) + return umul128_upper64(n, 2361183241434822607ull) >> 7; +} + +// Various subroutines using pow10 cache +template struct cache_accessor; + +template <> struct cache_accessor { + using carrier_uint = float_info::carrier_uint; + using cache_entry_type = uint64_t; + + static auto get_cached_power(int k) noexcept -> uint64_t { + FMT_ASSERT(k >= float_info::min_k && k <= float_info::max_k, + "k is out of range"); + static constexpr const uint64_t pow10_significands[] = { + 0x81ceb32c4b43fcf5, 0xa2425ff75e14fc32, 0xcad2f7f5359a3b3f, + 0xfd87b5f28300ca0e, 0x9e74d1b791e07e49, 0xc612062576589ddb, + 0xf79687aed3eec552, 0x9abe14cd44753b53, 0xc16d9a0095928a28, + 0xf1c90080baf72cb2, 0x971da05074da7bef, 0xbce5086492111aeb, + 0xec1e4a7db69561a6, 0x9392ee8e921d5d08, 0xb877aa3236a4b44a, + 0xe69594bec44de15c, 0x901d7cf73ab0acda, 0xb424dc35095cd810, + 0xe12e13424bb40e14, 0x8cbccc096f5088cc, 0xafebff0bcb24aaff, + 0xdbe6fecebdedd5bf, 0x89705f4136b4a598, 0xabcc77118461cefd, + 0xd6bf94d5e57a42bd, 0x8637bd05af6c69b6, 0xa7c5ac471b478424, + 0xd1b71758e219652c, 0x83126e978d4fdf3c, 0xa3d70a3d70a3d70b, + 0xcccccccccccccccd, 0x8000000000000000, 0xa000000000000000, + 0xc800000000000000, 0xfa00000000000000, 0x9c40000000000000, + 0xc350000000000000, 0xf424000000000000, 0x9896800000000000, + 0xbebc200000000000, 0xee6b280000000000, 0x9502f90000000000, + 0xba43b74000000000, 0xe8d4a51000000000, 0x9184e72a00000000, + 0xb5e620f480000000, 0xe35fa931a0000000, 0x8e1bc9bf04000000, + 0xb1a2bc2ec5000000, 0xde0b6b3a76400000, 0x8ac7230489e80000, + 0xad78ebc5ac620000, 0xd8d726b7177a8000, 0x878678326eac9000, + 0xa968163f0a57b400, 0xd3c21bcecceda100, 0x84595161401484a0, + 0xa56fa5b99019a5c8, 0xcecb8f27f4200f3a, 0x813f3978f8940985, + 0xa18f07d736b90be6, 0xc9f2c9cd04674edf, 0xfc6f7c4045812297, + 0x9dc5ada82b70b59e, 0xc5371912364ce306, 0xf684df56c3e01bc7, + 0x9a130b963a6c115d, 0xc097ce7bc90715b4, 0xf0bdc21abb48db21, + 0x96769950b50d88f5, 0xbc143fa4e250eb32, 0xeb194f8e1ae525fe, + 0x92efd1b8d0cf37bf, 0xb7abc627050305ae, 0xe596b7b0c643c71a, + 0x8f7e32ce7bea5c70, 0xb35dbf821ae4f38c, 0xe0352f62a19e306f}; + return pow10_significands[k - float_info::min_k]; + } + + struct compute_mul_result { + carrier_uint result; + bool is_integer; + }; + struct compute_mul_parity_result { + bool parity; + bool is_integer; + }; + + static auto compute_mul(carrier_uint u, + const cache_entry_type& cache) noexcept + -> compute_mul_result { + auto r = umul96_upper64(u, cache); + return {static_cast(r >> 32), + static_cast(r) == 0}; + } + + static auto compute_delta(const cache_entry_type& cache, int beta) noexcept + -> uint32_t { + return static_cast(cache >> (64 - 1 - beta)); + } + + static auto compute_mul_parity(carrier_uint two_f, + const cache_entry_type& cache, + int beta) noexcept + -> compute_mul_parity_result { + FMT_ASSERT(beta >= 1, ""); + FMT_ASSERT(beta < 64, ""); + + auto r = umul96_lower64(two_f, cache); + return {((r >> (64 - beta)) & 1) != 0, + static_cast(r >> (32 - beta)) == 0}; + } + + static auto compute_left_endpoint_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return static_cast( + (cache - (cache >> (num_significand_bits() + 2))) >> + (64 - num_significand_bits() - 1 - beta)); + } + + static auto compute_right_endpoint_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return static_cast( + (cache + (cache >> (num_significand_bits() + 1))) >> + (64 - num_significand_bits() - 1 - beta)); + } + + static auto compute_round_up_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return (static_cast( + cache >> (64 - num_significand_bits() - 2 - beta)) + + 1) / + 2; + } +}; + +template <> struct cache_accessor { + using carrier_uint = float_info::carrier_uint; + using cache_entry_type = uint128_fallback; + + static auto get_cached_power(int k) noexcept -> uint128_fallback { + FMT_ASSERT(k >= float_info::min_k && k <= float_info::max_k, + "k is out of range"); + + static constexpr const uint128_fallback pow10_significands[] = { +#if FMT_USE_FULL_CACHE_DRAGONBOX + {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b}, + {0x9faacf3df73609b1, 0x77b191618c54e9ad}, + {0xc795830d75038c1d, 0xd59df5b9ef6a2418}, + {0xf97ae3d0d2446f25, 0x4b0573286b44ad1e}, + {0x9becce62836ac577, 0x4ee367f9430aec33}, + {0xc2e801fb244576d5, 0x229c41f793cda740}, + {0xf3a20279ed56d48a, 0x6b43527578c11110}, + {0x9845418c345644d6, 0x830a13896b78aaaa}, + {0xbe5691ef416bd60c, 0x23cc986bc656d554}, + {0xedec366b11c6cb8f, 0x2cbfbe86b7ec8aa9}, + {0x94b3a202eb1c3f39, 0x7bf7d71432f3d6aa}, + {0xb9e08a83a5e34f07, 0xdaf5ccd93fb0cc54}, + {0xe858ad248f5c22c9, 0xd1b3400f8f9cff69}, + {0x91376c36d99995be, 0x23100809b9c21fa2}, + {0xb58547448ffffb2d, 0xabd40a0c2832a78b}, + {0xe2e69915b3fff9f9, 0x16c90c8f323f516d}, + {0x8dd01fad907ffc3b, 0xae3da7d97f6792e4}, + {0xb1442798f49ffb4a, 0x99cd11cfdf41779d}, + {0xdd95317f31c7fa1d, 0x40405643d711d584}, + {0x8a7d3eef7f1cfc52, 0x482835ea666b2573}, + {0xad1c8eab5ee43b66, 0xda3243650005eed0}, + {0xd863b256369d4a40, 0x90bed43e40076a83}, + {0x873e4f75e2224e68, 0x5a7744a6e804a292}, + {0xa90de3535aaae202, 0x711515d0a205cb37}, + {0xd3515c2831559a83, 0x0d5a5b44ca873e04}, + {0x8412d9991ed58091, 0xe858790afe9486c3}, + {0xa5178fff668ae0b6, 0x626e974dbe39a873}, + {0xce5d73ff402d98e3, 0xfb0a3d212dc81290}, + {0x80fa687f881c7f8e, 0x7ce66634bc9d0b9a}, + {0xa139029f6a239f72, 0x1c1fffc1ebc44e81}, + {0xc987434744ac874e, 0xa327ffb266b56221}, + {0xfbe9141915d7a922, 0x4bf1ff9f0062baa9}, + {0x9d71ac8fada6c9b5, 0x6f773fc3603db4aa}, + {0xc4ce17b399107c22, 0xcb550fb4384d21d4}, + {0xf6019da07f549b2b, 0x7e2a53a146606a49}, + {0x99c102844f94e0fb, 0x2eda7444cbfc426e}, + {0xc0314325637a1939, 0xfa911155fefb5309}, + {0xf03d93eebc589f88, 0x793555ab7eba27cb}, + {0x96267c7535b763b5, 0x4bc1558b2f3458df}, + {0xbbb01b9283253ca2, 0x9eb1aaedfb016f17}, + {0xea9c227723ee8bcb, 0x465e15a979c1cadd}, + {0x92a1958a7675175f, 0x0bfacd89ec191eca}, + {0xb749faed14125d36, 0xcef980ec671f667c}, + {0xe51c79a85916f484, 0x82b7e12780e7401b}, + {0x8f31cc0937ae58d2, 0xd1b2ecb8b0908811}, + {0xb2fe3f0b8599ef07, 0x861fa7e6dcb4aa16}, + {0xdfbdcece67006ac9, 0x67a791e093e1d49b}, + {0x8bd6a141006042bd, 0xe0c8bb2c5c6d24e1}, + {0xaecc49914078536d, 0x58fae9f773886e19}, + {0xda7f5bf590966848, 0xaf39a475506a899f}, + {0x888f99797a5e012d, 0x6d8406c952429604}, + {0xaab37fd7d8f58178, 0xc8e5087ba6d33b84}, + {0xd5605fcdcf32e1d6, 0xfb1e4a9a90880a65}, + {0x855c3be0a17fcd26, 0x5cf2eea09a550680}, + {0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481f}, + {0xd0601d8efc57b08b, 0xf13b94daf124da27}, + {0x823c12795db6ce57, 0x76c53d08d6b70859}, + {0xa2cb1717b52481ed, 0x54768c4b0c64ca6f}, + {0xcb7ddcdda26da268, 0xa9942f5dcf7dfd0a}, + {0xfe5d54150b090b02, 0xd3f93b35435d7c4d}, + {0x9efa548d26e5a6e1, 0xc47bc5014a1a6db0}, + {0xc6b8e9b0709f109a, 0x359ab6419ca1091c}, + {0xf867241c8cc6d4c0, 0xc30163d203c94b63}, + {0x9b407691d7fc44f8, 0x79e0de63425dcf1e}, + {0xc21094364dfb5636, 0x985915fc12f542e5}, + {0xf294b943e17a2bc4, 0x3e6f5b7b17b2939e}, + {0x979cf3ca6cec5b5a, 0xa705992ceecf9c43}, + {0xbd8430bd08277231, 0x50c6ff782a838354}, + {0xece53cec4a314ebd, 0xa4f8bf5635246429}, + {0x940f4613ae5ed136, 0x871b7795e136be9a}, + {0xb913179899f68584, 0x28e2557b59846e40}, + {0xe757dd7ec07426e5, 0x331aeada2fe589d0}, + {0x9096ea6f3848984f, 0x3ff0d2c85def7622}, + {0xb4bca50b065abe63, 0x0fed077a756b53aa}, + {0xe1ebce4dc7f16dfb, 0xd3e8495912c62895}, + {0x8d3360f09cf6e4bd, 0x64712dd7abbbd95d}, + {0xb080392cc4349dec, 0xbd8d794d96aacfb4}, + {0xdca04777f541c567, 0xecf0d7a0fc5583a1}, + {0x89e42caaf9491b60, 0xf41686c49db57245}, + {0xac5d37d5b79b6239, 0x311c2875c522ced6}, + {0xd77485cb25823ac7, 0x7d633293366b828c}, + {0x86a8d39ef77164bc, 0xae5dff9c02033198}, + {0xa8530886b54dbdeb, 0xd9f57f830283fdfd}, + {0xd267caa862a12d66, 0xd072df63c324fd7c}, + {0x8380dea93da4bc60, 0x4247cb9e59f71e6e}, + {0xa46116538d0deb78, 0x52d9be85f074e609}, + {0xcd795be870516656, 0x67902e276c921f8c}, + {0x806bd9714632dff6, 0x00ba1cd8a3db53b7}, + {0xa086cfcd97bf97f3, 0x80e8a40eccd228a5}, + {0xc8a883c0fdaf7df0, 0x6122cd128006b2ce}, + {0xfad2a4b13d1b5d6c, 0x796b805720085f82}, + {0x9cc3a6eec6311a63, 0xcbe3303674053bb1}, + {0xc3f490aa77bd60fc, 0xbedbfc4411068a9d}, + {0xf4f1b4d515acb93b, 0xee92fb5515482d45}, + {0x991711052d8bf3c5, 0x751bdd152d4d1c4b}, + {0xbf5cd54678eef0b6, 0xd262d45a78a0635e}, + {0xef340a98172aace4, 0x86fb897116c87c35}, + {0x9580869f0e7aac0e, 0xd45d35e6ae3d4da1}, + {0xbae0a846d2195712, 0x8974836059cca10a}, + {0xe998d258869facd7, 0x2bd1a438703fc94c}, + {0x91ff83775423cc06, 0x7b6306a34627ddd0}, + {0xb67f6455292cbf08, 0x1a3bc84c17b1d543}, + {0xe41f3d6a7377eeca, 0x20caba5f1d9e4a94}, + {0x8e938662882af53e, 0x547eb47b7282ee9d}, + {0xb23867fb2a35b28d, 0xe99e619a4f23aa44}, + {0xdec681f9f4c31f31, 0x6405fa00e2ec94d5}, + {0x8b3c113c38f9f37e, 0xde83bc408dd3dd05}, + {0xae0b158b4738705e, 0x9624ab50b148d446}, + {0xd98ddaee19068c76, 0x3badd624dd9b0958}, + {0x87f8a8d4cfa417c9, 0xe54ca5d70a80e5d7}, + {0xa9f6d30a038d1dbc, 0x5e9fcf4ccd211f4d}, + {0xd47487cc8470652b, 0x7647c32000696720}, + {0x84c8d4dfd2c63f3b, 0x29ecd9f40041e074}, + {0xa5fb0a17c777cf09, 0xf468107100525891}, + {0xcf79cc9db955c2cc, 0x7182148d4066eeb5}, + {0x81ac1fe293d599bf, 0xc6f14cd848405531}, + {0xa21727db38cb002f, 0xb8ada00e5a506a7d}, + {0xca9cf1d206fdc03b, 0xa6d90811f0e4851d}, + {0xfd442e4688bd304a, 0x908f4a166d1da664}, + {0x9e4a9cec15763e2e, 0x9a598e4e043287ff}, + {0xc5dd44271ad3cdba, 0x40eff1e1853f29fe}, + {0xf7549530e188c128, 0xd12bee59e68ef47d}, + {0x9a94dd3e8cf578b9, 0x82bb74f8301958cf}, + {0xc13a148e3032d6e7, 0xe36a52363c1faf02}, + {0xf18899b1bc3f8ca1, 0xdc44e6c3cb279ac2}, + {0x96f5600f15a7b7e5, 0x29ab103a5ef8c0ba}, + {0xbcb2b812db11a5de, 0x7415d448f6b6f0e8}, + {0xebdf661791d60f56, 0x111b495b3464ad22}, + {0x936b9fcebb25c995, 0xcab10dd900beec35}, + {0xb84687c269ef3bfb, 0x3d5d514f40eea743}, + {0xe65829b3046b0afa, 0x0cb4a5a3112a5113}, + {0x8ff71a0fe2c2e6dc, 0x47f0e785eaba72ac}, + {0xb3f4e093db73a093, 0x59ed216765690f57}, + {0xe0f218b8d25088b8, 0x306869c13ec3532d}, + {0x8c974f7383725573, 0x1e414218c73a13fc}, + {0xafbd2350644eeacf, 0xe5d1929ef90898fb}, + {0xdbac6c247d62a583, 0xdf45f746b74abf3a}, + {0x894bc396ce5da772, 0x6b8bba8c328eb784}, + {0xab9eb47c81f5114f, 0x066ea92f3f326565}, + {0xd686619ba27255a2, 0xc80a537b0efefebe}, + {0x8613fd0145877585, 0xbd06742ce95f5f37}, + {0xa798fc4196e952e7, 0x2c48113823b73705}, + {0xd17f3b51fca3a7a0, 0xf75a15862ca504c6}, + {0x82ef85133de648c4, 0x9a984d73dbe722fc}, + {0xa3ab66580d5fdaf5, 0xc13e60d0d2e0ebbb}, + {0xcc963fee10b7d1b3, 0x318df905079926a9}, + {0xffbbcfe994e5c61f, 0xfdf17746497f7053}, + {0x9fd561f1fd0f9bd3, 0xfeb6ea8bedefa634}, + {0xc7caba6e7c5382c8, 0xfe64a52ee96b8fc1}, + {0xf9bd690a1b68637b, 0x3dfdce7aa3c673b1}, + {0x9c1661a651213e2d, 0x06bea10ca65c084f}, + {0xc31bfa0fe5698db8, 0x486e494fcff30a63}, + {0xf3e2f893dec3f126, 0x5a89dba3c3efccfb}, + {0x986ddb5c6b3a76b7, 0xf89629465a75e01d}, + {0xbe89523386091465, 0xf6bbb397f1135824}, + {0xee2ba6c0678b597f, 0x746aa07ded582e2d}, + {0x94db483840b717ef, 0xa8c2a44eb4571cdd}, + {0xba121a4650e4ddeb, 0x92f34d62616ce414}, + {0xe896a0d7e51e1566, 0x77b020baf9c81d18}, + {0x915e2486ef32cd60, 0x0ace1474dc1d122f}, + {0xb5b5ada8aaff80b8, 0x0d819992132456bb}, + {0xe3231912d5bf60e6, 0x10e1fff697ed6c6a}, + {0x8df5efabc5979c8f, 0xca8d3ffa1ef463c2}, + {0xb1736b96b6fd83b3, 0xbd308ff8a6b17cb3}, + {0xddd0467c64bce4a0, 0xac7cb3f6d05ddbdf}, + {0x8aa22c0dbef60ee4, 0x6bcdf07a423aa96c}, + {0xad4ab7112eb3929d, 0x86c16c98d2c953c7}, + {0xd89d64d57a607744, 0xe871c7bf077ba8b8}, + {0x87625f056c7c4a8b, 0x11471cd764ad4973}, + {0xa93af6c6c79b5d2d, 0xd598e40d3dd89bd0}, + {0xd389b47879823479, 0x4aff1d108d4ec2c4}, + {0x843610cb4bf160cb, 0xcedf722a585139bb}, + {0xa54394fe1eedb8fe, 0xc2974eb4ee658829}, + {0xce947a3da6a9273e, 0x733d226229feea33}, + {0x811ccc668829b887, 0x0806357d5a3f5260}, + {0xa163ff802a3426a8, 0xca07c2dcb0cf26f8}, + {0xc9bcff6034c13052, 0xfc89b393dd02f0b6}, + {0xfc2c3f3841f17c67, 0xbbac2078d443ace3}, + {0x9d9ba7832936edc0, 0xd54b944b84aa4c0e}, + {0xc5029163f384a931, 0x0a9e795e65d4df12}, + {0xf64335bcf065d37d, 0x4d4617b5ff4a16d6}, + {0x99ea0196163fa42e, 0x504bced1bf8e4e46}, + {0xc06481fb9bcf8d39, 0xe45ec2862f71e1d7}, + {0xf07da27a82c37088, 0x5d767327bb4e5a4d}, + {0x964e858c91ba2655, 0x3a6a07f8d510f870}, + {0xbbe226efb628afea, 0x890489f70a55368c}, + {0xeadab0aba3b2dbe5, 0x2b45ac74ccea842f}, + {0x92c8ae6b464fc96f, 0x3b0b8bc90012929e}, + {0xb77ada0617e3bbcb, 0x09ce6ebb40173745}, + {0xe55990879ddcaabd, 0xcc420a6a101d0516}, + {0x8f57fa54c2a9eab6, 0x9fa946824a12232e}, + {0xb32df8e9f3546564, 0x47939822dc96abfa}, + {0xdff9772470297ebd, 0x59787e2b93bc56f8}, + {0x8bfbea76c619ef36, 0x57eb4edb3c55b65b}, + {0xaefae51477a06b03, 0xede622920b6b23f2}, + {0xdab99e59958885c4, 0xe95fab368e45ecee}, + {0x88b402f7fd75539b, 0x11dbcb0218ebb415}, + {0xaae103b5fcd2a881, 0xd652bdc29f26a11a}, + {0xd59944a37c0752a2, 0x4be76d3346f04960}, + {0x857fcae62d8493a5, 0x6f70a4400c562ddc}, + {0xa6dfbd9fb8e5b88e, 0xcb4ccd500f6bb953}, + {0xd097ad07a71f26b2, 0x7e2000a41346a7a8}, + {0x825ecc24c873782f, 0x8ed400668c0c28c9}, + {0xa2f67f2dfa90563b, 0x728900802f0f32fb}, + {0xcbb41ef979346bca, 0x4f2b40a03ad2ffba}, + {0xfea126b7d78186bc, 0xe2f610c84987bfa9}, + {0x9f24b832e6b0f436, 0x0dd9ca7d2df4d7ca}, + {0xc6ede63fa05d3143, 0x91503d1c79720dbc}, + {0xf8a95fcf88747d94, 0x75a44c6397ce912b}, + {0x9b69dbe1b548ce7c, 0xc986afbe3ee11abb}, + {0xc24452da229b021b, 0xfbe85badce996169}, + {0xf2d56790ab41c2a2, 0xfae27299423fb9c4}, + {0x97c560ba6b0919a5, 0xdccd879fc967d41b}, + {0xbdb6b8e905cb600f, 0x5400e987bbc1c921}, + {0xed246723473e3813, 0x290123e9aab23b69}, + {0x9436c0760c86e30b, 0xf9a0b6720aaf6522}, + {0xb94470938fa89bce, 0xf808e40e8d5b3e6a}, + {0xe7958cb87392c2c2, 0xb60b1d1230b20e05}, + {0x90bd77f3483bb9b9, 0xb1c6f22b5e6f48c3}, + {0xb4ecd5f01a4aa828, 0x1e38aeb6360b1af4}, + {0xe2280b6c20dd5232, 0x25c6da63c38de1b1}, + {0x8d590723948a535f, 0x579c487e5a38ad0f}, + {0xb0af48ec79ace837, 0x2d835a9df0c6d852}, + {0xdcdb1b2798182244, 0xf8e431456cf88e66}, + {0x8a08f0f8bf0f156b, 0x1b8e9ecb641b5900}, + {0xac8b2d36eed2dac5, 0xe272467e3d222f40}, + {0xd7adf884aa879177, 0x5b0ed81dcc6abb10}, + {0x86ccbb52ea94baea, 0x98e947129fc2b4ea}, + {0xa87fea27a539e9a5, 0x3f2398d747b36225}, + {0xd29fe4b18e88640e, 0x8eec7f0d19a03aae}, + {0x83a3eeeef9153e89, 0x1953cf68300424ad}, + {0xa48ceaaab75a8e2b, 0x5fa8c3423c052dd8}, + {0xcdb02555653131b6, 0x3792f412cb06794e}, + {0x808e17555f3ebf11, 0xe2bbd88bbee40bd1}, + {0xa0b19d2ab70e6ed6, 0x5b6aceaeae9d0ec5}, + {0xc8de047564d20a8b, 0xf245825a5a445276}, + {0xfb158592be068d2e, 0xeed6e2f0f0d56713}, + {0x9ced737bb6c4183d, 0x55464dd69685606c}, + {0xc428d05aa4751e4c, 0xaa97e14c3c26b887}, + {0xf53304714d9265df, 0xd53dd99f4b3066a9}, + {0x993fe2c6d07b7fab, 0xe546a8038efe402a}, + {0xbf8fdb78849a5f96, 0xde98520472bdd034}, + {0xef73d256a5c0f77c, 0x963e66858f6d4441}, + {0x95a8637627989aad, 0xdde7001379a44aa9}, + {0xbb127c53b17ec159, 0x5560c018580d5d53}, + {0xe9d71b689dde71af, 0xaab8f01e6e10b4a7}, + {0x9226712162ab070d, 0xcab3961304ca70e9}, + {0xb6b00d69bb55c8d1, 0x3d607b97c5fd0d23}, + {0xe45c10c42a2b3b05, 0x8cb89a7db77c506b}, + {0x8eb98a7a9a5b04e3, 0x77f3608e92adb243}, + {0xb267ed1940f1c61c, 0x55f038b237591ed4}, + {0xdf01e85f912e37a3, 0x6b6c46dec52f6689}, + {0x8b61313bbabce2c6, 0x2323ac4b3b3da016}, + {0xae397d8aa96c1b77, 0xabec975e0a0d081b}, + {0xd9c7dced53c72255, 0x96e7bd358c904a22}, + {0x881cea14545c7575, 0x7e50d64177da2e55}, + {0xaa242499697392d2, 0xdde50bd1d5d0b9ea}, + {0xd4ad2dbfc3d07787, 0x955e4ec64b44e865}, + {0x84ec3c97da624ab4, 0xbd5af13bef0b113f}, + {0xa6274bbdd0fadd61, 0xecb1ad8aeacdd58f}, + {0xcfb11ead453994ba, 0x67de18eda5814af3}, + {0x81ceb32c4b43fcf4, 0x80eacf948770ced8}, + {0xa2425ff75e14fc31, 0xa1258379a94d028e}, + {0xcad2f7f5359a3b3e, 0x096ee45813a04331}, + {0xfd87b5f28300ca0d, 0x8bca9d6e188853fd}, + {0x9e74d1b791e07e48, 0x775ea264cf55347e}, + {0xc612062576589dda, 0x95364afe032a819e}, + {0xf79687aed3eec551, 0x3a83ddbd83f52205}, + {0x9abe14cd44753b52, 0xc4926a9672793543}, + {0xc16d9a0095928a27, 0x75b7053c0f178294}, + {0xf1c90080baf72cb1, 0x5324c68b12dd6339}, + {0x971da05074da7bee, 0xd3f6fc16ebca5e04}, + {0xbce5086492111aea, 0x88f4bb1ca6bcf585}, + {0xec1e4a7db69561a5, 0x2b31e9e3d06c32e6}, + {0x9392ee8e921d5d07, 0x3aff322e62439fd0}, + {0xb877aa3236a4b449, 0x09befeb9fad487c3}, + {0xe69594bec44de15b, 0x4c2ebe687989a9b4}, + {0x901d7cf73ab0acd9, 0x0f9d37014bf60a11}, + {0xb424dc35095cd80f, 0x538484c19ef38c95}, + {0xe12e13424bb40e13, 0x2865a5f206b06fba}, + {0x8cbccc096f5088cb, 0xf93f87b7442e45d4}, + {0xafebff0bcb24aafe, 0xf78f69a51539d749}, + {0xdbe6fecebdedd5be, 0xb573440e5a884d1c}, + {0x89705f4136b4a597, 0x31680a88f8953031}, + {0xabcc77118461cefc, 0xfdc20d2b36ba7c3e}, + {0xd6bf94d5e57a42bc, 0x3d32907604691b4d}, + {0x8637bd05af6c69b5, 0xa63f9a49c2c1b110}, + {0xa7c5ac471b478423, 0x0fcf80dc33721d54}, + {0xd1b71758e219652b, 0xd3c36113404ea4a9}, + {0x83126e978d4fdf3b, 0x645a1cac083126ea}, + {0xa3d70a3d70a3d70a, 0x3d70a3d70a3d70a4}, + {0xcccccccccccccccc, 0xcccccccccccccccd}, + {0x8000000000000000, 0x0000000000000000}, + {0xa000000000000000, 0x0000000000000000}, + {0xc800000000000000, 0x0000000000000000}, + {0xfa00000000000000, 0x0000000000000000}, + {0x9c40000000000000, 0x0000000000000000}, + {0xc350000000000000, 0x0000000000000000}, + {0xf424000000000000, 0x0000000000000000}, + {0x9896800000000000, 0x0000000000000000}, + {0xbebc200000000000, 0x0000000000000000}, + {0xee6b280000000000, 0x0000000000000000}, + {0x9502f90000000000, 0x0000000000000000}, + {0xba43b74000000000, 0x0000000000000000}, + {0xe8d4a51000000000, 0x0000000000000000}, + {0x9184e72a00000000, 0x0000000000000000}, + {0xb5e620f480000000, 0x0000000000000000}, + {0xe35fa931a0000000, 0x0000000000000000}, + {0x8e1bc9bf04000000, 0x0000000000000000}, + {0xb1a2bc2ec5000000, 0x0000000000000000}, + {0xde0b6b3a76400000, 0x0000000000000000}, + {0x8ac7230489e80000, 0x0000000000000000}, + {0xad78ebc5ac620000, 0x0000000000000000}, + {0xd8d726b7177a8000, 0x0000000000000000}, + {0x878678326eac9000, 0x0000000000000000}, + {0xa968163f0a57b400, 0x0000000000000000}, + {0xd3c21bcecceda100, 0x0000000000000000}, + {0x84595161401484a0, 0x0000000000000000}, + {0xa56fa5b99019a5c8, 0x0000000000000000}, + {0xcecb8f27f4200f3a, 0x0000000000000000}, + {0x813f3978f8940984, 0x4000000000000000}, + {0xa18f07d736b90be5, 0x5000000000000000}, + {0xc9f2c9cd04674ede, 0xa400000000000000}, + {0xfc6f7c4045812296, 0x4d00000000000000}, + {0x9dc5ada82b70b59d, 0xf020000000000000}, + {0xc5371912364ce305, 0x6c28000000000000}, + {0xf684df56c3e01bc6, 0xc732000000000000}, + {0x9a130b963a6c115c, 0x3c7f400000000000}, + {0xc097ce7bc90715b3, 0x4b9f100000000000}, + {0xf0bdc21abb48db20, 0x1e86d40000000000}, + {0x96769950b50d88f4, 0x1314448000000000}, + {0xbc143fa4e250eb31, 0x17d955a000000000}, + {0xeb194f8e1ae525fd, 0x5dcfab0800000000}, + {0x92efd1b8d0cf37be, 0x5aa1cae500000000}, + {0xb7abc627050305ad, 0xf14a3d9e40000000}, + {0xe596b7b0c643c719, 0x6d9ccd05d0000000}, + {0x8f7e32ce7bea5c6f, 0xe4820023a2000000}, + {0xb35dbf821ae4f38b, 0xdda2802c8a800000}, + {0xe0352f62a19e306e, 0xd50b2037ad200000}, + {0x8c213d9da502de45, 0x4526f422cc340000}, + {0xaf298d050e4395d6, 0x9670b12b7f410000}, + {0xdaf3f04651d47b4c, 0x3c0cdd765f114000}, + {0x88d8762bf324cd0f, 0xa5880a69fb6ac800}, + {0xab0e93b6efee0053, 0x8eea0d047a457a00}, + {0xd5d238a4abe98068, 0x72a4904598d6d880}, + {0x85a36366eb71f041, 0x47a6da2b7f864750}, + {0xa70c3c40a64e6c51, 0x999090b65f67d924}, + {0xd0cf4b50cfe20765, 0xfff4b4e3f741cf6d}, + {0x82818f1281ed449f, 0xbff8f10e7a8921a5}, + {0xa321f2d7226895c7, 0xaff72d52192b6a0e}, + {0xcbea6f8ceb02bb39, 0x9bf4f8a69f764491}, + {0xfee50b7025c36a08, 0x02f236d04753d5b5}, + {0x9f4f2726179a2245, 0x01d762422c946591}, + {0xc722f0ef9d80aad6, 0x424d3ad2b7b97ef6}, + {0xf8ebad2b84e0d58b, 0xd2e0898765a7deb3}, + {0x9b934c3b330c8577, 0x63cc55f49f88eb30}, + {0xc2781f49ffcfa6d5, 0x3cbf6b71c76b25fc}, + {0xf316271c7fc3908a, 0x8bef464e3945ef7b}, + {0x97edd871cfda3a56, 0x97758bf0e3cbb5ad}, + {0xbde94e8e43d0c8ec, 0x3d52eeed1cbea318}, + {0xed63a231d4c4fb27, 0x4ca7aaa863ee4bde}, + {0x945e455f24fb1cf8, 0x8fe8caa93e74ef6b}, + {0xb975d6b6ee39e436, 0xb3e2fd538e122b45}, + {0xe7d34c64a9c85d44, 0x60dbbca87196b617}, + {0x90e40fbeea1d3a4a, 0xbc8955e946fe31ce}, + {0xb51d13aea4a488dd, 0x6babab6398bdbe42}, + {0xe264589a4dcdab14, 0xc696963c7eed2dd2}, + {0x8d7eb76070a08aec, 0xfc1e1de5cf543ca3}, + {0xb0de65388cc8ada8, 0x3b25a55f43294bcc}, + {0xdd15fe86affad912, 0x49ef0eb713f39ebf}, + {0x8a2dbf142dfcc7ab, 0x6e3569326c784338}, + {0xacb92ed9397bf996, 0x49c2c37f07965405}, + {0xd7e77a8f87daf7fb, 0xdc33745ec97be907}, + {0x86f0ac99b4e8dafd, 0x69a028bb3ded71a4}, + {0xa8acd7c0222311bc, 0xc40832ea0d68ce0d}, + {0xd2d80db02aabd62b, 0xf50a3fa490c30191}, + {0x83c7088e1aab65db, 0x792667c6da79e0fb}, + {0xa4b8cab1a1563f52, 0x577001b891185939}, + {0xcde6fd5e09abcf26, 0xed4c0226b55e6f87}, + {0x80b05e5ac60b6178, 0x544f8158315b05b5}, + {0xa0dc75f1778e39d6, 0x696361ae3db1c722}, + {0xc913936dd571c84c, 0x03bc3a19cd1e38ea}, + {0xfb5878494ace3a5f, 0x04ab48a04065c724}, + {0x9d174b2dcec0e47b, 0x62eb0d64283f9c77}, + {0xc45d1df942711d9a, 0x3ba5d0bd324f8395}, + {0xf5746577930d6500, 0xca8f44ec7ee3647a}, + {0x9968bf6abbe85f20, 0x7e998b13cf4e1ecc}, + {0xbfc2ef456ae276e8, 0x9e3fedd8c321a67f}, + {0xefb3ab16c59b14a2, 0xc5cfe94ef3ea101f}, + {0x95d04aee3b80ece5, 0xbba1f1d158724a13}, + {0xbb445da9ca61281f, 0x2a8a6e45ae8edc98}, + {0xea1575143cf97226, 0xf52d09d71a3293be}, + {0x924d692ca61be758, 0x593c2626705f9c57}, + {0xb6e0c377cfa2e12e, 0x6f8b2fb00c77836d}, + {0xe498f455c38b997a, 0x0b6dfb9c0f956448}, + {0x8edf98b59a373fec, 0x4724bd4189bd5ead}, + {0xb2977ee300c50fe7, 0x58edec91ec2cb658}, + {0xdf3d5e9bc0f653e1, 0x2f2967b66737e3ee}, + {0x8b865b215899f46c, 0xbd79e0d20082ee75}, + {0xae67f1e9aec07187, 0xecd8590680a3aa12}, + {0xda01ee641a708de9, 0xe80e6f4820cc9496}, + {0x884134fe908658b2, 0x3109058d147fdcde}, + {0xaa51823e34a7eede, 0xbd4b46f0599fd416}, + {0xd4e5e2cdc1d1ea96, 0x6c9e18ac7007c91b}, + {0x850fadc09923329e, 0x03e2cf6bc604ddb1}, + {0xa6539930bf6bff45, 0x84db8346b786151d}, + {0xcfe87f7cef46ff16, 0xe612641865679a64}, + {0x81f14fae158c5f6e, 0x4fcb7e8f3f60c07f}, + {0xa26da3999aef7749, 0xe3be5e330f38f09e}, + {0xcb090c8001ab551c, 0x5cadf5bfd3072cc6}, + {0xfdcb4fa002162a63, 0x73d9732fc7c8f7f7}, + {0x9e9f11c4014dda7e, 0x2867e7fddcdd9afb}, + {0xc646d63501a1511d, 0xb281e1fd541501b9}, + {0xf7d88bc24209a565, 0x1f225a7ca91a4227}, + {0x9ae757596946075f, 0x3375788de9b06959}, + {0xc1a12d2fc3978937, 0x0052d6b1641c83af}, + {0xf209787bb47d6b84, 0xc0678c5dbd23a49b}, + {0x9745eb4d50ce6332, 0xf840b7ba963646e1}, + {0xbd176620a501fbff, 0xb650e5a93bc3d899}, + {0xec5d3fa8ce427aff, 0xa3e51f138ab4cebf}, + {0x93ba47c980e98cdf, 0xc66f336c36b10138}, + {0xb8a8d9bbe123f017, 0xb80b0047445d4185}, + {0xe6d3102ad96cec1d, 0xa60dc059157491e6}, + {0x9043ea1ac7e41392, 0x87c89837ad68db30}, + {0xb454e4a179dd1877, 0x29babe4598c311fc}, + {0xe16a1dc9d8545e94, 0xf4296dd6fef3d67b}, + {0x8ce2529e2734bb1d, 0x1899e4a65f58660d}, + {0xb01ae745b101e9e4, 0x5ec05dcff72e7f90}, + {0xdc21a1171d42645d, 0x76707543f4fa1f74}, + {0x899504ae72497eba, 0x6a06494a791c53a9}, + {0xabfa45da0edbde69, 0x0487db9d17636893}, + {0xd6f8d7509292d603, 0x45a9d2845d3c42b7}, + {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b3}, + {0xa7f26836f282b732, 0x8e6cac7768d7141f}, + {0xd1ef0244af2364ff, 0x3207d795430cd927}, + {0x8335616aed761f1f, 0x7f44e6bd49e807b9}, + {0xa402b9c5a8d3a6e7, 0x5f16206c9c6209a7}, + {0xcd036837130890a1, 0x36dba887c37a8c10}, + {0x802221226be55a64, 0xc2494954da2c978a}, + {0xa02aa96b06deb0fd, 0xf2db9baa10b7bd6d}, + {0xc83553c5c8965d3d, 0x6f92829494e5acc8}, + {0xfa42a8b73abbf48c, 0xcb772339ba1f17fa}, + {0x9c69a97284b578d7, 0xff2a760414536efc}, + {0xc38413cf25e2d70d, 0xfef5138519684abb}, + {0xf46518c2ef5b8cd1, 0x7eb258665fc25d6a}, + {0x98bf2f79d5993802, 0xef2f773ffbd97a62}, + {0xbeeefb584aff8603, 0xaafb550ffacfd8fb}, + {0xeeaaba2e5dbf6784, 0x95ba2a53f983cf39}, + {0x952ab45cfa97a0b2, 0xdd945a747bf26184}, + {0xba756174393d88df, 0x94f971119aeef9e5}, + {0xe912b9d1478ceb17, 0x7a37cd5601aab85e}, + {0x91abb422ccb812ee, 0xac62e055c10ab33b}, + {0xb616a12b7fe617aa, 0x577b986b314d600a}, + {0xe39c49765fdf9d94, 0xed5a7e85fda0b80c}, + {0x8e41ade9fbebc27d, 0x14588f13be847308}, + {0xb1d219647ae6b31c, 0x596eb2d8ae258fc9}, + {0xde469fbd99a05fe3, 0x6fca5f8ed9aef3bc}, + {0x8aec23d680043bee, 0x25de7bb9480d5855}, + {0xada72ccc20054ae9, 0xaf561aa79a10ae6b}, + {0xd910f7ff28069da4, 0x1b2ba1518094da05}, + {0x87aa9aff79042286, 0x90fb44d2f05d0843}, + {0xa99541bf57452b28, 0x353a1607ac744a54}, + {0xd3fa922f2d1675f2, 0x42889b8997915ce9}, + {0x847c9b5d7c2e09b7, 0x69956135febada12}, + {0xa59bc234db398c25, 0x43fab9837e699096}, + {0xcf02b2c21207ef2e, 0x94f967e45e03f4bc}, + {0x8161afb94b44f57d, 0x1d1be0eebac278f6}, + {0xa1ba1ba79e1632dc, 0x6462d92a69731733}, + {0xca28a291859bbf93, 0x7d7b8f7503cfdcff}, + {0xfcb2cb35e702af78, 0x5cda735244c3d43f}, + {0x9defbf01b061adab, 0x3a0888136afa64a8}, + {0xc56baec21c7a1916, 0x088aaa1845b8fdd1}, + {0xf6c69a72a3989f5b, 0x8aad549e57273d46}, + {0x9a3c2087a63f6399, 0x36ac54e2f678864c}, + {0xc0cb28a98fcf3c7f, 0x84576a1bb416a7de}, + {0xf0fdf2d3f3c30b9f, 0x656d44a2a11c51d6}, + {0x969eb7c47859e743, 0x9f644ae5a4b1b326}, + {0xbc4665b596706114, 0x873d5d9f0dde1fef}, + {0xeb57ff22fc0c7959, 0xa90cb506d155a7eb}, + {0x9316ff75dd87cbd8, 0x09a7f12442d588f3}, + {0xb7dcbf5354e9bece, 0x0c11ed6d538aeb30}, + {0xe5d3ef282a242e81, 0x8f1668c8a86da5fb}, + {0x8fa475791a569d10, 0xf96e017d694487bd}, + {0xb38d92d760ec4455, 0x37c981dcc395a9ad}, + {0xe070f78d3927556a, 0x85bbe253f47b1418}, + {0x8c469ab843b89562, 0x93956d7478ccec8f}, + {0xaf58416654a6babb, 0x387ac8d1970027b3}, + {0xdb2e51bfe9d0696a, 0x06997b05fcc0319f}, + {0x88fcf317f22241e2, 0x441fece3bdf81f04}, + {0xab3c2fddeeaad25a, 0xd527e81cad7626c4}, + {0xd60b3bd56a5586f1, 0x8a71e223d8d3b075}, + {0x85c7056562757456, 0xf6872d5667844e4a}, + {0xa738c6bebb12d16c, 0xb428f8ac016561dc}, + {0xd106f86e69d785c7, 0xe13336d701beba53}, + {0x82a45b450226b39c, 0xecc0024661173474}, + {0xa34d721642b06084, 0x27f002d7f95d0191}, + {0xcc20ce9bd35c78a5, 0x31ec038df7b441f5}, + {0xff290242c83396ce, 0x7e67047175a15272}, + {0x9f79a169bd203e41, 0x0f0062c6e984d387}, + {0xc75809c42c684dd1, 0x52c07b78a3e60869}, + {0xf92e0c3537826145, 0xa7709a56ccdf8a83}, + {0x9bbcc7a142b17ccb, 0x88a66076400bb692}, + {0xc2abf989935ddbfe, 0x6acff893d00ea436}, + {0xf356f7ebf83552fe, 0x0583f6b8c4124d44}, + {0x98165af37b2153de, 0xc3727a337a8b704b}, + {0xbe1bf1b059e9a8d6, 0x744f18c0592e4c5d}, + {0xeda2ee1c7064130c, 0x1162def06f79df74}, + {0x9485d4d1c63e8be7, 0x8addcb5645ac2ba9}, + {0xb9a74a0637ce2ee1, 0x6d953e2bd7173693}, + {0xe8111c87c5c1ba99, 0xc8fa8db6ccdd0438}, + {0x910ab1d4db9914a0, 0x1d9c9892400a22a3}, + {0xb54d5e4a127f59c8, 0x2503beb6d00cab4c}, + {0xe2a0b5dc971f303a, 0x2e44ae64840fd61e}, + {0x8da471a9de737e24, 0x5ceaecfed289e5d3}, + {0xb10d8e1456105dad, 0x7425a83e872c5f48}, + {0xdd50f1996b947518, 0xd12f124e28f7771a}, + {0x8a5296ffe33cc92f, 0x82bd6b70d99aaa70}, + {0xace73cbfdc0bfb7b, 0x636cc64d1001550c}, + {0xd8210befd30efa5a, 0x3c47f7e05401aa4f}, + {0x8714a775e3e95c78, 0x65acfaec34810a72}, + {0xa8d9d1535ce3b396, 0x7f1839a741a14d0e}, + {0xd31045a8341ca07c, 0x1ede48111209a051}, + {0x83ea2b892091e44d, 0x934aed0aab460433}, + {0xa4e4b66b68b65d60, 0xf81da84d56178540}, + {0xce1de40642e3f4b9, 0x36251260ab9d668f}, + {0x80d2ae83e9ce78f3, 0xc1d72b7c6b42601a}, + {0xa1075a24e4421730, 0xb24cf65b8612f820}, + {0xc94930ae1d529cfc, 0xdee033f26797b628}, + {0xfb9b7cd9a4a7443c, 0x169840ef017da3b2}, + {0x9d412e0806e88aa5, 0x8e1f289560ee864f}, + {0xc491798a08a2ad4e, 0xf1a6f2bab92a27e3}, + {0xf5b5d7ec8acb58a2, 0xae10af696774b1dc}, + {0x9991a6f3d6bf1765, 0xacca6da1e0a8ef2a}, + {0xbff610b0cc6edd3f, 0x17fd090a58d32af4}, + {0xeff394dcff8a948e, 0xddfc4b4cef07f5b1}, + {0x95f83d0a1fb69cd9, 0x4abdaf101564f98f}, + {0xbb764c4ca7a4440f, 0x9d6d1ad41abe37f2}, + {0xea53df5fd18d5513, 0x84c86189216dc5ee}, + {0x92746b9be2f8552c, 0x32fd3cf5b4e49bb5}, + {0xb7118682dbb66a77, 0x3fbc8c33221dc2a2}, + {0xe4d5e82392a40515, 0x0fabaf3feaa5334b}, + {0x8f05b1163ba6832d, 0x29cb4d87f2a7400f}, + {0xb2c71d5bca9023f8, 0x743e20e9ef511013}, + {0xdf78e4b2bd342cf6, 0x914da9246b255417}, + {0x8bab8eefb6409c1a, 0x1ad089b6c2f7548f}, + {0xae9672aba3d0c320, 0xa184ac2473b529b2}, + {0xda3c0f568cc4f3e8, 0xc9e5d72d90a2741f}, + {0x8865899617fb1871, 0x7e2fa67c7a658893}, + {0xaa7eebfb9df9de8d, 0xddbb901b98feeab8}, + {0xd51ea6fa85785631, 0x552a74227f3ea566}, + {0x8533285c936b35de, 0xd53a88958f872760}, + {0xa67ff273b8460356, 0x8a892abaf368f138}, + {0xd01fef10a657842c, 0x2d2b7569b0432d86}, + {0x8213f56a67f6b29b, 0x9c3b29620e29fc74}, + {0xa298f2c501f45f42, 0x8349f3ba91b47b90}, + {0xcb3f2f7642717713, 0x241c70a936219a74}, + {0xfe0efb53d30dd4d7, 0xed238cd383aa0111}, + {0x9ec95d1463e8a506, 0xf4363804324a40ab}, + {0xc67bb4597ce2ce48, 0xb143c6053edcd0d6}, + {0xf81aa16fdc1b81da, 0xdd94b7868e94050b}, + {0x9b10a4e5e9913128, 0xca7cf2b4191c8327}, + {0xc1d4ce1f63f57d72, 0xfd1c2f611f63a3f1}, + {0xf24a01a73cf2dccf, 0xbc633b39673c8ced}, + {0x976e41088617ca01, 0xd5be0503e085d814}, + {0xbd49d14aa79dbc82, 0x4b2d8644d8a74e19}, + {0xec9c459d51852ba2, 0xddf8e7d60ed1219f}, + {0x93e1ab8252f33b45, 0xcabb90e5c942b504}, + {0xb8da1662e7b00a17, 0x3d6a751f3b936244}, + {0xe7109bfba19c0c9d, 0x0cc512670a783ad5}, + {0x906a617d450187e2, 0x27fb2b80668b24c6}, + {0xb484f9dc9641e9da, 0xb1f9f660802dedf7}, + {0xe1a63853bbd26451, 0x5e7873f8a0396974}, + {0x8d07e33455637eb2, 0xdb0b487b6423e1e9}, + {0xb049dc016abc5e5f, 0x91ce1a9a3d2cda63}, + {0xdc5c5301c56b75f7, 0x7641a140cc7810fc}, + {0x89b9b3e11b6329ba, 0xa9e904c87fcb0a9e}, + {0xac2820d9623bf429, 0x546345fa9fbdcd45}, + {0xd732290fbacaf133, 0xa97c177947ad4096}, + {0x867f59a9d4bed6c0, 0x49ed8eabcccc485e}, + {0xa81f301449ee8c70, 0x5c68f256bfff5a75}, + {0xd226fc195c6a2f8c, 0x73832eec6fff3112}, + {0x83585d8fd9c25db7, 0xc831fd53c5ff7eac}, + {0xa42e74f3d032f525, 0xba3e7ca8b77f5e56}, + {0xcd3a1230c43fb26f, 0x28ce1bd2e55f35ec}, + {0x80444b5e7aa7cf85, 0x7980d163cf5b81b4}, + {0xa0555e361951c366, 0xd7e105bcc3326220}, + {0xc86ab5c39fa63440, 0x8dd9472bf3fefaa8}, + {0xfa856334878fc150, 0xb14f98f6f0feb952}, + {0x9c935e00d4b9d8d2, 0x6ed1bf9a569f33d4}, + {0xc3b8358109e84f07, 0x0a862f80ec4700c9}, + {0xf4a642e14c6262c8, 0xcd27bb612758c0fb}, + {0x98e7e9cccfbd7dbd, 0x8038d51cb897789d}, + {0xbf21e44003acdd2c, 0xe0470a63e6bd56c4}, + {0xeeea5d5004981478, 0x1858ccfce06cac75}, + {0x95527a5202df0ccb, 0x0f37801e0c43ebc9}, + {0xbaa718e68396cffd, 0xd30560258f54e6bb}, + {0xe950df20247c83fd, 0x47c6b82ef32a206a}, + {0x91d28b7416cdd27e, 0x4cdc331d57fa5442}, + {0xb6472e511c81471d, 0xe0133fe4adf8e953}, + {0xe3d8f9e563a198e5, 0x58180fddd97723a7}, + {0x8e679c2f5e44ff8f, 0x570f09eaa7ea7649}, + {0xb201833b35d63f73, 0x2cd2cc6551e513db}, + {0xde81e40a034bcf4f, 0xf8077f7ea65e58d2}, + {0x8b112e86420f6191, 0xfb04afaf27faf783}, + {0xadd57a27d29339f6, 0x79c5db9af1f9b564}, + {0xd94ad8b1c7380874, 0x18375281ae7822bd}, + {0x87cec76f1c830548, 0x8f2293910d0b15b6}, + {0xa9c2794ae3a3c69a, 0xb2eb3875504ddb23}, + {0xd433179d9c8cb841, 0x5fa60692a46151ec}, + {0x849feec281d7f328, 0xdbc7c41ba6bcd334}, + {0xa5c7ea73224deff3, 0x12b9b522906c0801}, + {0xcf39e50feae16bef, 0xd768226b34870a01}, + {0x81842f29f2cce375, 0xe6a1158300d46641}, + {0xa1e53af46f801c53, 0x60495ae3c1097fd1}, + {0xca5e89b18b602368, 0x385bb19cb14bdfc5}, + {0xfcf62c1dee382c42, 0x46729e03dd9ed7b6}, + {0x9e19db92b4e31ba9, 0x6c07a2c26a8346d2}, + {0xc5a05277621be293, 0xc7098b7305241886}, + {0xf70867153aa2db38, 0xb8cbee4fc66d1ea8}, + {0x9a65406d44a5c903, 0x737f74f1dc043329}, + {0xc0fe908895cf3b44, 0x505f522e53053ff3}, + {0xf13e34aabb430a15, 0x647726b9e7c68ff0}, + {0x96c6e0eab509e64d, 0x5eca783430dc19f6}, + {0xbc789925624c5fe0, 0xb67d16413d132073}, + {0xeb96bf6ebadf77d8, 0xe41c5bd18c57e890}, + {0x933e37a534cbaae7, 0x8e91b962f7b6f15a}, + {0xb80dc58e81fe95a1, 0x723627bbb5a4adb1}, + {0xe61136f2227e3b09, 0xcec3b1aaa30dd91d}, + {0x8fcac257558ee4e6, 0x213a4f0aa5e8a7b2}, + {0xb3bd72ed2af29e1f, 0xa988e2cd4f62d19e}, + {0xe0accfa875af45a7, 0x93eb1b80a33b8606}, + {0x8c6c01c9498d8b88, 0xbc72f130660533c4}, + {0xaf87023b9bf0ee6a, 0xeb8fad7c7f8680b5}, + {0xdb68c2ca82ed2a05, 0xa67398db9f6820e2}, +#else + {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b}, + {0xce5d73ff402d98e3, 0xfb0a3d212dc81290}, + {0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481f}, + {0x86a8d39ef77164bc, 0xae5dff9c02033198}, + {0xd98ddaee19068c76, 0x3badd624dd9b0958}, + {0xafbd2350644eeacf, 0xe5d1929ef90898fb}, + {0x8df5efabc5979c8f, 0xca8d3ffa1ef463c2}, + {0xe55990879ddcaabd, 0xcc420a6a101d0516}, + {0xb94470938fa89bce, 0xf808e40e8d5b3e6a}, + {0x95a8637627989aad, 0xdde7001379a44aa9}, + {0xf1c90080baf72cb1, 0x5324c68b12dd6339}, + {0xc350000000000000, 0x0000000000000000}, + {0x9dc5ada82b70b59d, 0xf020000000000000}, + {0xfee50b7025c36a08, 0x02f236d04753d5b5}, + {0xcde6fd5e09abcf26, 0xed4c0226b55e6f87}, + {0xa6539930bf6bff45, 0x84db8346b786151d}, + {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b3}, + {0xd910f7ff28069da4, 0x1b2ba1518094da05}, + {0xaf58416654a6babb, 0x387ac8d1970027b3}, + {0x8da471a9de737e24, 0x5ceaecfed289e5d3}, + {0xe4d5e82392a40515, 0x0fabaf3feaa5334b}, + {0xb8da1662e7b00a17, 0x3d6a751f3b936244}, + {0x95527a5202df0ccb, 0x0f37801e0c43ebc9}, + {0xf13e34aabb430a15, 0x647726b9e7c68ff0} +#endif + }; + +#if FMT_USE_FULL_CACHE_DRAGONBOX + return pow10_significands[k - float_info::min_k]; +#else + static constexpr const uint64_t powers_of_5_64[] = { + 0x0000000000000001, 0x0000000000000005, 0x0000000000000019, + 0x000000000000007d, 0x0000000000000271, 0x0000000000000c35, + 0x0000000000003d09, 0x000000000001312d, 0x000000000005f5e1, + 0x00000000001dcd65, 0x00000000009502f9, 0x0000000002e90edd, + 0x000000000e8d4a51, 0x0000000048c27395, 0x000000016bcc41e9, + 0x000000071afd498d, 0x0000002386f26fc1, 0x000000b1a2bc2ec5, + 0x000003782dace9d9, 0x00001158e460913d, 0x000056bc75e2d631, + 0x0001b1ae4d6e2ef5, 0x000878678326eac9, 0x002a5a058fc295ed, + 0x00d3c21bcecceda1, 0x0422ca8b0a00a425, 0x14adf4b7320334b9}; + + static const int compression_ratio = 27; + + // Compute base index. + int cache_index = (k - float_info::min_k) / compression_ratio; + int kb = cache_index * compression_ratio + float_info::min_k; + int offset = k - kb; + + // Get base cache. + uint128_fallback base_cache = pow10_significands[cache_index]; + if (offset == 0) return base_cache; + + // Compute the required amount of bit-shift. + int alpha = floor_log2_pow10(kb + offset) - floor_log2_pow10(kb) - offset; + FMT_ASSERT(alpha > 0 && alpha < 64, "shifting error detected"); + + // Try to recover the real cache. + uint64_t pow5 = powers_of_5_64[offset]; + uint128_fallback recovered_cache = umul128(base_cache.high(), pow5); + uint128_fallback middle_low = umul128(base_cache.low(), pow5); + + recovered_cache += middle_low.high(); + + uint64_t high_to_middle = recovered_cache.high() << (64 - alpha); + uint64_t middle_to_low = recovered_cache.low() << (64 - alpha); + + recovered_cache = + uint128_fallback{(recovered_cache.low() >> alpha) | high_to_middle, + ((middle_low.low() >> alpha) | middle_to_low)}; + FMT_ASSERT(recovered_cache.low() + 1 != 0, ""); + return {recovered_cache.high(), recovered_cache.low() + 1}; +#endif + } + + struct compute_mul_result { + carrier_uint result; + bool is_integer; + }; + struct compute_mul_parity_result { + bool parity; + bool is_integer; + }; + + static auto compute_mul(carrier_uint u, + const cache_entry_type& cache) noexcept + -> compute_mul_result { + auto r = umul192_upper128(u, cache); + return {r.high(), r.low() == 0}; + } + + static auto compute_delta(const cache_entry_type& cache, int beta) noexcept + -> uint32_t { + return static_cast(cache.high() >> (64 - 1 - beta)); + } + + static auto compute_mul_parity(carrier_uint two_f, + const cache_entry_type& cache, + int beta) noexcept + -> compute_mul_parity_result { + FMT_ASSERT(beta >= 1, ""); + FMT_ASSERT(beta < 64, ""); + + auto r = umul192_lower128(two_f, cache); + return {((r.high() >> (64 - beta)) & 1) != 0, + ((r.high() << beta) | (r.low() >> (64 - beta))) == 0}; + } + + static auto compute_left_endpoint_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return (cache.high() - + (cache.high() >> (num_significand_bits() + 2))) >> + (64 - num_significand_bits() - 1 - beta); + } + + static auto compute_right_endpoint_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return (cache.high() + + (cache.high() >> (num_significand_bits() + 1))) >> + (64 - num_significand_bits() - 1 - beta); + } + + static auto compute_round_up_for_shorter_interval_case( + const cache_entry_type& cache, int beta) noexcept -> carrier_uint { + return ((cache.high() >> (64 - num_significand_bits() - 2 - beta)) + + 1) / + 2; + } +}; + +FMT_FUNC auto get_cached_power(int k) noexcept -> uint128_fallback { + return cache_accessor::get_cached_power(k); +} + +// Various integer checks +template +auto is_left_endpoint_integer_shorter_interval(int exponent) noexcept -> bool { + const int case_shorter_interval_left_endpoint_lower_threshold = 2; + const int case_shorter_interval_left_endpoint_upper_threshold = 3; + return exponent >= case_shorter_interval_left_endpoint_lower_threshold && + exponent <= case_shorter_interval_left_endpoint_upper_threshold; +} + +// Remove trailing zeros from n and return the number of zeros removed (float) +FMT_INLINE int remove_trailing_zeros(uint32_t& n, int s = 0) noexcept { + FMT_ASSERT(n != 0, ""); + // Modular inverse of 5 (mod 2^32): (mod_inv_5 * 5) mod 2^32 = 1. + constexpr uint32_t mod_inv_5 = 0xcccccccd; + constexpr uint32_t mod_inv_25 = 0xc28f5c29; // = mod_inv_5 * mod_inv_5 + + while (true) { + auto q = rotr(n * mod_inv_25, 2); + if (q > max_value() / 100) break; + n = q; + s += 2; + } + auto q = rotr(n * mod_inv_5, 1); + if (q <= max_value() / 10) { + n = q; + s |= 1; + } + return s; +} + +// Removes trailing zeros and returns the number of zeros removed (double) +FMT_INLINE int remove_trailing_zeros(uint64_t& n) noexcept { + FMT_ASSERT(n != 0, ""); + + // This magic number is ceil(2^90 / 10^8). + constexpr uint64_t magic_number = 12379400392853802749ull; + auto nm = umul128(n, magic_number); + + // Is n is divisible by 10^8? + if ((nm.high() & ((1ull << (90 - 64)) - 1)) == 0 && nm.low() < magic_number) { + // If yes, work with the quotient... + auto n32 = static_cast(nm.high() >> (90 - 64)); + // ... and use the 32 bit variant of the function + int s = remove_trailing_zeros(n32, 8); + n = n32; + return s; + } + + // If n is not divisible by 10^8, work with n itself. + constexpr uint64_t mod_inv_5 = 0xcccccccccccccccd; + constexpr uint64_t mod_inv_25 = 0x8f5c28f5c28f5c29; // mod_inv_5 * mod_inv_5 + + int s = 0; + while (true) { + auto q = rotr(n * mod_inv_25, 2); + if (q > max_value() / 100) break; + n = q; + s += 2; + } + auto q = rotr(n * mod_inv_5, 1); + if (q <= max_value() / 10) { + n = q; + s |= 1; + } + + return s; +} + +// The main algorithm for shorter interval case +template +FMT_INLINE decimal_fp shorter_interval_case(int exponent) noexcept { + decimal_fp ret_value; + // Compute k and beta + const int minus_k = floor_log10_pow2_minus_log10_4_over_3(exponent); + const int beta = exponent + floor_log2_pow10(-minus_k); + + // Compute xi and zi + using cache_entry_type = typename cache_accessor::cache_entry_type; + const cache_entry_type cache = cache_accessor::get_cached_power(-minus_k); + + auto xi = cache_accessor::compute_left_endpoint_for_shorter_interval_case( + cache, beta); + auto zi = cache_accessor::compute_right_endpoint_for_shorter_interval_case( + cache, beta); + + // If the left endpoint is not an integer, increase it + if (!is_left_endpoint_integer_shorter_interval(exponent)) ++xi; + + // Try bigger divisor + ret_value.significand = zi / 10; + + // If succeed, remove trailing zeros if necessary and return + if (ret_value.significand * 10 >= xi) { + ret_value.exponent = minus_k + 1; + ret_value.exponent += remove_trailing_zeros(ret_value.significand); + return ret_value; + } + + // Otherwise, compute the round-up of y + ret_value.significand = + cache_accessor::compute_round_up_for_shorter_interval_case(cache, + beta); + ret_value.exponent = minus_k; + + // When tie occurs, choose one of them according to the rule + if (exponent >= float_info::shorter_interval_tie_lower_threshold && + exponent <= float_info::shorter_interval_tie_upper_threshold) { + ret_value.significand = ret_value.significand % 2 == 0 + ? ret_value.significand + : ret_value.significand - 1; + } else if (ret_value.significand < xi) { + ++ret_value.significand; + } + return ret_value; +} + +template auto to_decimal(T x) noexcept -> decimal_fp { + // Step 1: integer promotion & Schubfach multiplier calculation. + + using carrier_uint = typename float_info::carrier_uint; + using cache_entry_type = typename cache_accessor::cache_entry_type; + auto br = bit_cast(x); + + // Extract significand bits and exponent bits. + const carrier_uint significand_mask = + (static_cast(1) << num_significand_bits()) - 1; + carrier_uint significand = (br & significand_mask); + int exponent = + static_cast((br & exponent_mask()) >> num_significand_bits()); + + if (exponent != 0) { // Check if normal. + exponent -= exponent_bias() + num_significand_bits(); + + // Shorter interval case; proceed like Schubfach. + // In fact, when exponent == 1 and significand == 0, the interval is + // regular. However, it can be shown that the end-results are anyway same. + if (significand == 0) return shorter_interval_case(exponent); + + significand |= (static_cast(1) << num_significand_bits()); + } else { + // Subnormal case; the interval is always regular. + if (significand == 0) return {0, 0}; + exponent = + std::numeric_limits::min_exponent - num_significand_bits() - 1; + } + + const bool include_left_endpoint = (significand % 2 == 0); + const bool include_right_endpoint = include_left_endpoint; + + // Compute k and beta. + const int minus_k = floor_log10_pow2(exponent) - float_info::kappa; + const cache_entry_type cache = cache_accessor::get_cached_power(-minus_k); + const int beta = exponent + floor_log2_pow10(-minus_k); + + // Compute zi and deltai. + // 10^kappa <= deltai < 10^(kappa + 1) + const uint32_t deltai = cache_accessor::compute_delta(cache, beta); + const carrier_uint two_fc = significand << 1; + + // For the case of binary32, the result of integer check is not correct for + // 29711844 * 2^-82 + // = 6.1442653300000000008655037797566933477355632930994033813476... * 10^-18 + // and 29711844 * 2^-81 + // = 1.2288530660000000001731007559513386695471126586198806762695... * 10^-17, + // and they are the unique counterexamples. However, since 29711844 is even, + // this does not cause any problem for the endpoints calculations; it can only + // cause a problem when we need to perform integer check for the center. + // Fortunately, with these inputs, that branch is never executed, so we are + // fine. + const typename cache_accessor::compute_mul_result z_mul = + cache_accessor::compute_mul((two_fc | 1) << beta, cache); + + // Step 2: Try larger divisor; remove trailing zeros if necessary. + + // Using an upper bound on zi, we might be able to optimize the division + // better than the compiler; we are computing zi / big_divisor here. + decimal_fp ret_value; + ret_value.significand = divide_by_10_to_kappa_plus_1(z_mul.result); + uint32_t r = static_cast(z_mul.result - float_info::big_divisor * + ret_value.significand); + + if (r < deltai) { + // Exclude the right endpoint if necessary. + if (r == 0 && (z_mul.is_integer & !include_right_endpoint)) { + --ret_value.significand; + r = float_info::big_divisor; + goto small_divisor_case_label; + } + } else if (r > deltai) { + goto small_divisor_case_label; + } else { + // r == deltai; compare fractional parts. + const typename cache_accessor::compute_mul_parity_result x_mul = + cache_accessor::compute_mul_parity(two_fc - 1, cache, beta); + + if (!(x_mul.parity | (x_mul.is_integer & include_left_endpoint))) + goto small_divisor_case_label; + } + ret_value.exponent = minus_k + float_info::kappa + 1; + + // We may need to remove trailing zeros. + ret_value.exponent += remove_trailing_zeros(ret_value.significand); + return ret_value; + + // Step 3: Find the significand with the smaller divisor. + +small_divisor_case_label: + ret_value.significand *= 10; + ret_value.exponent = minus_k + float_info::kappa; + + uint32_t dist = r - (deltai / 2) + (float_info::small_divisor / 2); + const bool approx_y_parity = + ((dist ^ (float_info::small_divisor / 2)) & 1) != 0; + + // Is dist divisible by 10^kappa? + const bool divisible_by_small_divisor = + check_divisibility_and_divide_by_pow10::kappa>(dist); + + // Add dist / 10^kappa to the significand. + ret_value.significand += dist; + + if (!divisible_by_small_divisor) return ret_value; + + // Check z^(f) >= epsilon^(f). + // We have either yi == zi - epsiloni or yi == (zi - epsiloni) - 1, + // where yi == zi - epsiloni if and only if z^(f) >= epsilon^(f). + // Since there are only 2 possibilities, we only need to care about the + // parity. Also, zi and r should have the same parity since the divisor + // is an even number. + const auto y_mul = cache_accessor::compute_mul_parity(two_fc, cache, beta); + + // If z^(f) >= epsilon^(f), we might have a tie when z^(f) == epsilon^(f), + // or equivalently, when y is an integer. + if (y_mul.parity != approx_y_parity) + --ret_value.significand; + else if (y_mul.is_integer & (ret_value.significand % 2 != 0)) + --ret_value.significand; + return ret_value; +} +} // namespace dragonbox +} // namespace detail + +template <> struct formatter { + FMT_CONSTEXPR auto parse(format_parse_context& ctx) + -> format_parse_context::iterator { + return ctx.begin(); + } + + auto format(const detail::bigint& n, format_context& ctx) const + -> format_context::iterator { + auto out = ctx.out(); + bool first = true; + for (auto i = n.bigits_.size(); i > 0; --i) { + auto value = n.bigits_[i - 1u]; + if (first) { + out = fmt::format_to(out, FMT_STRING("{:x}"), value); + first = false; + continue; + } + out = fmt::format_to(out, FMT_STRING("{:08x}"), value); + } + if (n.exp_ > 0) + out = fmt::format_to(out, FMT_STRING("p{}"), + n.exp_ * detail::bigint::bigit_bits); + return out; + } +}; + +FMT_FUNC detail::utf8_to_utf16::utf8_to_utf16(string_view s) { + for_each_codepoint(s, [this](uint32_t cp, string_view) { + if (cp == invalid_code_point) FMT_THROW(std::runtime_error("invalid utf8")); + if (cp <= 0xFFFF) { + buffer_.push_back(static_cast(cp)); + } else { + cp -= 0x10000; + buffer_.push_back(static_cast(0xD800 + (cp >> 10))); + buffer_.push_back(static_cast(0xDC00 + (cp & 0x3FF))); + } + return true; + }); + buffer_.push_back(0); +} + +FMT_FUNC void format_system_error(detail::buffer& out, int error_code, + const char* message) noexcept { + FMT_TRY { + auto ec = std::error_code(error_code, std::generic_category()); + detail::write(appender(out), std::system_error(ec, message).what()); + return; + } + FMT_CATCH(...) {} + format_error_code(out, error_code, message); +} + +FMT_FUNC void report_system_error(int error_code, + const char* message) noexcept { + do_report_error(format_system_error, error_code, message); +} + +FMT_FUNC auto vformat(string_view fmt, format_args args) -> std::string { + // Don't optimize the "{}" case to keep the binary size small and because it + // can be better optimized in fmt::format anyway. + auto buffer = memory_buffer(); + detail::vformat_to(buffer, fmt, args); + return to_string(buffer); +} + +namespace detail { + +FMT_FUNC void vformat_to(buffer& buf, string_view fmt, format_args args, + locale_ref loc) { + auto out = appender(buf); + if (fmt.size() == 2 && equal2(fmt.data(), "{}")) + return args.get(0).visit(default_arg_formatter{out}); + parse_format_string( + fmt, format_handler{parse_context(fmt), {out, args, loc}}); +} + +template struct span { + T* data; + size_t size; +}; + +template auto flockfile(F* f) -> decltype(_lock_file(f)) { + _lock_file(f); +} +template auto funlockfile(F* f) -> decltype(_unlock_file(f)) { + _unlock_file(f); +} + +#ifndef getc_unlocked +template auto getc_unlocked(F* f) -> decltype(_fgetc_nolock(f)) { + return _fgetc_nolock(f); +} +#endif + +template +struct has_flockfile : std::false_type {}; + +template +struct has_flockfile()))>> + : std::true_type {}; + +// A FILE wrapper. F is FILE defined as a template parameter to make system API +// detection work. +template class file_base { + public: + F* file_; + + public: + file_base(F* file) : file_(file) {} + operator F*() const { return file_; } + + // Reads a code unit from the stream. + auto get() -> int { + int result = getc_unlocked(file_); + if (result == EOF && ferror(file_) != 0) + FMT_THROW(system_error(errno, FMT_STRING("getc failed"))); + return result; + } + + // Puts the code unit back into the stream buffer. + void unget(char c) { + if (ungetc(c, file_) == EOF) + FMT_THROW(system_error(errno, FMT_STRING("ungetc failed"))); + } + + void flush() { fflush(this->file_); } +}; + +// A FILE wrapper for glibc. +template class glibc_file : public file_base { + private: + enum { + line_buffered = 0x200, // _IO_LINE_BUF + unbuffered = 2 // _IO_UNBUFFERED + }; + + public: + using file_base::file_base; + + auto is_buffered() const -> bool { + return (this->file_->_flags & unbuffered) == 0; + } + + void init_buffer() { + if (this->file_->_IO_write_ptr < this->file_->_IO_write_end) return; + // Force buffer initialization by placing and removing a char in a buffer. + putc_unlocked(0, this->file_); + --this->file_->_IO_write_ptr; + } + + // Returns the file's read buffer. + auto get_read_buffer() const -> span { + auto ptr = this->file_->_IO_read_ptr; + return {ptr, to_unsigned(this->file_->_IO_read_end - ptr)}; + } + + // Returns the file's write buffer. + auto get_write_buffer() const -> span { + auto ptr = this->file_->_IO_write_ptr; + return {ptr, to_unsigned(this->file_->_IO_buf_end - ptr)}; + } + + void advance_write_buffer(size_t size) { this->file_->_IO_write_ptr += size; } + + bool needs_flush() const { + if ((this->file_->_flags & line_buffered) == 0) return false; + char* end = this->file_->_IO_write_end; + return memchr(end, '\n', to_unsigned(this->file_->_IO_write_ptr - end)); + } + + void flush() { fflush_unlocked(this->file_); } +}; + +// A FILE wrapper for Apple's libc. +template class apple_file : public file_base { + private: + enum { + line_buffered = 1, // __SNBF + unbuffered = 2 // __SLBF + }; + + public: + using file_base::file_base; + + auto is_buffered() const -> bool { + return (this->file_->_flags & unbuffered) == 0; + } + + void init_buffer() { + if (this->file_->_p) return; + // Force buffer initialization by placing and removing a char in a buffer. + putc_unlocked(0, this->file_); + --this->file_->_p; + ++this->file_->_w; + } + + auto get_read_buffer() const -> span { + return {reinterpret_cast(this->file_->_p), + to_unsigned(this->file_->_r)}; + } + + auto get_write_buffer() const -> span { + return {reinterpret_cast(this->file_->_p), + to_unsigned(this->file_->_bf._base + this->file_->_bf._size - + this->file_->_p)}; + } + + void advance_write_buffer(size_t size) { + this->file_->_p += size; + this->file_->_w -= size; + } + + bool needs_flush() const { + if ((this->file_->_flags & line_buffered) == 0) return false; + return memchr(this->file_->_p + this->file_->_w, '\n', + to_unsigned(-this->file_->_w)); + } +}; + +// A fallback FILE wrapper. +template class fallback_file : public file_base { + private: + char next_; // The next unconsumed character in the buffer. + bool has_next_ = false; + + public: + using file_base::file_base; + + auto is_buffered() const -> bool { return false; } + auto needs_flush() const -> bool { return false; } + void init_buffer() {} + + auto get_read_buffer() const -> span { + return {&next_, has_next_ ? 1u : 0u}; + } + + auto get_write_buffer() const -> span { return {nullptr, 0}; } + + void advance_write_buffer(size_t) {} + + auto get() -> int { + has_next_ = false; + return file_base::get(); + } + + void unget(char c) { + file_base::unget(c); + next_ = c; + has_next_ = true; + } +}; + +#ifndef FMT_USE_FALLBACK_FILE +# define FMT_USE_FALLBACK_FILE 0 +#endif + +template +auto get_file(F* f, int) -> apple_file { + return f; +} +template +inline auto get_file(F* f, int) -> glibc_file { + return f; +} + +inline auto get_file(FILE* f, ...) -> fallback_file { return f; } + +using file_ref = decltype(get_file(static_cast(nullptr), 0)); + +template +class file_print_buffer : public buffer { + public: + explicit file_print_buffer(F*) : buffer(nullptr, size_t()) {} +}; + +template +class file_print_buffer::value>> + : public buffer { + private: + file_ref file_; + + static void grow(buffer& base, size_t) { + auto& self = static_cast(base); + self.file_.advance_write_buffer(self.size()); + if (self.file_.get_write_buffer().size == 0) self.file_.flush(); + auto buf = self.file_.get_write_buffer(); + FMT_ASSERT(buf.size > 0, ""); + self.set(buf.data, buf.size); + self.clear(); + } + + public: + explicit file_print_buffer(F* f) : buffer(grow, size_t()), file_(f) { + flockfile(f); + file_.init_buffer(); + auto buf = file_.get_write_buffer(); + set(buf.data, buf.size); + } + ~file_print_buffer() { + file_.advance_write_buffer(size()); + bool flush = file_.needs_flush(); + F* f = file_; // Make funlockfile depend on the template parameter F + funlockfile(f); // for the system API detection to work. + if (flush) fflush(file_); + } +}; + +#if !defined(_WIN32) || defined(FMT_USE_WRITE_CONSOLE) +FMT_FUNC auto write_console(int, string_view) -> bool { return false; } +#else +using dword = conditional_t; +extern "C" __declspec(dllimport) int __stdcall WriteConsoleW( // + void*, const void*, dword, dword*, void*); + +FMT_FUNC bool write_console(int fd, string_view text) { + auto u16 = utf8_to_utf16(text); + return WriteConsoleW(reinterpret_cast(_get_osfhandle(fd)), u16.c_str(), + static_cast(u16.size()), nullptr, nullptr) != 0; +} +#endif + +#ifdef _WIN32 +// Print assuming legacy (non-Unicode) encoding. +FMT_FUNC void vprint_mojibake(std::FILE* f, string_view fmt, format_args args, + bool newline) { + auto buffer = memory_buffer(); + detail::vformat_to(buffer, fmt, args); + if (newline) buffer.push_back('\n'); + fwrite_all(buffer.data(), buffer.size(), f); +} +#endif + +FMT_FUNC void print(std::FILE* f, string_view text) { +#if defined(_WIN32) && !defined(FMT_USE_WRITE_CONSOLE) + int fd = _fileno(f); + if (_isatty(fd)) { + std::fflush(f); + if (write_console(fd, text)) return; + } +#endif + fwrite_all(text.data(), text.size(), f); +} +} // namespace detail + +FMT_FUNC void vprint_buffered(std::FILE* f, string_view fmt, format_args args) { + auto buffer = memory_buffer(); + detail::vformat_to(buffer, fmt, args); + detail::print(f, {buffer.data(), buffer.size()}); +} + +FMT_FUNC void vprint(std::FILE* f, string_view fmt, format_args args) { + if (!detail::file_ref(f).is_buffered() || !detail::has_flockfile<>()) + return vprint_buffered(f, fmt, args); + auto&& buffer = detail::file_print_buffer<>(f); + return detail::vformat_to(buffer, fmt, args); +} + +FMT_FUNC void vprintln(std::FILE* f, string_view fmt, format_args args) { + auto buffer = memory_buffer(); + detail::vformat_to(buffer, fmt, args); + buffer.push_back('\n'); + detail::print(f, {buffer.data(), buffer.size()}); +} + +FMT_FUNC void vprint(string_view fmt, format_args args) { + vprint(stdout, fmt, args); +} + +namespace detail { + +struct singleton { + unsigned char upper; + unsigned char lower_count; +}; + +inline auto is_printable(uint16_t x, const singleton* singletons, + size_t singletons_size, + const unsigned char* singleton_lowers, + const unsigned char* normal, size_t normal_size) + -> bool { + auto upper = x >> 8; + auto lower_start = 0; + for (size_t i = 0; i < singletons_size; ++i) { + auto s = singletons[i]; + auto lower_end = lower_start + s.lower_count; + if (upper < s.upper) break; + if (upper == s.upper) { + for (auto j = lower_start; j < lower_end; ++j) { + if (singleton_lowers[j] == (x & 0xff)) return false; + } + } + lower_start = lower_end; + } + + auto xsigned = static_cast(x); + auto current = true; + for (size_t i = 0; i < normal_size; ++i) { + auto v = static_cast(normal[i]); + auto len = (v & 0x80) != 0 ? (v & 0x7f) << 8 | normal[++i] : v; + xsigned -= len; + if (xsigned < 0) break; + current = !current; + } + return current; +} + +// This code is generated by support/printable.py. +FMT_FUNC auto is_printable(uint32_t cp) -> bool { + static constexpr singleton singletons0[] = { + {0x00, 1}, {0x03, 5}, {0x05, 6}, {0x06, 3}, {0x07, 6}, {0x08, 8}, + {0x09, 17}, {0x0a, 28}, {0x0b, 25}, {0x0c, 20}, {0x0d, 16}, {0x0e, 13}, + {0x0f, 4}, {0x10, 3}, {0x12, 18}, {0x13, 9}, {0x16, 1}, {0x17, 5}, + {0x18, 2}, {0x19, 3}, {0x1a, 7}, {0x1c, 2}, {0x1d, 1}, {0x1f, 22}, + {0x20, 3}, {0x2b, 3}, {0x2c, 2}, {0x2d, 11}, {0x2e, 1}, {0x30, 3}, + {0x31, 2}, {0x32, 1}, {0xa7, 2}, {0xa9, 2}, {0xaa, 4}, {0xab, 8}, + {0xfa, 2}, {0xfb, 5}, {0xfd, 4}, {0xfe, 3}, {0xff, 9}, + }; + static constexpr unsigned char singletons0_lower[] = { + 0xad, 0x78, 0x79, 0x8b, 0x8d, 0xa2, 0x30, 0x57, 0x58, 0x8b, 0x8c, 0x90, + 0x1c, 0x1d, 0xdd, 0x0e, 0x0f, 0x4b, 0x4c, 0xfb, 0xfc, 0x2e, 0x2f, 0x3f, + 0x5c, 0x5d, 0x5f, 0xb5, 0xe2, 0x84, 0x8d, 0x8e, 0x91, 0x92, 0xa9, 0xb1, + 0xba, 0xbb, 0xc5, 0xc6, 0xc9, 0xca, 0xde, 0xe4, 0xe5, 0xff, 0x00, 0x04, + 0x11, 0x12, 0x29, 0x31, 0x34, 0x37, 0x3a, 0x3b, 0x3d, 0x49, 0x4a, 0x5d, + 0x84, 0x8e, 0x92, 0xa9, 0xb1, 0xb4, 0xba, 0xbb, 0xc6, 0xca, 0xce, 0xcf, + 0xe4, 0xe5, 0x00, 0x04, 0x0d, 0x0e, 0x11, 0x12, 0x29, 0x31, 0x34, 0x3a, + 0x3b, 0x45, 0x46, 0x49, 0x4a, 0x5e, 0x64, 0x65, 0x84, 0x91, 0x9b, 0x9d, + 0xc9, 0xce, 0xcf, 0x0d, 0x11, 0x29, 0x45, 0x49, 0x57, 0x64, 0x65, 0x8d, + 0x91, 0xa9, 0xb4, 0xba, 0xbb, 0xc5, 0xc9, 0xdf, 0xe4, 0xe5, 0xf0, 0x0d, + 0x11, 0x45, 0x49, 0x64, 0x65, 0x80, 0x84, 0xb2, 0xbc, 0xbe, 0xbf, 0xd5, + 0xd7, 0xf0, 0xf1, 0x83, 0x85, 0x8b, 0xa4, 0xa6, 0xbe, 0xbf, 0xc5, 0xc7, + 0xce, 0xcf, 0xda, 0xdb, 0x48, 0x98, 0xbd, 0xcd, 0xc6, 0xce, 0xcf, 0x49, + 0x4e, 0x4f, 0x57, 0x59, 0x5e, 0x5f, 0x89, 0x8e, 0x8f, 0xb1, 0xb6, 0xb7, + 0xbf, 0xc1, 0xc6, 0xc7, 0xd7, 0x11, 0x16, 0x17, 0x5b, 0x5c, 0xf6, 0xf7, + 0xfe, 0xff, 0x80, 0x0d, 0x6d, 0x71, 0xde, 0xdf, 0x0e, 0x0f, 0x1f, 0x6e, + 0x6f, 0x1c, 0x1d, 0x5f, 0x7d, 0x7e, 0xae, 0xaf, 0xbb, 0xbc, 0xfa, 0x16, + 0x17, 0x1e, 0x1f, 0x46, 0x47, 0x4e, 0x4f, 0x58, 0x5a, 0x5c, 0x5e, 0x7e, + 0x7f, 0xb5, 0xc5, 0xd4, 0xd5, 0xdc, 0xf0, 0xf1, 0xf5, 0x72, 0x73, 0x8f, + 0x74, 0x75, 0x96, 0x2f, 0x5f, 0x26, 0x2e, 0x2f, 0xa7, 0xaf, 0xb7, 0xbf, + 0xc7, 0xcf, 0xd7, 0xdf, 0x9a, 0x40, 0x97, 0x98, 0x30, 0x8f, 0x1f, 0xc0, + 0xc1, 0xce, 0xff, 0x4e, 0x4f, 0x5a, 0x5b, 0x07, 0x08, 0x0f, 0x10, 0x27, + 0x2f, 0xee, 0xef, 0x6e, 0x6f, 0x37, 0x3d, 0x3f, 0x42, 0x45, 0x90, 0x91, + 0xfe, 0xff, 0x53, 0x67, 0x75, 0xc8, 0xc9, 0xd0, 0xd1, 0xd8, 0xd9, 0xe7, + 0xfe, 0xff, + }; + static constexpr singleton singletons1[] = { + {0x00, 6}, {0x01, 1}, {0x03, 1}, {0x04, 2}, {0x08, 8}, {0x09, 2}, + {0x0a, 5}, {0x0b, 2}, {0x0e, 4}, {0x10, 1}, {0x11, 2}, {0x12, 5}, + {0x13, 17}, {0x14, 1}, {0x15, 2}, {0x17, 2}, {0x19, 13}, {0x1c, 5}, + {0x1d, 8}, {0x24, 1}, {0x6a, 3}, {0x6b, 2}, {0xbc, 2}, {0xd1, 2}, + {0xd4, 12}, {0xd5, 9}, {0xd6, 2}, {0xd7, 2}, {0xda, 1}, {0xe0, 5}, + {0xe1, 2}, {0xe8, 2}, {0xee, 32}, {0xf0, 4}, {0xf8, 2}, {0xf9, 2}, + {0xfa, 2}, {0xfb, 1}, + }; + static constexpr unsigned char singletons1_lower[] = { + 0x0c, 0x27, 0x3b, 0x3e, 0x4e, 0x4f, 0x8f, 0x9e, 0x9e, 0x9f, 0x06, 0x07, + 0x09, 0x36, 0x3d, 0x3e, 0x56, 0xf3, 0xd0, 0xd1, 0x04, 0x14, 0x18, 0x36, + 0x37, 0x56, 0x57, 0x7f, 0xaa, 0xae, 0xaf, 0xbd, 0x35, 0xe0, 0x12, 0x87, + 0x89, 0x8e, 0x9e, 0x04, 0x0d, 0x0e, 0x11, 0x12, 0x29, 0x31, 0x34, 0x3a, + 0x45, 0x46, 0x49, 0x4a, 0x4e, 0x4f, 0x64, 0x65, 0x5c, 0xb6, 0xb7, 0x1b, + 0x1c, 0x07, 0x08, 0x0a, 0x0b, 0x14, 0x17, 0x36, 0x39, 0x3a, 0xa8, 0xa9, + 0xd8, 0xd9, 0x09, 0x37, 0x90, 0x91, 0xa8, 0x07, 0x0a, 0x3b, 0x3e, 0x66, + 0x69, 0x8f, 0x92, 0x6f, 0x5f, 0xee, 0xef, 0x5a, 0x62, 0x9a, 0x9b, 0x27, + 0x28, 0x55, 0x9d, 0xa0, 0xa1, 0xa3, 0xa4, 0xa7, 0xa8, 0xad, 0xba, 0xbc, + 0xc4, 0x06, 0x0b, 0x0c, 0x15, 0x1d, 0x3a, 0x3f, 0x45, 0x51, 0xa6, 0xa7, + 0xcc, 0xcd, 0xa0, 0x07, 0x19, 0x1a, 0x22, 0x25, 0x3e, 0x3f, 0xc5, 0xc6, + 0x04, 0x20, 0x23, 0x25, 0x26, 0x28, 0x33, 0x38, 0x3a, 0x48, 0x4a, 0x4c, + 0x50, 0x53, 0x55, 0x56, 0x58, 0x5a, 0x5c, 0x5e, 0x60, 0x63, 0x65, 0x66, + 0x6b, 0x73, 0x78, 0x7d, 0x7f, 0x8a, 0xa4, 0xaa, 0xaf, 0xb0, 0xc0, 0xd0, + 0xae, 0xaf, 0x79, 0xcc, 0x6e, 0x6f, 0x93, + }; + static constexpr unsigned char normal0[] = { + 0x00, 0x20, 0x5f, 0x22, 0x82, 0xdf, 0x04, 0x82, 0x44, 0x08, 0x1b, 0x04, + 0x06, 0x11, 0x81, 0xac, 0x0e, 0x80, 0xab, 0x35, 0x28, 0x0b, 0x80, 0xe0, + 0x03, 0x19, 0x08, 0x01, 0x04, 0x2f, 0x04, 0x34, 0x04, 0x07, 0x03, 0x01, + 0x07, 0x06, 0x07, 0x11, 0x0a, 0x50, 0x0f, 0x12, 0x07, 0x55, 0x07, 0x03, + 0x04, 0x1c, 0x0a, 0x09, 0x03, 0x08, 0x03, 0x07, 0x03, 0x02, 0x03, 0x03, + 0x03, 0x0c, 0x04, 0x05, 0x03, 0x0b, 0x06, 0x01, 0x0e, 0x15, 0x05, 0x3a, + 0x03, 0x11, 0x07, 0x06, 0x05, 0x10, 0x07, 0x57, 0x07, 0x02, 0x07, 0x15, + 0x0d, 0x50, 0x04, 0x43, 0x03, 0x2d, 0x03, 0x01, 0x04, 0x11, 0x06, 0x0f, + 0x0c, 0x3a, 0x04, 0x1d, 0x25, 0x5f, 0x20, 0x6d, 0x04, 0x6a, 0x25, 0x80, + 0xc8, 0x05, 0x82, 0xb0, 0x03, 0x1a, 0x06, 0x82, 0xfd, 0x03, 0x59, 0x07, + 0x15, 0x0b, 0x17, 0x09, 0x14, 0x0c, 0x14, 0x0c, 0x6a, 0x06, 0x0a, 0x06, + 0x1a, 0x06, 0x59, 0x07, 0x2b, 0x05, 0x46, 0x0a, 0x2c, 0x04, 0x0c, 0x04, + 0x01, 0x03, 0x31, 0x0b, 0x2c, 0x04, 0x1a, 0x06, 0x0b, 0x03, 0x80, 0xac, + 0x06, 0x0a, 0x06, 0x21, 0x3f, 0x4c, 0x04, 0x2d, 0x03, 0x74, 0x08, 0x3c, + 0x03, 0x0f, 0x03, 0x3c, 0x07, 0x38, 0x08, 0x2b, 0x05, 0x82, 0xff, 0x11, + 0x18, 0x08, 0x2f, 0x11, 0x2d, 0x03, 0x20, 0x10, 0x21, 0x0f, 0x80, 0x8c, + 0x04, 0x82, 0x97, 0x19, 0x0b, 0x15, 0x88, 0x94, 0x05, 0x2f, 0x05, 0x3b, + 0x07, 0x02, 0x0e, 0x18, 0x09, 0x80, 0xb3, 0x2d, 0x74, 0x0c, 0x80, 0xd6, + 0x1a, 0x0c, 0x05, 0x80, 0xff, 0x05, 0x80, 0xdf, 0x0c, 0xee, 0x0d, 0x03, + 0x84, 0x8d, 0x03, 0x37, 0x09, 0x81, 0x5c, 0x14, 0x80, 0xb8, 0x08, 0x80, + 0xcb, 0x2a, 0x38, 0x03, 0x0a, 0x06, 0x38, 0x08, 0x46, 0x08, 0x0c, 0x06, + 0x74, 0x0b, 0x1e, 0x03, 0x5a, 0x04, 0x59, 0x09, 0x80, 0x83, 0x18, 0x1c, + 0x0a, 0x16, 0x09, 0x4c, 0x04, 0x80, 0x8a, 0x06, 0xab, 0xa4, 0x0c, 0x17, + 0x04, 0x31, 0xa1, 0x04, 0x81, 0xda, 0x26, 0x07, 0x0c, 0x05, 0x05, 0x80, + 0xa5, 0x11, 0x81, 0x6d, 0x10, 0x78, 0x28, 0x2a, 0x06, 0x4c, 0x04, 0x80, + 0x8d, 0x04, 0x80, 0xbe, 0x03, 0x1b, 0x03, 0x0f, 0x0d, + }; + static constexpr unsigned char normal1[] = { + 0x5e, 0x22, 0x7b, 0x05, 0x03, 0x04, 0x2d, 0x03, 0x66, 0x03, 0x01, 0x2f, + 0x2e, 0x80, 0x82, 0x1d, 0x03, 0x31, 0x0f, 0x1c, 0x04, 0x24, 0x09, 0x1e, + 0x05, 0x2b, 0x05, 0x44, 0x04, 0x0e, 0x2a, 0x80, 0xaa, 0x06, 0x24, 0x04, + 0x24, 0x04, 0x28, 0x08, 0x34, 0x0b, 0x01, 0x80, 0x90, 0x81, 0x37, 0x09, + 0x16, 0x0a, 0x08, 0x80, 0x98, 0x39, 0x03, 0x63, 0x08, 0x09, 0x30, 0x16, + 0x05, 0x21, 0x03, 0x1b, 0x05, 0x01, 0x40, 0x38, 0x04, 0x4b, 0x05, 0x2f, + 0x04, 0x0a, 0x07, 0x09, 0x07, 0x40, 0x20, 0x27, 0x04, 0x0c, 0x09, 0x36, + 0x03, 0x3a, 0x05, 0x1a, 0x07, 0x04, 0x0c, 0x07, 0x50, 0x49, 0x37, 0x33, + 0x0d, 0x33, 0x07, 0x2e, 0x08, 0x0a, 0x81, 0x26, 0x52, 0x4e, 0x28, 0x08, + 0x2a, 0x56, 0x1c, 0x14, 0x17, 0x09, 0x4e, 0x04, 0x1e, 0x0f, 0x43, 0x0e, + 0x19, 0x07, 0x0a, 0x06, 0x48, 0x08, 0x27, 0x09, 0x75, 0x0b, 0x3f, 0x41, + 0x2a, 0x06, 0x3b, 0x05, 0x0a, 0x06, 0x51, 0x06, 0x01, 0x05, 0x10, 0x03, + 0x05, 0x80, 0x8b, 0x62, 0x1e, 0x48, 0x08, 0x0a, 0x80, 0xa6, 0x5e, 0x22, + 0x45, 0x0b, 0x0a, 0x06, 0x0d, 0x13, 0x39, 0x07, 0x0a, 0x36, 0x2c, 0x04, + 0x10, 0x80, 0xc0, 0x3c, 0x64, 0x53, 0x0c, 0x48, 0x09, 0x0a, 0x46, 0x45, + 0x1b, 0x48, 0x08, 0x53, 0x1d, 0x39, 0x81, 0x07, 0x46, 0x0a, 0x1d, 0x03, + 0x47, 0x49, 0x37, 0x03, 0x0e, 0x08, 0x0a, 0x06, 0x39, 0x07, 0x0a, 0x81, + 0x36, 0x19, 0x80, 0xb7, 0x01, 0x0f, 0x32, 0x0d, 0x83, 0x9b, 0x66, 0x75, + 0x0b, 0x80, 0xc4, 0x8a, 0xbc, 0x84, 0x2f, 0x8f, 0xd1, 0x82, 0x47, 0xa1, + 0xb9, 0x82, 0x39, 0x07, 0x2a, 0x04, 0x02, 0x60, 0x26, 0x0a, 0x46, 0x0a, + 0x28, 0x05, 0x13, 0x82, 0xb0, 0x5b, 0x65, 0x4b, 0x04, 0x39, 0x07, 0x11, + 0x40, 0x05, 0x0b, 0x02, 0x0e, 0x97, 0xf8, 0x08, 0x84, 0xd6, 0x2a, 0x09, + 0xa2, 0xf7, 0x81, 0x1f, 0x31, 0x03, 0x11, 0x04, 0x08, 0x81, 0x8c, 0x89, + 0x04, 0x6b, 0x05, 0x0d, 0x03, 0x09, 0x07, 0x10, 0x93, 0x60, 0x80, 0xf6, + 0x0a, 0x73, 0x08, 0x6e, 0x17, 0x46, 0x80, 0x9a, 0x14, 0x0c, 0x57, 0x09, + 0x19, 0x80, 0x87, 0x81, 0x47, 0x03, 0x85, 0x42, 0x0f, 0x15, 0x85, 0x50, + 0x2b, 0x80, 0xd5, 0x2d, 0x03, 0x1a, 0x04, 0x02, 0x81, 0x70, 0x3a, 0x05, + 0x01, 0x85, 0x00, 0x80, 0xd7, 0x29, 0x4c, 0x04, 0x0a, 0x04, 0x02, 0x83, + 0x11, 0x44, 0x4c, 0x3d, 0x80, 0xc2, 0x3c, 0x06, 0x01, 0x04, 0x55, 0x05, + 0x1b, 0x34, 0x02, 0x81, 0x0e, 0x2c, 0x04, 0x64, 0x0c, 0x56, 0x0a, 0x80, + 0xae, 0x38, 0x1d, 0x0d, 0x2c, 0x04, 0x09, 0x07, 0x02, 0x0e, 0x06, 0x80, + 0x9a, 0x83, 0xd8, 0x08, 0x0d, 0x03, 0x0d, 0x03, 0x74, 0x0c, 0x59, 0x07, + 0x0c, 0x14, 0x0c, 0x04, 0x38, 0x08, 0x0a, 0x06, 0x28, 0x08, 0x22, 0x4e, + 0x81, 0x54, 0x0c, 0x15, 0x03, 0x03, 0x05, 0x07, 0x09, 0x19, 0x07, 0x07, + 0x09, 0x03, 0x0d, 0x07, 0x29, 0x80, 0xcb, 0x25, 0x0a, 0x84, 0x06, + }; + auto lower = static_cast(cp); + if (cp < 0x10000) { + return is_printable(lower, singletons0, + sizeof(singletons0) / sizeof(*singletons0), + singletons0_lower, normal0, sizeof(normal0)); + } + if (cp < 0x20000) { + return is_printable(lower, singletons1, + sizeof(singletons1) / sizeof(*singletons1), + singletons1_lower, normal1, sizeof(normal1)); + } + if (0x2a6de <= cp && cp < 0x2a700) return false; + if (0x2b735 <= cp && cp < 0x2b740) return false; + if (0x2b81e <= cp && cp < 0x2b820) return false; + if (0x2cea2 <= cp && cp < 0x2ceb0) return false; + if (0x2ebe1 <= cp && cp < 0x2f800) return false; + if (0x2fa1e <= cp && cp < 0x30000) return false; + if (0x3134b <= cp && cp < 0xe0100) return false; + if (0xe01f0 <= cp && cp < 0x110000) return false; + return cp < 0x110000; +} + +} // namespace detail + +FMT_END_NAMESPACE + +#endif // FMT_FORMAT_INL_H_ diff --git a/sdk/samples/asrun/vendor/fmt/format.h b/sdk/samples/asrun/vendor/fmt/format.h new file mode 100644 index 000000000..50e571442 --- /dev/null +++ b/sdk/samples/asrun/vendor/fmt/format.h @@ -0,0 +1,4244 @@ +/* + Formatting library for C++ + + Copyright (c) 2012 - present, Victor Zverovich + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + 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 AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + --- Optional exception to the license --- + + As an exception, if, as a result of your compiling your source code, portions + of this Software are embedded into a machine-executable object form of such + source code, you may redistribute such embedded portions in such object form + without including the above copyright and permission notices. + */ + +#ifndef FMT_FORMAT_H_ +#define FMT_FORMAT_H_ + +#ifndef _LIBCPP_REMOVE_TRANSITIVE_INCLUDES +# define _LIBCPP_REMOVE_TRANSITIVE_INCLUDES +# define FMT_REMOVE_TRANSITIVE_INCLUDES +#endif + +#include "base.h" + +#ifndef FMT_MODULE +# include // std::signbit +# include // std::byte +# include // uint32_t +# include // std::memcpy +# include // std::numeric_limits +# include // std::bad_alloc +# if defined(__GLIBCXX__) && !defined(_GLIBCXX_USE_DUAL_ABI) +// Workaround for pre gcc 5 libstdc++. +# include // std::allocator_traits +# endif +# include // std::runtime_error +# include // std::string +# include // std::system_error + +// Check FMT_CPLUSPLUS to avoid a warning in MSVC. +# if FMT_HAS_INCLUDE() && FMT_CPLUSPLUS > 201703L +# include // std::bit_cast +# endif + +// libc++ supports string_view in pre-c++17. +# if FMT_HAS_INCLUDE() && \ + (FMT_CPLUSPLUS >= 201703L || defined(_LIBCPP_VERSION)) +# include +# define FMT_USE_STRING_VIEW +# endif + +# if FMT_MSC_VERSION +# include // _BitScanReverse[64], _umul128 +# endif +#endif // FMT_MODULE + +#if defined(FMT_USE_NONTYPE_TEMPLATE_ARGS) +// Use the provided definition. +#elif defined(__NVCOMPILER) +# define FMT_USE_NONTYPE_TEMPLATE_ARGS 0 +#elif FMT_GCC_VERSION >= 903 && FMT_CPLUSPLUS >= 201709L +# define FMT_USE_NONTYPE_TEMPLATE_ARGS 1 +#elif defined(__cpp_nontype_template_args) && \ + __cpp_nontype_template_args >= 201911L +# define FMT_USE_NONTYPE_TEMPLATE_ARGS 1 +#elif FMT_CLANG_VERSION >= 1200 && FMT_CPLUSPLUS >= 202002L +# define FMT_USE_NONTYPE_TEMPLATE_ARGS 1 +#else +# define FMT_USE_NONTYPE_TEMPLATE_ARGS 0 +#endif + +#if defined __cpp_inline_variables && __cpp_inline_variables >= 201606L +# define FMT_INLINE_VARIABLE inline +#else +# define FMT_INLINE_VARIABLE +#endif + +// Check if RTTI is disabled. +#ifdef FMT_USE_RTTI +// Use the provided definition. +#elif defined(__GXX_RTTI) || FMT_HAS_FEATURE(cxx_rtti) || defined(_CPPRTTI) || \ + defined(__INTEL_RTTI__) || defined(__RTTI) +// __RTTI is for EDG compilers. _CPPRTTI is for MSVC. +# define FMT_USE_RTTI 1 +#else +# define FMT_USE_RTTI 0 +#endif + +// Visibility when compiled as a shared library/object. +#if defined(FMT_LIB_EXPORT) || defined(FMT_SHARED) +# define FMT_SO_VISIBILITY(value) FMT_VISIBILITY(value) +#else +# define FMT_SO_VISIBILITY(value) +#endif + +#if FMT_GCC_VERSION || FMT_CLANG_VERSION +# define FMT_NOINLINE __attribute__((noinline)) +#else +# define FMT_NOINLINE +#endif + +// GCC 4.9 doesn't support qualified names in specializations. +namespace std { +template struct iterator_traits> { + using iterator_category = output_iterator_tag; + using value_type = T; + using difference_type = + decltype(static_cast(nullptr) - static_cast(nullptr)); + using pointer = void; + using reference = void; +}; +} // namespace std + +#ifndef FMT_THROW +# if FMT_USE_EXCEPTIONS +# if FMT_MSC_VERSION || defined(__NVCC__) +FMT_BEGIN_NAMESPACE +namespace detail { +template inline void do_throw(const Exception& x) { + // Silence unreachable code warnings in MSVC and NVCC because these + // are nearly impossible to fix in a generic code. + volatile bool b = true; + if (b) throw x; +} +} // namespace detail +FMT_END_NAMESPACE +# define FMT_THROW(x) detail::do_throw(x) +# else +# define FMT_THROW(x) throw x +# endif +# else +# define FMT_THROW(x) \ + ::fmt::detail::assert_fail(__FILE__, __LINE__, (x).what()) +# endif // FMT_USE_EXCEPTIONS +#endif // FMT_THROW + +// Defining FMT_REDUCE_INT_INSTANTIATIONS to 1, will reduce the number of +// integer formatter template instantiations to just one by only using the +// largest integer type. This results in a reduction in binary size but will +// cause a decrease in integer formatting performance. +#if !defined(FMT_REDUCE_INT_INSTANTIATIONS) +# define FMT_REDUCE_INT_INSTANTIATIONS 0 +#endif + +FMT_BEGIN_NAMESPACE + +template +struct is_contiguous> + : std::true_type {}; + +namespace detail { + +// __builtin_clz is broken in clang with Microsoft codegen: +// https://github.com/fmtlib/fmt/issues/519. +#if !FMT_MSC_VERSION +# if FMT_HAS_BUILTIN(__builtin_clz) || FMT_GCC_VERSION || FMT_ICC_VERSION +# define FMT_BUILTIN_CLZ(n) __builtin_clz(n) +# endif +# if FMT_HAS_BUILTIN(__builtin_clzll) || FMT_GCC_VERSION || FMT_ICC_VERSION +# define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n) +# endif +#endif + +// Some compilers masquerade as both MSVC and GCC but otherwise support +// __builtin_clz and __builtin_clzll, so only define FMT_BUILTIN_CLZ using the +// MSVC intrinsics if the clz and clzll builtins are not available. +#if FMT_MSC_VERSION && !defined(FMT_BUILTIN_CLZLL) +// Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning. +# ifndef __clang__ +# pragma intrinsic(_BitScanReverse) +# ifdef _WIN64 +# pragma intrinsic(_BitScanReverse64) +# endif +# endif + +inline auto clz(uint32_t x) -> int { + FMT_ASSERT(x != 0, ""); + FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning. + unsigned long r = 0; + _BitScanReverse(&r, x); + return 31 ^ static_cast(r); +} +# define FMT_BUILTIN_CLZ(n) detail::clz(n) + +inline auto clzll(uint64_t x) -> int { + FMT_ASSERT(x != 0, ""); + FMT_MSC_WARNING(suppress : 6102) // Suppress a bogus static analysis warning. + unsigned long r = 0; +# ifdef _WIN64 + _BitScanReverse64(&r, x); +# else + // Scan the high 32 bits. + if (_BitScanReverse(&r, static_cast(x >> 32))) + return 63 ^ static_cast(r + 32); + // Scan the low 32 bits. + _BitScanReverse(&r, static_cast(x)); +# endif + return 63 ^ static_cast(r); +} +# define FMT_BUILTIN_CLZLL(n) detail::clzll(n) +#endif // FMT_MSC_VERSION && !defined(FMT_BUILTIN_CLZLL) + +FMT_CONSTEXPR inline void abort_fuzzing_if(bool condition) { + ignore_unused(condition); +#ifdef FMT_FUZZ + if (condition) throw std::runtime_error("fuzzing limit reached"); +#endif +} + +#if defined(FMT_USE_STRING_VIEW) +template using std_string_view = std::basic_string_view; +#else +template struct std_string_view { + operator basic_string_view() const; +}; +#endif + +template struct string_literal { + static constexpr Char value[sizeof...(C)] = {C...}; + constexpr operator basic_string_view() const { + return {value, sizeof...(C)}; + } +}; +#if FMT_CPLUSPLUS < 201703L +template +constexpr Char string_literal::value[sizeof...(C)]; +#endif + +// Implementation of std::bit_cast for pre-C++20. +template +FMT_CONSTEXPR20 auto bit_cast(const From& from) -> To { +#ifdef __cpp_lib_bit_cast + if (is_constant_evaluated()) return std::bit_cast(from); +#endif + auto to = To(); + // The cast suppresses a bogus -Wclass-memaccess on GCC. + std::memcpy(static_cast(&to), &from, sizeof(to)); + return to; +} + +inline auto is_big_endian() -> bool { +#ifdef _WIN32 + return false; +#elif defined(__BIG_ENDIAN__) + return true; +#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) + return __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__; +#else + struct bytes { + char data[sizeof(int)]; + }; + return bit_cast(1).data[0] == 0; +#endif +} + +class uint128_fallback { + private: + uint64_t lo_, hi_; + + public: + constexpr uint128_fallback(uint64_t hi, uint64_t lo) : lo_(lo), hi_(hi) {} + constexpr uint128_fallback(uint64_t value = 0) : lo_(value), hi_(0) {} + + constexpr auto high() const noexcept -> uint64_t { return hi_; } + constexpr auto low() const noexcept -> uint64_t { return lo_; } + + template ::value)> + constexpr explicit operator T() const { + return static_cast(lo_); + } + + friend constexpr auto operator==(const uint128_fallback& lhs, + const uint128_fallback& rhs) -> bool { + return lhs.hi_ == rhs.hi_ && lhs.lo_ == rhs.lo_; + } + friend constexpr auto operator!=(const uint128_fallback& lhs, + const uint128_fallback& rhs) -> bool { + return !(lhs == rhs); + } + friend constexpr auto operator>(const uint128_fallback& lhs, + const uint128_fallback& rhs) -> bool { + return lhs.hi_ != rhs.hi_ ? lhs.hi_ > rhs.hi_ : lhs.lo_ > rhs.lo_; + } + friend constexpr auto operator|(const uint128_fallback& lhs, + const uint128_fallback& rhs) + -> uint128_fallback { + return {lhs.hi_ | rhs.hi_, lhs.lo_ | rhs.lo_}; + } + friend constexpr auto operator&(const uint128_fallback& lhs, + const uint128_fallback& rhs) + -> uint128_fallback { + return {lhs.hi_ & rhs.hi_, lhs.lo_ & rhs.lo_}; + } + friend constexpr auto operator~(const uint128_fallback& n) + -> uint128_fallback { + return {~n.hi_, ~n.lo_}; + } + friend FMT_CONSTEXPR auto operator+(const uint128_fallback& lhs, + const uint128_fallback& rhs) + -> uint128_fallback { + auto result = uint128_fallback(lhs); + result += rhs; + return result; + } + friend FMT_CONSTEXPR auto operator*(const uint128_fallback& lhs, uint32_t rhs) + -> uint128_fallback { + FMT_ASSERT(lhs.hi_ == 0, ""); + uint64_t hi = (lhs.lo_ >> 32) * rhs; + uint64_t lo = (lhs.lo_ & ~uint32_t()) * rhs; + uint64_t new_lo = (hi << 32) + lo; + return {(hi >> 32) + (new_lo < lo ? 1 : 0), new_lo}; + } + friend constexpr auto operator-(const uint128_fallback& lhs, uint64_t rhs) + -> uint128_fallback { + return {lhs.hi_ - (lhs.lo_ < rhs ? 1 : 0), lhs.lo_ - rhs}; + } + FMT_CONSTEXPR auto operator>>(int shift) const -> uint128_fallback { + if (shift == 64) return {0, hi_}; + if (shift > 64) return uint128_fallback(0, hi_) >> (shift - 64); + return {hi_ >> shift, (hi_ << (64 - shift)) | (lo_ >> shift)}; + } + FMT_CONSTEXPR auto operator<<(int shift) const -> uint128_fallback { + if (shift == 64) return {lo_, 0}; + if (shift > 64) return uint128_fallback(lo_, 0) << (shift - 64); + return {hi_ << shift | (lo_ >> (64 - shift)), (lo_ << shift)}; + } + FMT_CONSTEXPR auto operator>>=(int shift) -> uint128_fallback& { + return *this = *this >> shift; + } + FMT_CONSTEXPR void operator+=(uint128_fallback n) { + uint64_t new_lo = lo_ + n.lo_; + uint64_t new_hi = hi_ + n.hi_ + (new_lo < lo_ ? 1 : 0); + FMT_ASSERT(new_hi >= hi_, ""); + lo_ = new_lo; + hi_ = new_hi; + } + FMT_CONSTEXPR void operator&=(uint128_fallback n) { + lo_ &= n.lo_; + hi_ &= n.hi_; + } + + FMT_CONSTEXPR20 auto operator+=(uint64_t n) noexcept -> uint128_fallback& { + if (is_constant_evaluated()) { + lo_ += n; + hi_ += (lo_ < n ? 1 : 0); + return *this; + } +#if FMT_HAS_BUILTIN(__builtin_addcll) && !defined(__ibmxl__) + unsigned long long carry; + lo_ = __builtin_addcll(lo_, n, 0, &carry); + hi_ += carry; +#elif FMT_HAS_BUILTIN(__builtin_ia32_addcarryx_u64) && !defined(__ibmxl__) + unsigned long long result; + auto carry = __builtin_ia32_addcarryx_u64(0, lo_, n, &result); + lo_ = result; + hi_ += carry; +#elif defined(_MSC_VER) && defined(_M_X64) + auto carry = _addcarry_u64(0, lo_, n, &lo_); + _addcarry_u64(carry, hi_, 0, &hi_); +#else + lo_ += n; + hi_ += (lo_ < n ? 1 : 0); +#endif + return *this; + } +}; + +using uint128_t = conditional_t; + +#ifdef UINTPTR_MAX +using uintptr_t = ::uintptr_t; +#else +using uintptr_t = uint128_t; +#endif + +// Returns the largest possible value for type T. Same as +// std::numeric_limits::max() but shorter and not affected by the max macro. +template constexpr auto max_value() -> T { + return (std::numeric_limits::max)(); +} +template constexpr auto num_bits() -> int { + return std::numeric_limits::digits; +} +// std::numeric_limits::digits may return 0 for 128-bit ints. +template <> constexpr auto num_bits() -> int { return 128; } +template <> constexpr auto num_bits() -> int { return 128; } +template <> constexpr auto num_bits() -> int { return 128; } + +// A heterogeneous bit_cast used for converting 96-bit long double to uint128_t +// and 128-bit pointers to uint128_fallback. +template sizeof(From))> +inline auto bit_cast(const From& from) -> To { + constexpr auto size = static_cast(sizeof(From) / sizeof(unsigned short)); + struct data_t { + unsigned short value[static_cast(size)]; + } data = bit_cast(from); + auto result = To(); + if (const_check(is_big_endian())) { + for (int i = 0; i < size; ++i) + result = (result << num_bits()) | data.value[i]; + } else { + for (int i = size - 1; i >= 0; --i) + result = (result << num_bits()) | data.value[i]; + } + return result; +} + +template +FMT_CONSTEXPR20 inline auto countl_zero_fallback(UInt n) -> int { + int lz = 0; + constexpr UInt msb_mask = static_cast(1) << (num_bits() - 1); + for (; (n & msb_mask) == 0; n <<= 1) lz++; + return lz; +} + +FMT_CONSTEXPR20 inline auto countl_zero(uint32_t n) -> int { +#ifdef FMT_BUILTIN_CLZ + if (!is_constant_evaluated()) return FMT_BUILTIN_CLZ(n); +#endif + return countl_zero_fallback(n); +} + +FMT_CONSTEXPR20 inline auto countl_zero(uint64_t n) -> int { +#ifdef FMT_BUILTIN_CLZLL + if (!is_constant_evaluated()) return FMT_BUILTIN_CLZLL(n); +#endif + return countl_zero_fallback(n); +} + +FMT_INLINE void assume(bool condition) { + (void)condition; +#if FMT_HAS_BUILTIN(__builtin_assume) && !FMT_ICC_VERSION + __builtin_assume(condition); +#elif FMT_GCC_VERSION + if (!condition) __builtin_unreachable(); +#endif +} + +// Attempts to reserve space for n extra characters in the output range. +// Returns a pointer to the reserved range or a reference to it. +template ::value&& + is_contiguous::value)> +#if FMT_CLANG_VERSION >= 307 && !FMT_ICC_VERSION +__attribute__((no_sanitize("undefined"))) +#endif +FMT_CONSTEXPR20 inline auto +reserve(OutputIt it, size_t n) -> typename OutputIt::value_type* { + auto& c = get_container(it); + size_t size = c.size(); + c.resize(size + n); + return &c[size]; +} + +template +FMT_CONSTEXPR20 inline auto reserve(basic_appender it, size_t n) + -> basic_appender { + buffer& buf = get_container(it); + buf.try_reserve(buf.size() + n); + return it; +} + +template +constexpr auto reserve(Iterator& it, size_t) -> Iterator& { + return it; +} + +template +using reserve_iterator = + remove_reference_t(), 0))>; + +template +constexpr auto to_pointer(OutputIt, size_t) -> T* { + return nullptr; +} +template +FMT_CONSTEXPR20 auto to_pointer(basic_appender it, size_t n) -> T* { + buffer& buf = get_container(it); + buf.try_reserve(buf.size() + n); + auto size = buf.size(); + if (buf.capacity() < size + n) return nullptr; + buf.try_resize(size + n); + return buf.data() + size; +} + +template ::value&& + is_contiguous::value)> +inline auto base_iterator(OutputIt it, + typename OutputIt::container_type::value_type*) + -> OutputIt { + return it; +} + +template +constexpr auto base_iterator(Iterator, Iterator it) -> Iterator { + return it; +} + +// is spectacularly slow to compile in C++20 so use a simple fill_n +// instead (#1998). +template +FMT_CONSTEXPR auto fill_n(OutputIt out, Size count, const T& value) + -> OutputIt { + for (Size i = 0; i < count; ++i) *out++ = value; + return out; +} +template +FMT_CONSTEXPR20 auto fill_n(T* out, Size count, char value) -> T* { + if (is_constant_evaluated()) return fill_n(out, count, value); + std::memset(out, value, to_unsigned(count)); + return out + count; +} + +template +FMT_CONSTEXPR FMT_NOINLINE auto copy_noinline(InputIt begin, InputIt end, + OutputIt out) -> OutputIt { + return copy(begin, end, out); +} + +// A public domain branchless UTF-8 decoder by Christopher Wellons: +// https://github.com/skeeto/branchless-utf8 +/* Decode the next character, c, from s, reporting errors in e. + * + * Since this is a branchless decoder, four bytes will be read from the + * buffer regardless of the actual length of the next character. This + * means the buffer _must_ have at least three bytes of zero padding + * following the end of the data stream. + * + * Errors are reported in e, which will be non-zero if the parsed + * character was somehow invalid: invalid byte sequence, non-canonical + * encoding, or a surrogate half. + * + * The function returns a pointer to the next character. When an error + * occurs, this pointer will be a guess that depends on the particular + * error, but it will always advance at least one byte. + */ +FMT_CONSTEXPR inline auto utf8_decode(const char* s, uint32_t* c, int* e) + -> const char* { + constexpr const int masks[] = {0x00, 0x7f, 0x1f, 0x0f, 0x07}; + constexpr const uint32_t mins[] = {4194304, 0, 128, 2048, 65536}; + constexpr const int shiftc[] = {0, 18, 12, 6, 0}; + constexpr const int shifte[] = {0, 6, 4, 2, 0}; + + int len = "\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\1\0\0\0\0\0\0\0\0\2\2\2\2\3\3\4" + [static_cast(*s) >> 3]; + // Compute the pointer to the next character early so that the next + // iteration can start working on the next character. Neither Clang + // nor GCC figure out this reordering on their own. + const char* next = s + len + !len; + + using uchar = unsigned char; + + // Assume a four-byte character and load four bytes. Unused bits are + // shifted out. + *c = uint32_t(uchar(s[0]) & masks[len]) << 18; + *c |= uint32_t(uchar(s[1]) & 0x3f) << 12; + *c |= uint32_t(uchar(s[2]) & 0x3f) << 6; + *c |= uint32_t(uchar(s[3]) & 0x3f) << 0; + *c >>= shiftc[len]; + + // Accumulate the various error conditions. + *e = (*c < mins[len]) << 6; // non-canonical encoding + *e |= ((*c >> 11) == 0x1b) << 7; // surrogate half? + *e |= (*c > 0x10FFFF) << 8; // out of range? + *e |= (uchar(s[1]) & 0xc0) >> 2; + *e |= (uchar(s[2]) & 0xc0) >> 4; + *e |= uchar(s[3]) >> 6; + *e ^= 0x2a; // top two bits of each tail byte correct? + *e >>= shifte[len]; + + return next; +} + +constexpr FMT_INLINE_VARIABLE uint32_t invalid_code_point = ~uint32_t(); + +// Invokes f(cp, sv) for every code point cp in s with sv being the string view +// corresponding to the code point. cp is invalid_code_point on error. +template +FMT_CONSTEXPR void for_each_codepoint(string_view s, F f) { + auto decode = [f](const char* buf_ptr, const char* ptr) { + auto cp = uint32_t(); + auto error = 0; + auto end = utf8_decode(buf_ptr, &cp, &error); + bool result = f(error ? invalid_code_point : cp, + string_view(ptr, error ? 1 : to_unsigned(end - buf_ptr))); + return result ? (error ? buf_ptr + 1 : end) : nullptr; + }; + + auto p = s.data(); + const size_t block_size = 4; // utf8_decode always reads blocks of 4 chars. + if (s.size() >= block_size) { + for (auto end = p + s.size() - block_size + 1; p < end;) { + p = decode(p, p); + if (!p) return; + } + } + auto num_chars_left = to_unsigned(s.data() + s.size() - p); + if (num_chars_left == 0) return; + + // Suppress bogus -Wstringop-overflow. + if (FMT_GCC_VERSION) num_chars_left &= 3; + char buf[2 * block_size - 1] = {}; + copy(p, p + num_chars_left, buf); + const char* buf_ptr = buf; + do { + auto end = decode(buf_ptr, p); + if (!end) return; + p += end - buf_ptr; + buf_ptr = end; + } while (buf_ptr < buf + num_chars_left); +} + +template +inline auto compute_width(basic_string_view s) -> size_t { + return s.size(); +} + +// Computes approximate display width of a UTF-8 string. +FMT_CONSTEXPR inline auto compute_width(string_view s) -> size_t { + size_t num_code_points = 0; + // It is not a lambda for compatibility with C++14. + struct count_code_points { + size_t* count; + FMT_CONSTEXPR auto operator()(uint32_t cp, string_view) const -> bool { + *count += to_unsigned( + 1 + + (cp >= 0x1100 && + (cp <= 0x115f || // Hangul Jamo init. consonants + cp == 0x2329 || // LEFT-POINTING ANGLE BRACKET + cp == 0x232a || // RIGHT-POINTING ANGLE BRACKET + // CJK ... Yi except IDEOGRAPHIC HALF FILL SPACE: + (cp >= 0x2e80 && cp <= 0xa4cf && cp != 0x303f) || + (cp >= 0xac00 && cp <= 0xd7a3) || // Hangul Syllables + (cp >= 0xf900 && cp <= 0xfaff) || // CJK Compatibility Ideographs + (cp >= 0xfe10 && cp <= 0xfe19) || // Vertical Forms + (cp >= 0xfe30 && cp <= 0xfe6f) || // CJK Compatibility Forms + (cp >= 0xff00 && cp <= 0xff60) || // Fullwidth Forms + (cp >= 0xffe0 && cp <= 0xffe6) || // Fullwidth Forms + (cp >= 0x20000 && cp <= 0x2fffd) || // CJK + (cp >= 0x30000 && cp <= 0x3fffd) || + // Miscellaneous Symbols and Pictographs + Emoticons: + (cp >= 0x1f300 && cp <= 0x1f64f) || + // Supplemental Symbols and Pictographs: + (cp >= 0x1f900 && cp <= 0x1f9ff)))); + return true; + } + }; + // We could avoid branches by using utf8_decode directly. + for_each_codepoint(s, count_code_points{&num_code_points}); + return num_code_points; +} + +template +inline auto code_point_index(basic_string_view s, size_t n) -> size_t { + return min_of(n, s.size()); +} + +// Calculates the index of the nth code point in a UTF-8 string. +inline auto code_point_index(string_view s, size_t n) -> size_t { + size_t result = s.size(); + const char* begin = s.begin(); + for_each_codepoint(s, [begin, &n, &result](uint32_t, string_view sv) { + if (n != 0) { + --n; + return true; + } + result = to_unsigned(sv.begin() - begin); + return false; + }); + return result; +} + +template struct is_integral : std::is_integral {}; +template <> struct is_integral : std::true_type {}; +template <> struct is_integral : std::true_type {}; + +template +using is_signed = + std::integral_constant::is_signed || + std::is_same::value>; + +template +using is_integer = + bool_constant::value && !std::is_same::value && + !std::is_same::value && + !std::is_same::value>; + +#if defined(FMT_USE_FLOAT128) +// Use the provided definition. +#elif FMT_CLANG_VERSION >= 309 && FMT_HAS_INCLUDE() +# define FMT_USE_FLOAT128 1 +#elif FMT_GCC_VERSION && defined(_GLIBCXX_USE_FLOAT128) && \ + !defined(__STRICT_ANSI__) +# define FMT_USE_FLOAT128 1 +#else +# define FMT_USE_FLOAT128 0 +#endif +#if FMT_USE_FLOAT128 +using float128 = __float128; +#else +struct float128 {}; +#endif + +template using is_float128 = std::is_same; + +template struct is_floating_point : std::is_floating_point {}; +template <> struct is_floating_point : std::true_type {}; + +template ::value> +struct is_fast_float : bool_constant::is_iec559 && + sizeof(T) <= sizeof(double)> {}; +template struct is_fast_float : std::false_type {}; + +template +using is_double_double = bool_constant::digits == 106>; + +#ifndef FMT_USE_FULL_CACHE_DRAGONBOX +# define FMT_USE_FULL_CACHE_DRAGONBOX 0 +#endif + +// An allocator that uses malloc/free to allow removing dependency on the C++ +// standard libary runtime. +template struct allocator { + using value_type = T; + + T* allocate(size_t n) { + FMT_ASSERT(n <= max_value() / sizeof(T), ""); + T* p = static_cast(malloc(n * sizeof(T))); + if (!p) FMT_THROW(std::bad_alloc()); + return p; + } + + void deallocate(T* p, size_t) { free(p); } +}; + +} // namespace detail + +FMT_BEGIN_EXPORT + +// The number of characters to store in the basic_memory_buffer object itself +// to avoid dynamic memory allocation. +enum { inline_buffer_size = 500 }; + +/** + * A dynamically growing memory buffer for trivially copyable/constructible + * types with the first `SIZE` elements stored in the object itself. Most + * commonly used via the `memory_buffer` alias for `char`. + * + * **Example**: + * + * auto out = fmt::memory_buffer(); + * fmt::format_to(std::back_inserter(out), "The answer is {}.", 42); + * + * This will append "The answer is 42." to `out`. The buffer content can be + * converted to `std::string` with `to_string(out)`. + */ +template > +class basic_memory_buffer : public detail::buffer { + private: + T store_[SIZE]; + + // Don't inherit from Allocator to avoid generating type_info for it. + FMT_NO_UNIQUE_ADDRESS Allocator alloc_; + + // Deallocate memory allocated by the buffer. + FMT_CONSTEXPR20 void deallocate() { + T* data = this->data(); + if (data != store_) alloc_.deallocate(data, this->capacity()); + } + + static FMT_CONSTEXPR20 void grow(detail::buffer& buf, size_t size) { + detail::abort_fuzzing_if(size > 5000); + auto& self = static_cast(buf); + const size_t max_size = + std::allocator_traits::max_size(self.alloc_); + size_t old_capacity = buf.capacity(); + size_t new_capacity = old_capacity + old_capacity / 2; + if (size > new_capacity) + new_capacity = size; + else if (new_capacity > max_size) + new_capacity = max_of(size, max_size); + T* old_data = buf.data(); + T* new_data = self.alloc_.allocate(new_capacity); + // Suppress a bogus -Wstringop-overflow in gcc 13.1 (#3481). + detail::assume(buf.size() <= new_capacity); + // The following code doesn't throw, so the raw pointer above doesn't leak. + memcpy(new_data, old_data, buf.size() * sizeof(T)); + self.set(new_data, new_capacity); + // deallocate must not throw according to the standard, but even if it does, + // the buffer already uses the new storage and will deallocate it in + // destructor. + if (old_data != self.store_) self.alloc_.deallocate(old_data, old_capacity); + } + + public: + using value_type = T; + using const_reference = const T&; + + FMT_CONSTEXPR explicit basic_memory_buffer( + const Allocator& alloc = Allocator()) + : detail::buffer(grow), alloc_(alloc) { + this->set(store_, SIZE); + if (detail::is_constant_evaluated()) detail::fill_n(store_, SIZE, T()); + } + FMT_CONSTEXPR20 ~basic_memory_buffer() { deallocate(); } + + private: + // Move data from other to this buffer. + FMT_CONSTEXPR20 void move(basic_memory_buffer& other) { + alloc_ = std::move(other.alloc_); + T* data = other.data(); + size_t size = other.size(), capacity = other.capacity(); + if (data == other.store_) { + this->set(store_, capacity); + detail::copy(other.store_, other.store_ + size, store_); + } else { + this->set(data, capacity); + // Set pointer to the inline array so that delete is not called + // when deallocating. + other.set(other.store_, 0); + other.clear(); + } + this->resize(size); + } + + public: + /// Constructs a `basic_memory_buffer` object moving the content of the other + /// object to it. + FMT_CONSTEXPR20 basic_memory_buffer(basic_memory_buffer&& other) noexcept + : detail::buffer(grow) { + move(other); + } + + /// Moves the content of the other `basic_memory_buffer` object to this one. + auto operator=(basic_memory_buffer&& other) noexcept -> basic_memory_buffer& { + FMT_ASSERT(this != &other, ""); + deallocate(); + move(other); + return *this; + } + + // Returns a copy of the allocator associated with this buffer. + auto get_allocator() const -> Allocator { return alloc_; } + + /// Resizes the buffer to contain `count` elements. If T is a POD type new + /// elements may not be initialized. + FMT_CONSTEXPR void resize(size_t count) { this->try_resize(count); } + + /// Increases the buffer capacity to `new_capacity`. + void reserve(size_t new_capacity) { this->try_reserve(new_capacity); } + + using detail::buffer::append; + template + FMT_CONSTEXPR20 void append(const ContiguousRange& range) { + append(range.data(), range.data() + range.size()); + } +}; + +using memory_buffer = basic_memory_buffer; + +template +FMT_NODISCARD auto to_string(const basic_memory_buffer& buf) + -> std::string { + auto size = buf.size(); + detail::assume(size < std::string().max_size()); + return {buf.data(), size}; +} + +// A writer to a buffered stream. It doesn't own the underlying stream. +class writer { + private: + detail::buffer* buf_; + + // We cannot create a file buffer in advance because any write to a FILE may + // invalidate it. + FILE* file_; + + public: + inline writer(FILE* f) : buf_(nullptr), file_(f) {} + inline writer(detail::buffer& buf) : buf_(&buf) {} + + /// Formats `args` according to specifications in `fmt` and writes the + /// output to the file. + template void print(format_string fmt, T&&... args) { + if (buf_) + fmt::format_to(appender(*buf_), fmt, std::forward(args)...); + else + fmt::print(file_, fmt, std::forward(args)...); + } +}; + +class string_buffer { + private: + std::string str_; + detail::container_buffer buf_; + + public: + inline string_buffer() : buf_(str_) {} + + inline operator writer() { return buf_; } + inline std::string& str() { return str_; } +}; + +template +struct is_contiguous> : std::true_type { +}; + +// Suppress a misleading warning in older versions of clang. +FMT_PRAGMA_CLANG(diagnostic ignored "-Wweak-vtables") + +/// An error reported from a formatting function. +class FMT_SO_VISIBILITY("default") format_error : public std::runtime_error { + public: + using std::runtime_error::runtime_error; +}; + +class loc_value; + +FMT_END_EXPORT +namespace detail { +FMT_API auto write_console(int fd, string_view text) -> bool; +FMT_API void print(FILE*, string_view); +} // namespace detail + +namespace detail { +template struct fixed_string { + FMT_CONSTEXPR20 fixed_string(const Char (&s)[N]) { + detail::copy(static_cast(s), s + N, + data); + } + Char data[N] = {}; +}; + +// Converts a compile-time string to basic_string_view. +FMT_EXPORT template +constexpr auto compile_string_to_view(const Char (&s)[N]) + -> basic_string_view { + // Remove trailing NUL character if needed. Won't be present if this is used + // with a raw character array (i.e. not defined as a string). + return {s, N - (std::char_traits::to_int_type(s[N - 1]) == 0 ? 1 : 0)}; +} +FMT_EXPORT template +constexpr auto compile_string_to_view(basic_string_view s) + -> basic_string_view { + return s; +} + +// Returns true if value is negative, false otherwise. +// Same as `value < 0` but doesn't produce warnings if T is an unsigned type. +template ::value)> +constexpr auto is_negative(T value) -> bool { + return value < 0; +} +template ::value)> +constexpr auto is_negative(T) -> bool { + return false; +} + +// Smallest of uint32_t, uint64_t, uint128_t that is large enough to +// represent all values of an integral type T. +template +using uint32_or_64_or_128_t = + conditional_t() <= 32 && !FMT_REDUCE_INT_INSTANTIATIONS, + uint32_t, + conditional_t() <= 64, uint64_t, uint128_t>>; +template +using uint64_or_128_t = conditional_t() <= 64, uint64_t, uint128_t>; + +#define FMT_POWERS_OF_10(factor) \ + factor * 10, (factor) * 100, (factor) * 1000, (factor) * 10000, \ + (factor) * 100000, (factor) * 1000000, (factor) * 10000000, \ + (factor) * 100000000, (factor) * 1000000000 + +// Converts value in the range [0, 100) to a string. +// GCC generates slightly better code when value is pointer-size. +inline auto digits2(size_t value) -> const char* { + // Align data since unaligned access may be slower when crossing a + // hardware-specific boundary. + alignas(2) static const char data[] = + "0001020304050607080910111213141516171819" + "2021222324252627282930313233343536373839" + "4041424344454647484950515253545556575859" + "6061626364656667686970717273747576777879" + "8081828384858687888990919293949596979899"; + return &data[value * 2]; +} + +template constexpr auto getsign(sign s) -> Char { + return static_cast(((' ' << 24) | ('+' << 16) | ('-' << 8)) >> + (static_cast(s) * 8)); +} + +template FMT_CONSTEXPR auto count_digits_fallback(T n) -> int { + int count = 1; + for (;;) { + // Integer division is slow so do it for a group of four digits instead + // of for every digit. The idea comes from the talk by Alexandrescu + // "Three Optimization Tips for C++". See speed-test for a comparison. + if (n < 10) return count; + if (n < 100) return count + 1; + if (n < 1000) return count + 2; + if (n < 10000) return count + 3; + n /= 10000u; + count += 4; + } +} +#if FMT_USE_INT128 +FMT_CONSTEXPR inline auto count_digits(uint128_opt n) -> int { + return count_digits_fallback(n); +} +#endif + +#ifdef FMT_BUILTIN_CLZLL +// It is a separate function rather than a part of count_digits to workaround +// the lack of static constexpr in constexpr functions. +inline auto do_count_digits(uint64_t n) -> int { + // This has comparable performance to the version by Kendall Willets + // (https://github.com/fmtlib/format-benchmark/blob/master/digits10) + // but uses smaller tables. + // Maps bsr(n) to ceil(log10(pow(2, bsr(n) + 1) - 1)). + static constexpr uint8_t bsr2log10[] = { + 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, + 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, + 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15, 15, + 15, 16, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 19, 20}; + auto t = bsr2log10[FMT_BUILTIN_CLZLL(n | 1) ^ 63]; + static constexpr const uint64_t zero_or_powers_of_10[] = { + 0, 0, FMT_POWERS_OF_10(1U), FMT_POWERS_OF_10(1000000000ULL), + 10000000000000000000ULL}; + return t - (n < zero_or_powers_of_10[t]); +} +#endif + +// Returns the number of decimal digits in n. Leading zeros are not counted +// except for n == 0 in which case count_digits returns 1. +FMT_CONSTEXPR20 inline auto count_digits(uint64_t n) -> int { +#ifdef FMT_BUILTIN_CLZLL + if (!is_constant_evaluated() && !FMT_OPTIMIZE_SIZE) return do_count_digits(n); +#endif + return count_digits_fallback(n); +} + +// Counts the number of digits in n. BITS = log2(radix). +template +FMT_CONSTEXPR auto count_digits(UInt n) -> int { +#ifdef FMT_BUILTIN_CLZ + if (!is_constant_evaluated() && num_bits() == 32) + return (FMT_BUILTIN_CLZ(static_cast(n) | 1) ^ 31) / BITS + 1; +#endif + // Lambda avoids unreachable code warnings from NVHPC. + return [](UInt m) { + int num_digits = 0; + do { + ++num_digits; + } while ((m >>= BITS) != 0); + return num_digits; + }(n); +} + +#ifdef FMT_BUILTIN_CLZ +// It is a separate function rather than a part of count_digits to workaround +// the lack of static constexpr in constexpr functions. +FMT_INLINE auto do_count_digits(uint32_t n) -> int { +// An optimization by Kendall Willets from https://bit.ly/3uOIQrB. +// This increments the upper 32 bits (log10(T) - 1) when >= T is added. +# define FMT_INC(T) (((sizeof(#T) - 1ull) << 32) - T) + static constexpr uint64_t table[] = { + FMT_INC(0), FMT_INC(0), FMT_INC(0), // 8 + FMT_INC(10), FMT_INC(10), FMT_INC(10), // 64 + FMT_INC(100), FMT_INC(100), FMT_INC(100), // 512 + FMT_INC(1000), FMT_INC(1000), FMT_INC(1000), // 4096 + FMT_INC(10000), FMT_INC(10000), FMT_INC(10000), // 32k + FMT_INC(100000), FMT_INC(100000), FMT_INC(100000), // 256k + FMT_INC(1000000), FMT_INC(1000000), FMT_INC(1000000), // 2048k + FMT_INC(10000000), FMT_INC(10000000), FMT_INC(10000000), // 16M + FMT_INC(100000000), FMT_INC(100000000), FMT_INC(100000000), // 128M + FMT_INC(1000000000), FMT_INC(1000000000), FMT_INC(1000000000), // 1024M + FMT_INC(1000000000), FMT_INC(1000000000) // 4B + }; + auto inc = table[FMT_BUILTIN_CLZ(n | 1) ^ 31]; + return static_cast((n + inc) >> 32); +} +#endif + +// Optional version of count_digits for better performance on 32-bit platforms. +FMT_CONSTEXPR20 inline auto count_digits(uint32_t n) -> int { +#ifdef FMT_BUILTIN_CLZ + if (!is_constant_evaluated() && !FMT_OPTIMIZE_SIZE) return do_count_digits(n); +#endif + return count_digits_fallback(n); +} + +template constexpr auto digits10() noexcept -> int { + return std::numeric_limits::digits10; +} +template <> constexpr auto digits10() noexcept -> int { return 38; } +template <> constexpr auto digits10() noexcept -> int { return 38; } + +template struct thousands_sep_result { + std::string grouping; + Char thousands_sep; +}; + +template +FMT_API auto thousands_sep_impl(locale_ref loc) -> thousands_sep_result; +template +inline auto thousands_sep(locale_ref loc) -> thousands_sep_result { + auto result = thousands_sep_impl(loc); + return {result.grouping, Char(result.thousands_sep)}; +} +template <> +inline auto thousands_sep(locale_ref loc) -> thousands_sep_result { + return thousands_sep_impl(loc); +} + +template +FMT_API auto decimal_point_impl(locale_ref loc) -> Char; +template inline auto decimal_point(locale_ref loc) -> Char { + return Char(decimal_point_impl(loc)); +} +template <> inline auto decimal_point(locale_ref loc) -> wchar_t { + return decimal_point_impl(loc); +} + +#ifndef FMT_HEADER_ONLY +FMT_BEGIN_EXPORT +extern template FMT_API auto thousands_sep_impl(locale_ref) + -> thousands_sep_result; +extern template FMT_API auto thousands_sep_impl(locale_ref) + -> thousands_sep_result; +extern template FMT_API auto decimal_point_impl(locale_ref) -> char; +extern template FMT_API auto decimal_point_impl(locale_ref) -> wchar_t; +FMT_END_EXPORT +#endif // FMT_HEADER_ONLY + +// Compares two characters for equality. +template auto equal2(const Char* lhs, const char* rhs) -> bool { + return lhs[0] == Char(rhs[0]) && lhs[1] == Char(rhs[1]); +} +inline auto equal2(const char* lhs, const char* rhs) -> bool { + return memcmp(lhs, rhs, 2) == 0; +} + +// Writes a two-digit value to out. +template +FMT_CONSTEXPR20 FMT_INLINE void write2digits(Char* out, size_t value) { + if (!is_constant_evaluated() && std::is_same::value && + !FMT_OPTIMIZE_SIZE) { + memcpy(out, digits2(value), 2); + return; + } + *out++ = static_cast('0' + value / 10); + *out = static_cast('0' + value % 10); +} + +// Formats a decimal unsigned integer value writing to out pointing to a buffer +// of specified size. The caller must ensure that the buffer is large enough. +template +FMT_CONSTEXPR20 auto do_format_decimal(Char* out, UInt value, int size) + -> Char* { + FMT_ASSERT(size >= count_digits(value), "invalid digit count"); + unsigned n = to_unsigned(size); + while (value >= 100) { + // Integer division is slow so do it for a group of two digits instead + // of for every digit. The idea comes from the talk by Alexandrescu + // "Three Optimization Tips for C++". See speed-test for a comparison. + n -= 2; + write2digits(out + n, static_cast(value % 100)); + value /= 100; + } + if (value >= 10) { + n -= 2; + write2digits(out + n, static_cast(value)); + } else { + out[--n] = static_cast('0' + value); + } + return out + n; +} + +template +FMT_CONSTEXPR FMT_INLINE auto format_decimal(Char* out, UInt value, + int num_digits) -> Char* { + do_format_decimal(out, value, num_digits); + return out + num_digits; +} + +template >::value)> +FMT_CONSTEXPR auto format_decimal(OutputIt out, UInt value, int num_digits) + -> OutputIt { + if (auto ptr = to_pointer(out, to_unsigned(num_digits))) { + do_format_decimal(ptr, value, num_digits); + return out; + } + // Buffer is large enough to hold all digits (digits10 + 1). + char buffer[digits10() + 1]; + if (is_constant_evaluated()) fill_n(buffer, sizeof(buffer), '\0'); + do_format_decimal(buffer, value, num_digits); + return copy_noinline(buffer, buffer + num_digits, out); +} + +template +FMT_CONSTEXPR auto do_format_base2e(int base_bits, Char* out, UInt value, + int size, bool upper = false) -> Char* { + out += size; + do { + const char* digits = upper ? "0123456789ABCDEF" : "0123456789abcdef"; + unsigned digit = static_cast(value & ((1 << base_bits) - 1)); + *--out = static_cast(base_bits < 4 ? static_cast('0' + digit) + : digits[digit]); + } while ((value >>= base_bits) != 0); + return out; +} + +// Formats an unsigned integer in the power of two base (binary, octal, hex). +template +FMT_CONSTEXPR auto format_base2e(int base_bits, Char* out, UInt value, + int num_digits, bool upper = false) -> Char* { + do_format_base2e(base_bits, out, value, num_digits, upper); + return out + num_digits; +} + +template ::value)> +FMT_CONSTEXPR inline auto format_base2e(int base_bits, OutputIt out, UInt value, + int num_digits, bool upper = false) + -> OutputIt { + if (auto ptr = to_pointer(out, to_unsigned(num_digits))) { + format_base2e(base_bits, ptr, value, num_digits, upper); + return out; + } + // Make buffer large enough for any base. + char buffer[num_bits()]; + if (is_constant_evaluated()) fill_n(buffer, sizeof(buffer), '\0'); + format_base2e(base_bits, buffer, value, num_digits, upper); + return detail::copy_noinline(buffer, buffer + num_digits, out); +} + +// A converter from UTF-8 to UTF-16. +class utf8_to_utf16 { + private: + basic_memory_buffer buffer_; + + public: + FMT_API explicit utf8_to_utf16(string_view s); + inline operator basic_string_view() const { + return {&buffer_[0], size()}; + } + inline auto size() const -> size_t { return buffer_.size() - 1; } + inline auto c_str() const -> const wchar_t* { return &buffer_[0]; } + inline auto str() const -> std::wstring { return {&buffer_[0], size()}; } +}; + +enum class to_utf8_error_policy { abort, replace }; + +// A converter from UTF-16/UTF-32 (host endian) to UTF-8. +template class to_utf8 { + private: + Buffer buffer_; + + public: + to_utf8() {} + explicit to_utf8(basic_string_view s, + to_utf8_error_policy policy = to_utf8_error_policy::abort) { + static_assert(sizeof(WChar) == 2 || sizeof(WChar) == 4, + "Expect utf16 or utf32"); + if (!convert(s, policy)) + FMT_THROW(std::runtime_error(sizeof(WChar) == 2 ? "invalid utf16" + : "invalid utf32")); + } + operator string_view() const { return string_view(&buffer_[0], size()); } + auto size() const -> size_t { return buffer_.size() - 1; } + auto c_str() const -> const char* { return &buffer_[0]; } + auto str() const -> std::string { return std::string(&buffer_[0], size()); } + + // Performs conversion returning a bool instead of throwing exception on + // conversion error. This method may still throw in case of memory allocation + // error. + auto convert(basic_string_view s, + to_utf8_error_policy policy = to_utf8_error_policy::abort) + -> bool { + if (!convert(buffer_, s, policy)) return false; + buffer_.push_back(0); + return true; + } + static auto convert(Buffer& buf, basic_string_view s, + to_utf8_error_policy policy = to_utf8_error_policy::abort) + -> bool { + for (auto p = s.begin(); p != s.end(); ++p) { + uint32_t c = static_cast(*p); + if (sizeof(WChar) == 2 && c >= 0xd800 && c <= 0xdfff) { + // Handle a surrogate pair. + ++p; + if (p == s.end() || (c & 0xfc00) != 0xd800 || (*p & 0xfc00) != 0xdc00) { + if (policy == to_utf8_error_policy::abort) return false; + buf.append(string_view("\xEF\xBF\xBD")); + --p; + continue; + } else { + c = (c << 10) + static_cast(*p) - 0x35fdc00; + } + } + if (c < 0x80) { + buf.push_back(static_cast(c)); + } else if (c < 0x800) { + buf.push_back(static_cast(0xc0 | (c >> 6))); + buf.push_back(static_cast(0x80 | (c & 0x3f))); + } else if ((c >= 0x800 && c <= 0xd7ff) || (c >= 0xe000 && c <= 0xffff)) { + buf.push_back(static_cast(0xe0 | (c >> 12))); + buf.push_back(static_cast(0x80 | ((c & 0xfff) >> 6))); + buf.push_back(static_cast(0x80 | (c & 0x3f))); + } else if (c >= 0x10000 && c <= 0x10ffff) { + buf.push_back(static_cast(0xf0 | (c >> 18))); + buf.push_back(static_cast(0x80 | ((c & 0x3ffff) >> 12))); + buf.push_back(static_cast(0x80 | ((c & 0xfff) >> 6))); + buf.push_back(static_cast(0x80 | (c & 0x3f))); + } else { + return false; + } + } + return true; + } +}; + +// Computes 128-bit result of multiplication of two 64-bit unsigned integers. +inline auto umul128(uint64_t x, uint64_t y) noexcept -> uint128_fallback { +#if FMT_USE_INT128 + auto p = static_cast(x) * static_cast(y); + return {static_cast(p >> 64), static_cast(p)}; +#elif defined(_MSC_VER) && defined(_M_X64) + auto hi = uint64_t(); + auto lo = _umul128(x, y, &hi); + return {hi, lo}; +#else + const uint64_t mask = static_cast(max_value()); + + uint64_t a = x >> 32; + uint64_t b = x & mask; + uint64_t c = y >> 32; + uint64_t d = y & mask; + + uint64_t ac = a * c; + uint64_t bc = b * c; + uint64_t ad = a * d; + uint64_t bd = b * d; + + uint64_t intermediate = (bd >> 32) + (ad & mask) + (bc & mask); + + return {ac + (intermediate >> 32) + (ad >> 32) + (bc >> 32), + (intermediate << 32) + (bd & mask)}; +#endif +} + +namespace dragonbox { +// Computes floor(log10(pow(2, e))) for e in [-2620, 2620] using the method from +// https://fmt.dev/papers/Dragonbox.pdf#page=28, section 6.1. +inline auto floor_log10_pow2(int e) noexcept -> int { + FMT_ASSERT(e <= 2620 && e >= -2620, "too large exponent"); + static_assert((-1 >> 1) == -1, "right shift is not arithmetic"); + return (e * 315653) >> 20; +} + +inline auto floor_log2_pow10(int e) noexcept -> int { + FMT_ASSERT(e <= 1233 && e >= -1233, "too large exponent"); + return (e * 1741647) >> 19; +} + +// Computes upper 64 bits of multiplication of two 64-bit unsigned integers. +inline auto umul128_upper64(uint64_t x, uint64_t y) noexcept -> uint64_t { +#if FMT_USE_INT128 + auto p = static_cast(x) * static_cast(y); + return static_cast(p >> 64); +#elif defined(_MSC_VER) && defined(_M_X64) + return __umulh(x, y); +#else + return umul128(x, y).high(); +#endif +} + +// Computes upper 128 bits of multiplication of a 64-bit unsigned integer and a +// 128-bit unsigned integer. +inline auto umul192_upper128(uint64_t x, uint128_fallback y) noexcept + -> uint128_fallback { + uint128_fallback r = umul128(x, y.high()); + r += umul128_upper64(x, y.low()); + return r; +} + +FMT_API auto get_cached_power(int k) noexcept -> uint128_fallback; + +// Type-specific information that Dragonbox uses. +template struct float_info; + +template <> struct float_info { + using carrier_uint = uint32_t; + static const int exponent_bits = 8; + static const int kappa = 1; + static const int big_divisor = 100; + static const int small_divisor = 10; + static const int min_k = -31; + static const int max_k = 46; + static const int shorter_interval_tie_lower_threshold = -35; + static const int shorter_interval_tie_upper_threshold = -35; +}; + +template <> struct float_info { + using carrier_uint = uint64_t; + static const int exponent_bits = 11; + static const int kappa = 2; + static const int big_divisor = 1000; + static const int small_divisor = 100; + static const int min_k = -292; + static const int max_k = 341; + static const int shorter_interval_tie_lower_threshold = -77; + static const int shorter_interval_tie_upper_threshold = -77; +}; + +// An 80- or 128-bit floating point number. +template +struct float_info::digits == 64 || + std::numeric_limits::digits == 113 || + is_float128::value>> { + using carrier_uint = detail::uint128_t; + static const int exponent_bits = 15; +}; + +// A double-double floating point number. +template +struct float_info::value>> { + using carrier_uint = detail::uint128_t; +}; + +template struct decimal_fp { + using significand_type = typename float_info::carrier_uint; + significand_type significand; + int exponent; +}; + +template FMT_API auto to_decimal(T x) noexcept -> decimal_fp; +} // namespace dragonbox + +// Returns true iff Float has the implicit bit which is not stored. +template constexpr auto has_implicit_bit() -> bool { + // An 80-bit FP number has a 64-bit significand an no implicit bit. + return std::numeric_limits::digits != 64; +} + +// Returns the number of significand bits stored in Float. The implicit bit is +// not counted since it is not stored. +template constexpr auto num_significand_bits() -> int { + // std::numeric_limits may not support __float128. + return is_float128() ? 112 + : (std::numeric_limits::digits - + (has_implicit_bit() ? 1 : 0)); +} + +template +constexpr auto exponent_mask() -> + typename dragonbox::float_info::carrier_uint { + using float_uint = typename dragonbox::float_info::carrier_uint; + return ((float_uint(1) << dragonbox::float_info::exponent_bits) - 1) + << num_significand_bits(); +} +template constexpr auto exponent_bias() -> int { + // std::numeric_limits may not support __float128. + return is_float128() ? 16383 + : std::numeric_limits::max_exponent - 1; +} + +// Writes the exponent exp in the form "[+-]d{2,3}" to buffer. +template +FMT_CONSTEXPR auto write_exponent(int exp, OutputIt out) -> OutputIt { + FMT_ASSERT(-10000 < exp && exp < 10000, "exponent out of range"); + if (exp < 0) { + *out++ = static_cast('-'); + exp = -exp; + } else { + *out++ = static_cast('+'); + } + auto uexp = static_cast(exp); + if (is_constant_evaluated()) { + if (uexp < 10) *out++ = '0'; + return format_decimal(out, uexp, count_digits(uexp)); + } + if (uexp >= 100u) { + const char* top = digits2(uexp / 100); + if (uexp >= 1000u) *out++ = static_cast(top[0]); + *out++ = static_cast(top[1]); + uexp %= 100; + } + const char* d = digits2(uexp); + *out++ = static_cast(d[0]); + *out++ = static_cast(d[1]); + return out; +} + +// A floating-point number f * pow(2, e) where F is an unsigned type. +template struct basic_fp { + F f; + int e; + + static constexpr const int num_significand_bits = + static_cast(sizeof(F) * num_bits()); + + constexpr basic_fp() : f(0), e(0) {} + constexpr basic_fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {} + + // Constructs fp from an IEEE754 floating-point number. + template FMT_CONSTEXPR basic_fp(Float n) { assign(n); } + + // Assigns n to this and return true iff predecessor is closer than successor. + template ::value)> + FMT_CONSTEXPR auto assign(Float n) -> bool { + static_assert(std::numeric_limits::digits <= 113, "unsupported FP"); + // Assume Float is in the format [sign][exponent][significand]. + using carrier_uint = typename dragonbox::float_info::carrier_uint; + const auto num_float_significand_bits = + detail::num_significand_bits(); + const auto implicit_bit = carrier_uint(1) << num_float_significand_bits; + const auto significand_mask = implicit_bit - 1; + auto u = bit_cast(n); + f = static_cast(u & significand_mask); + auto biased_e = static_cast((u & exponent_mask()) >> + num_float_significand_bits); + // The predecessor is closer if n is a normalized power of 2 (f == 0) + // other than the smallest normalized number (biased_e > 1). + auto is_predecessor_closer = f == 0 && biased_e > 1; + if (biased_e == 0) + biased_e = 1; // Subnormals use biased exponent 1 (min exponent). + else if (has_implicit_bit()) + f += static_cast(implicit_bit); + e = biased_e - exponent_bias() - num_float_significand_bits; + if (!has_implicit_bit()) ++e; + return is_predecessor_closer; + } + + template ::value)> + FMT_CONSTEXPR auto assign(Float n) -> bool { + static_assert(std::numeric_limits::is_iec559, "unsupported FP"); + return assign(static_cast(n)); + } +}; + +using fp = basic_fp; + +// Normalizes the value converted from double and multiplied by (1 << SHIFT). +template +FMT_CONSTEXPR auto normalize(basic_fp value) -> basic_fp { + // Handle subnormals. + const auto implicit_bit = F(1) << num_significand_bits(); + const auto shifted_implicit_bit = implicit_bit << SHIFT; + while ((value.f & shifted_implicit_bit) == 0) { + value.f <<= 1; + --value.e; + } + // Subtract 1 to account for hidden bit. + const auto offset = basic_fp::num_significand_bits - + num_significand_bits() - SHIFT - 1; + value.f <<= offset; + value.e -= offset; + return value; +} + +// Computes lhs * rhs / pow(2, 64) rounded to nearest with half-up tie breaking. +FMT_CONSTEXPR inline auto multiply(uint64_t lhs, uint64_t rhs) -> uint64_t { +#if FMT_USE_INT128 + auto product = static_cast<__uint128_t>(lhs) * rhs; + auto f = static_cast(product >> 64); + return (static_cast(product) & (1ULL << 63)) != 0 ? f + 1 : f; +#else + // Multiply 32-bit parts of significands. + uint64_t mask = (1ULL << 32) - 1; + uint64_t a = lhs >> 32, b = lhs & mask; + uint64_t c = rhs >> 32, d = rhs & mask; + uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d; + // Compute mid 64-bit of result and round. + uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31); + return ac + (ad >> 32) + (bc >> 32) + (mid >> 32); +#endif +} + +FMT_CONSTEXPR inline auto operator*(fp x, fp y) -> fp { + return {multiply(x.f, y.f), x.e + y.e + 64}; +} + +template () == num_bits()> +using convert_float_result = + conditional_t::value || doublish, double, T>; + +template +constexpr auto convert_float(T value) -> convert_float_result { + return static_cast>(value); +} + +template +FMT_CONSTEXPR FMT_NOINLINE auto fill(OutputIt it, size_t n, + const basic_specs& specs) -> OutputIt { + auto fill_size = specs.fill_size(); + if (fill_size == 1) return detail::fill_n(it, n, specs.fill_unit()); + if (const Char* data = specs.fill()) { + for (size_t i = 0; i < n; ++i) it = copy(data, data + fill_size, it); + } + return it; +} + +// Writes the output of f, padded according to format specifications in specs. +// size: output size in code units. +// width: output display width in (terminal) column positions. +template +FMT_CONSTEXPR auto write_padded(OutputIt out, const format_specs& specs, + size_t size, size_t width, F&& f) -> OutputIt { + static_assert(default_align == align::left || default_align == align::right, + ""); + unsigned spec_width = to_unsigned(specs.width); + size_t padding = spec_width > width ? spec_width - width : 0; + // Shifts are encoded as string literals because static constexpr is not + // supported in constexpr functions. + auto* shifts = + default_align == align::left ? "\x1f\x1f\x00\x01" : "\x00\x1f\x00\x01"; + size_t left_padding = padding >> shifts[static_cast(specs.align())]; + size_t right_padding = padding - left_padding; + auto it = reserve(out, size + padding * specs.fill_size()); + if (left_padding != 0) it = fill(it, left_padding, specs); + it = f(it); + if (right_padding != 0) it = fill(it, right_padding, specs); + return base_iterator(out, it); +} + +template +constexpr auto write_padded(OutputIt out, const format_specs& specs, + size_t size, F&& f) -> OutputIt { + return write_padded(out, specs, size, size, f); +} + +template +FMT_CONSTEXPR auto write_bytes(OutputIt out, string_view bytes, + const format_specs& specs = {}) -> OutputIt { + return write_padded( + out, specs, bytes.size(), [bytes](reserve_iterator it) { + const char* data = bytes.data(); + return copy(data, data + bytes.size(), it); + }); +} + +template +auto write_ptr(OutputIt out, UIntPtr value, const format_specs* specs) + -> OutputIt { + int num_digits = count_digits<4>(value); + auto size = to_unsigned(num_digits) + size_t(2); + auto write = [=](reserve_iterator it) { + *it++ = static_cast('0'); + *it++ = static_cast('x'); + return format_base2e(4, it, value, num_digits); + }; + return specs ? write_padded(out, *specs, size, write) + : base_iterator(out, write(reserve(out, size))); +} + +// Returns true iff the code point cp is printable. +FMT_API auto is_printable(uint32_t cp) -> bool; + +inline auto needs_escape(uint32_t cp) -> bool { + if (cp < 0x20 || cp == 0x7f || cp == '"' || cp == '\\') return true; + if (const_check(FMT_OPTIMIZE_SIZE > 1)) return false; + return !is_printable(cp); +} + +template struct find_escape_result { + const Char* begin; + const Char* end; + uint32_t cp; +}; + +template +auto find_escape(const Char* begin, const Char* end) + -> find_escape_result { + for (; begin != end; ++begin) { + uint32_t cp = static_cast>(*begin); + if (const_check(sizeof(Char) == 1) && cp >= 0x80) continue; + if (needs_escape(cp)) return {begin, begin + 1, cp}; + } + return {begin, nullptr, 0}; +} + +inline auto find_escape(const char* begin, const char* end) + -> find_escape_result { + if (const_check(!use_utf8)) return find_escape(begin, end); + auto result = find_escape_result{end, nullptr, 0}; + for_each_codepoint(string_view(begin, to_unsigned(end - begin)), + [&](uint32_t cp, string_view sv) { + if (needs_escape(cp)) { + result = {sv.begin(), sv.end(), cp}; + return false; + } + return true; + }); + return result; +} + +template +auto write_codepoint(OutputIt out, char prefix, uint32_t cp) -> OutputIt { + *out++ = static_cast('\\'); + *out++ = static_cast(prefix); + Char buf[width]; + fill_n(buf, width, static_cast('0')); + format_base2e(4, buf, cp, width); + return copy(buf, buf + width, out); +} + +template +auto write_escaped_cp(OutputIt out, const find_escape_result& escape) + -> OutputIt { + auto c = static_cast(escape.cp); + switch (escape.cp) { + case '\n': + *out++ = static_cast('\\'); + c = static_cast('n'); + break; + case '\r': + *out++ = static_cast('\\'); + c = static_cast('r'); + break; + case '\t': + *out++ = static_cast('\\'); + c = static_cast('t'); + break; + case '"': FMT_FALLTHROUGH; + case '\'': FMT_FALLTHROUGH; + case '\\': *out++ = static_cast('\\'); break; + default: + if (escape.cp < 0x100) return write_codepoint<2, Char>(out, 'x', escape.cp); + if (escape.cp < 0x10000) + return write_codepoint<4, Char>(out, 'u', escape.cp); + if (escape.cp < 0x110000) + return write_codepoint<8, Char>(out, 'U', escape.cp); + for (Char escape_char : basic_string_view( + escape.begin, to_unsigned(escape.end - escape.begin))) { + out = write_codepoint<2, Char>(out, 'x', + static_cast(escape_char) & 0xFF); + } + return out; + } + *out++ = c; + return out; +} + +template +auto write_escaped_string(OutputIt out, basic_string_view str) + -> OutputIt { + *out++ = static_cast('"'); + auto begin = str.begin(), end = str.end(); + do { + auto escape = find_escape(begin, end); + out = copy(begin, escape.begin, out); + begin = escape.end; + if (!begin) break; + out = write_escaped_cp(out, escape); + } while (begin != end); + *out++ = static_cast('"'); + return out; +} + +template +auto write_escaped_char(OutputIt out, Char v) -> OutputIt { + Char v_array[1] = {v}; + *out++ = static_cast('\''); + if ((needs_escape(static_cast(v)) && v != static_cast('"')) || + v == static_cast('\'')) { + out = write_escaped_cp(out, + find_escape_result{v_array, v_array + 1, + static_cast(v)}); + } else { + *out++ = v; + } + *out++ = static_cast('\''); + return out; +} + +template +FMT_CONSTEXPR auto write_char(OutputIt out, Char value, + const format_specs& specs) -> OutputIt { + bool is_debug = specs.type() == presentation_type::debug; + return write_padded(out, specs, 1, [=](reserve_iterator it) { + if (is_debug) return write_escaped_char(it, value); + *it++ = value; + return it; + }); +} +template +FMT_CONSTEXPR auto write(OutputIt out, Char value, const format_specs& specs, + locale_ref loc = {}) -> OutputIt { + // char is formatted as unsigned char for consistency across platforms. + using unsigned_type = + conditional_t::value, unsigned char, unsigned>; + return check_char_specs(specs) + ? write_char(out, value, specs) + : write(out, static_cast(value), specs, loc); +} + +template class digit_grouping { + private: + std::string grouping_; + std::basic_string thousands_sep_; + + struct next_state { + std::string::const_iterator group; + int pos; + }; + auto initial_state() const -> next_state { return {grouping_.begin(), 0}; } + + // Returns the next digit group separator position. + auto next(next_state& state) const -> int { + if (thousands_sep_.empty()) return max_value(); + if (state.group == grouping_.end()) return state.pos += grouping_.back(); + if (*state.group <= 0 || *state.group == max_value()) + return max_value(); + state.pos += *state.group++; + return state.pos; + } + + public: + template ::value)> + explicit digit_grouping(Locale loc, bool localized = true) { + if (!localized) return; + auto sep = thousands_sep(loc); + grouping_ = sep.grouping; + if (sep.thousands_sep) thousands_sep_.assign(1, sep.thousands_sep); + } + digit_grouping(std::string grouping, std::basic_string sep) + : grouping_(std::move(grouping)), thousands_sep_(std::move(sep)) {} + + auto has_separator() const -> bool { return !thousands_sep_.empty(); } + + auto count_separators(int num_digits) const -> int { + int count = 0; + auto state = initial_state(); + while (num_digits > next(state)) ++count; + return count; + } + + // Applies grouping to digits and write the output to out. + template + auto apply(Out out, basic_string_view digits) const -> Out { + auto num_digits = static_cast(digits.size()); + auto separators = basic_memory_buffer(); + separators.push_back(0); + auto state = initial_state(); + while (int i = next(state)) { + if (i >= num_digits) break; + separators.push_back(i); + } + for (int i = 0, sep_index = static_cast(separators.size() - 1); + i < num_digits; ++i) { + if (num_digits - i == separators[sep_index]) { + out = copy(thousands_sep_.data(), + thousands_sep_.data() + thousands_sep_.size(), out); + --sep_index; + } + *out++ = static_cast(digits[to_unsigned(i)]); + } + return out; + } +}; + +FMT_CONSTEXPR inline void prefix_append(unsigned& prefix, unsigned value) { + prefix |= prefix != 0 ? value << 8 : value; + prefix += (1u + (value > 0xff ? 1 : 0)) << 24; +} + +// Writes a decimal integer with digit grouping. +template +auto write_int(OutputIt out, UInt value, unsigned prefix, + const format_specs& specs, const digit_grouping& grouping) + -> OutputIt { + static_assert(std::is_same, UInt>::value, ""); + int num_digits = 0; + auto buffer = memory_buffer(); + switch (specs.type()) { + default: FMT_ASSERT(false, ""); FMT_FALLTHROUGH; + case presentation_type::none: + case presentation_type::dec: + num_digits = count_digits(value); + format_decimal(appender(buffer), value, num_digits); + break; + case presentation_type::hex: + if (specs.alt()) + prefix_append(prefix, unsigned(specs.upper() ? 'X' : 'x') << 8 | '0'); + num_digits = count_digits<4>(value); + format_base2e(4, appender(buffer), value, num_digits, specs.upper()); + break; + case presentation_type::oct: + num_digits = count_digits<3>(value); + // Octal prefix '0' is counted as a digit, so only add it if precision + // is not greater than the number of digits. + if (specs.alt() && specs.precision <= num_digits && value != 0) + prefix_append(prefix, '0'); + format_base2e(3, appender(buffer), value, num_digits); + break; + case presentation_type::bin: + if (specs.alt()) + prefix_append(prefix, unsigned(specs.upper() ? 'B' : 'b') << 8 | '0'); + num_digits = count_digits<1>(value); + format_base2e(1, appender(buffer), value, num_digits); + break; + case presentation_type::chr: + return write_char(out, static_cast(value), specs); + } + + unsigned size = (prefix != 0 ? prefix >> 24 : 0) + to_unsigned(num_digits) + + to_unsigned(grouping.count_separators(num_digits)); + return write_padded( + out, specs, size, size, [&](reserve_iterator it) { + for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8) + *it++ = static_cast(p & 0xff); + return grouping.apply(it, string_view(buffer.data(), buffer.size())); + }); +} + +#if FMT_USE_LOCALE +// Writes a localized value. +FMT_API auto write_loc(appender out, loc_value value, const format_specs& specs, + locale_ref loc) -> bool; +#endif +template +inline auto write_loc(OutputIt, const loc_value&, const format_specs&, + locale_ref) -> bool { + return false; +} + +template struct write_int_arg { + UInt abs_value; + unsigned prefix; +}; + +template +FMT_CONSTEXPR auto make_write_int_arg(T value, sign s) + -> write_int_arg> { + auto prefix = 0u; + auto abs_value = static_cast>(value); + if (is_negative(value)) { + prefix = 0x01000000 | '-'; + abs_value = 0 - abs_value; + } else { + constexpr const unsigned prefixes[4] = {0, 0, 0x1000000u | '+', + 0x1000000u | ' '}; + prefix = prefixes[static_cast(s)]; + } + return {abs_value, prefix}; +} + +template struct loc_writer { + basic_appender out; + const format_specs& specs; + std::basic_string sep; + std::string grouping; + std::basic_string decimal_point; + + template ::value)> + auto operator()(T value) -> bool { + auto arg = make_write_int_arg(value, specs.sign()); + write_int(out, static_cast>(arg.abs_value), arg.prefix, + specs, digit_grouping(grouping, sep)); + return true; + } + + template ::value)> + auto operator()(T) -> bool { + return false; + } +}; + +// Size and padding computation separate from write_int to avoid template bloat. +struct size_padding { + unsigned size; + unsigned padding; + + FMT_CONSTEXPR size_padding(int num_digits, unsigned prefix, + const format_specs& specs) + : size((prefix >> 24) + to_unsigned(num_digits)), padding(0) { + if (specs.align() == align::numeric) { + auto width = to_unsigned(specs.width); + if (width > size) { + padding = width - size; + size = width; + } + } else if (specs.precision > num_digits) { + size = (prefix >> 24) + to_unsigned(specs.precision); + padding = to_unsigned(specs.precision - num_digits); + } + } +}; + +template +FMT_CONSTEXPR FMT_INLINE auto write_int(OutputIt out, write_int_arg arg, + const format_specs& specs) -> OutputIt { + static_assert(std::is_same>::value, ""); + + constexpr int buffer_size = num_bits(); + char buffer[buffer_size]; + if (is_constant_evaluated()) fill_n(buffer, buffer_size, '\0'); + const char* begin = nullptr; + const char* end = buffer + buffer_size; + + auto abs_value = arg.abs_value; + auto prefix = arg.prefix; + switch (specs.type()) { + default: FMT_ASSERT(false, ""); FMT_FALLTHROUGH; + case presentation_type::none: + case presentation_type::dec: + begin = do_format_decimal(buffer, abs_value, buffer_size); + break; + case presentation_type::hex: + begin = do_format_base2e(4, buffer, abs_value, buffer_size, specs.upper()); + if (specs.alt()) + prefix_append(prefix, unsigned(specs.upper() ? 'X' : 'x') << 8 | '0'); + break; + case presentation_type::oct: { + begin = do_format_base2e(3, buffer, abs_value, buffer_size); + // Octal prefix '0' is counted as a digit, so only add it if precision + // is not greater than the number of digits. + auto num_digits = end - begin; + if (specs.alt() && specs.precision <= num_digits && abs_value != 0) + prefix_append(prefix, '0'); + break; + } + case presentation_type::bin: + begin = do_format_base2e(1, buffer, abs_value, buffer_size); + if (specs.alt()) + prefix_append(prefix, unsigned(specs.upper() ? 'B' : 'b') << 8 | '0'); + break; + case presentation_type::chr: + return write_char(out, static_cast(abs_value), specs); + } + + // Write an integer in the format + // + // prefix contains chars in three lower bytes and the size in the fourth byte. + int num_digits = static_cast(end - begin); + // Slightly faster check for specs.width == 0 && specs.precision == -1. + if ((specs.width | (specs.precision + 1)) == 0) { + auto it = reserve(out, to_unsigned(num_digits) + (prefix >> 24)); + for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8) + *it++ = static_cast(p & 0xff); + return base_iterator(out, copy(begin, end, it)); + } + auto sp = size_padding(num_digits, prefix, specs); + unsigned padding = sp.padding; + return write_padded( + out, specs, sp.size, [=](reserve_iterator it) { + for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8) + *it++ = static_cast(p & 0xff); + it = detail::fill_n(it, padding, static_cast('0')); + return copy(begin, end, it); + }); +} + +template +FMT_CONSTEXPR FMT_NOINLINE auto write_int_noinline(OutputIt out, + write_int_arg arg, + const format_specs& specs) + -> OutputIt { + return write_int(out, arg, specs); +} + +template ::value && + !std::is_same::value && + !std::is_same::value)> +FMT_CONSTEXPR FMT_INLINE auto write(basic_appender out, T value, + const format_specs& specs, locale_ref loc) + -> basic_appender { + if (specs.localized() && write_loc(out, value, specs, loc)) return out; + return write_int_noinline(out, make_write_int_arg(value, specs.sign()), + specs); +} + +// An inlined version of write used in format string compilation. +template ::value && + !std::is_same::value && + !std::is_same::value && + !std::is_same>::value)> +FMT_CONSTEXPR FMT_INLINE auto write(OutputIt out, T value, + const format_specs& specs, locale_ref loc) + -> OutputIt { + if (specs.localized() && write_loc(out, value, specs, loc)) return out; + return write_int(out, make_write_int_arg(value, specs.sign()), specs); +} + +template +FMT_CONSTEXPR auto write(OutputIt out, basic_string_view s, + const format_specs& specs) -> OutputIt { + auto data = s.data(); + auto size = s.size(); + if (specs.precision >= 0 && to_unsigned(specs.precision) < size) + size = code_point_index(s, to_unsigned(specs.precision)); + + bool is_debug = specs.type() == presentation_type::debug; + if (is_debug) { + auto buf = counting_buffer(); + write_escaped_string(basic_appender(buf), s); + size = buf.count(); + } + + size_t width = 0; + if (specs.width != 0) { + width = + is_debug ? size : compute_width(basic_string_view(data, size)); + } + return write_padded( + out, specs, size, width, [=](reserve_iterator it) { + return is_debug ? write_escaped_string(it, s) + : copy(data, data + size, it); + }); +} +template +FMT_CONSTEXPR auto write(OutputIt out, basic_string_view s, + const format_specs& specs, locale_ref) -> OutputIt { + return write(out, s, specs); +} +template +FMT_CONSTEXPR auto write(OutputIt out, const Char* s, const format_specs& specs, + locale_ref) -> OutputIt { + if (specs.type() == presentation_type::pointer) + return write_ptr(out, bit_cast(s), &specs); + if (!s) report_error("string pointer is null"); + return write(out, basic_string_view(s), specs, {}); +} + +template ::value && + !std::is_same::value && + !std::is_same::value)> +FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt { + auto abs_value = static_cast>(value); + bool negative = is_negative(value); + // Don't do -abs_value since it trips unsigned-integer-overflow sanitizer. + if (negative) abs_value = ~abs_value + 1; + int num_digits = count_digits(abs_value); + auto size = (negative ? 1 : 0) + static_cast(num_digits); + if (auto ptr = to_pointer(out, size)) { + if (negative) *ptr++ = static_cast('-'); + format_decimal(ptr, abs_value, num_digits); + return out; + } + if (negative) *out++ = static_cast('-'); + return format_decimal(out, abs_value, num_digits); +} + +template +FMT_CONSTEXPR auto parse_align(const Char* begin, const Char* end, + format_specs& specs) -> const Char* { + FMT_ASSERT(begin != end, ""); + auto alignment = align::none; + auto p = begin + code_point_length(begin); + if (end - p <= 0) p = begin; + for (;;) { + switch (to_ascii(*p)) { + case '<': alignment = align::left; break; + case '>': alignment = align::right; break; + case '^': alignment = align::center; break; + } + if (alignment != align::none) { + if (p != begin) { + auto c = *begin; + if (c == '}') return begin; + if (c == '{') { + report_error("invalid fill character '{'"); + return begin; + } + specs.set_fill(basic_string_view(begin, to_unsigned(p - begin))); + begin = p + 1; + } else { + ++begin; + } + break; + } else if (p == begin) { + break; + } + p = begin; + } + specs.set_align(alignment); + return begin; +} + +template +FMT_CONSTEXPR20 auto write_nonfinite(OutputIt out, bool isnan, + format_specs specs, sign s) -> OutputIt { + auto str = + isnan ? (specs.upper() ? "NAN" : "nan") : (specs.upper() ? "INF" : "inf"); + constexpr size_t str_size = 3; + auto size = str_size + (s != sign::none ? 1 : 0); + // Replace '0'-padding with space for non-finite values. + const bool is_zero_fill = + specs.fill_size() == 1 && specs.fill_unit() == '0'; + if (is_zero_fill) specs.set_fill(' '); + return write_padded(out, specs, size, + [=](reserve_iterator it) { + if (s != sign::none) + *it++ = detail::getsign(s); + return copy(str, str + str_size, it); + }); +} + +// A decimal floating-point number significand * pow(10, exp). +struct big_decimal_fp { + const char* significand; + int significand_size; + int exponent; +}; + +constexpr auto get_significand_size(const big_decimal_fp& f) -> int { + return f.significand_size; +} +template +inline auto get_significand_size(const dragonbox::decimal_fp& f) -> int { + return count_digits(f.significand); +} + +template +constexpr auto write_significand(OutputIt out, const char* significand, + int significand_size) -> OutputIt { + return copy(significand, significand + significand_size, out); +} +template +inline auto write_significand(OutputIt out, UInt significand, + int significand_size) -> OutputIt { + return format_decimal(out, significand, significand_size); +} +template +FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand, + int significand_size, int exponent, + const Grouping& grouping) -> OutputIt { + if (!grouping.has_separator()) { + out = write_significand(out, significand, significand_size); + return detail::fill_n(out, exponent, static_cast('0')); + } + auto buffer = memory_buffer(); + write_significand(appender(buffer), significand, significand_size); + detail::fill_n(appender(buffer), exponent, '0'); + return grouping.apply(out, string_view(buffer.data(), buffer.size())); +} + +template ::value)> +inline auto write_significand(Char* out, UInt significand, int significand_size, + int integral_size, Char decimal_point) -> Char* { + if (!decimal_point) return format_decimal(out, significand, significand_size); + out += significand_size + 1; + Char* end = out; + int floating_size = significand_size - integral_size; + for (int i = floating_size / 2; i > 0; --i) { + out -= 2; + write2digits(out, static_cast(significand % 100)); + significand /= 100; + } + if (floating_size % 2 != 0) { + *--out = static_cast('0' + significand % 10); + significand /= 10; + } + *--out = decimal_point; + format_decimal(out - integral_size, significand, integral_size); + return end; +} + +template >::value)> +inline auto write_significand(OutputIt out, UInt significand, + int significand_size, int integral_size, + Char decimal_point) -> OutputIt { + // Buffer is large enough to hold digits (digits10 + 1) and a decimal point. + Char buffer[digits10() + 2]; + auto end = write_significand(buffer, significand, significand_size, + integral_size, decimal_point); + return detail::copy_noinline(buffer, end, out); +} + +template +FMT_CONSTEXPR auto write_significand(OutputIt out, const char* significand, + int significand_size, int integral_size, + Char decimal_point) -> OutputIt { + out = detail::copy_noinline(significand, significand + integral_size, + out); + if (!decimal_point) return out; + *out++ = decimal_point; + return detail::copy_noinline(significand + integral_size, + significand + significand_size, out); +} + +template +FMT_CONSTEXPR20 auto write_significand(OutputIt out, T significand, + int significand_size, int integral_size, + Char decimal_point, + const Grouping& grouping) -> OutputIt { + if (!grouping.has_separator()) { + return write_significand(out, significand, significand_size, integral_size, + decimal_point); + } + auto buffer = basic_memory_buffer(); + write_significand(basic_appender(buffer), significand, significand_size, + integral_size, decimal_point); + grouping.apply( + out, basic_string_view(buffer.data(), to_unsigned(integral_size))); + return detail::copy_noinline(buffer.data() + integral_size, + buffer.end(), out); +} + +template > +FMT_CONSTEXPR20 auto do_write_float(OutputIt out, const DecimalFP& f, + const format_specs& specs, sign s, + int exp_upper, locale_ref loc) -> OutputIt { + auto significand = f.significand; + int significand_size = get_significand_size(f); + const Char zero = static_cast('0'); + size_t size = to_unsigned(significand_size) + (s != sign::none ? 1 : 0); + using iterator = reserve_iterator; + + Char decimal_point = specs.localized() ? detail::decimal_point(loc) + : static_cast('.'); + + int output_exp = f.exponent + significand_size - 1; + auto use_exp_format = [=]() { + if (specs.type() == presentation_type::exp) return true; + if (specs.type() == presentation_type::fixed) return false; + // Use the fixed notation if the exponent is in [exp_lower, exp_upper), + // e.g. 0.0001 instead of 1e-04. Otherwise use the exponent notation. + const int exp_lower = -4; + return output_exp < exp_lower || + output_exp >= (specs.precision > 0 ? specs.precision : exp_upper); + }; + if (use_exp_format()) { + int num_zeros = 0; + if (specs.alt()) { + num_zeros = specs.precision - significand_size; + if (num_zeros < 0) num_zeros = 0; + size += to_unsigned(num_zeros); + } else if (significand_size == 1) { + decimal_point = Char(); + } + auto abs_output_exp = output_exp >= 0 ? output_exp : -output_exp; + int exp_digits = 2; + if (abs_output_exp >= 100) exp_digits = abs_output_exp >= 1000 ? 4 : 3; + + size += to_unsigned((decimal_point ? 1 : 0) + 2 + exp_digits); + char exp_char = specs.upper() ? 'E' : 'e'; + auto write = [=](iterator it) { + if (s != sign::none) *it++ = detail::getsign(s); + // Insert a decimal point after the first digit and add an exponent. + it = write_significand(it, significand, significand_size, 1, + decimal_point); + if (num_zeros > 0) it = detail::fill_n(it, num_zeros, zero); + *it++ = static_cast(exp_char); + return write_exponent(output_exp, it); + }; + return specs.width > 0 + ? write_padded(out, specs, size, write) + : base_iterator(out, write(reserve(out, size))); + } + + int exp = f.exponent + significand_size; + if (f.exponent >= 0) { + // 1234e5 -> 123400000[.0+] + size += to_unsigned(f.exponent); + int num_zeros = specs.precision - exp; + abort_fuzzing_if(num_zeros > 5000); + if (specs.alt()) { + ++size; + if (num_zeros <= 0 && specs.type() != presentation_type::fixed) + num_zeros = 0; + if (num_zeros > 0) size += to_unsigned(num_zeros); + } + auto grouping = Grouping(loc, specs.localized()); + size += to_unsigned(grouping.count_separators(exp)); + return write_padded(out, specs, size, [&](iterator it) { + if (s != sign::none) *it++ = detail::getsign(s); + it = write_significand(it, significand, significand_size, + f.exponent, grouping); + if (!specs.alt()) return it; + *it++ = decimal_point; + return num_zeros > 0 ? detail::fill_n(it, num_zeros, zero) : it; + }); + } else if (exp > 0) { + // 1234e-2 -> 12.34[0+] + int num_zeros = specs.alt() ? specs.precision - significand_size : 0; + size += 1 + static_cast(max_of(num_zeros, 0)); + auto grouping = Grouping(loc, specs.localized()); + size += to_unsigned(grouping.count_separators(exp)); + return write_padded(out, specs, size, [&](iterator it) { + if (s != sign::none) *it++ = detail::getsign(s); + it = write_significand(it, significand, significand_size, exp, + decimal_point, grouping); + return num_zeros > 0 ? detail::fill_n(it, num_zeros, zero) : it; + }); + } + // 1234e-6 -> 0.001234 + int num_zeros = -exp; + if (significand_size == 0 && specs.precision >= 0 && + specs.precision < num_zeros) { + num_zeros = specs.precision; + } + bool pointy = num_zeros != 0 || significand_size != 0 || specs.alt(); + size += 1 + (pointy ? 1 : 0) + to_unsigned(num_zeros); + return write_padded(out, specs, size, [&](iterator it) { + if (s != sign::none) *it++ = detail::getsign(s); + *it++ = zero; + if (!pointy) return it; + *it++ = decimal_point; + it = detail::fill_n(it, num_zeros, zero); + return write_significand(it, significand, significand_size); + }); +} + +template class fallback_digit_grouping { + public: + constexpr fallback_digit_grouping(locale_ref, bool) {} + + constexpr auto has_separator() const -> bool { return false; } + + constexpr auto count_separators(int) const -> int { return 0; } + + template + constexpr auto apply(Out out, basic_string_view) const -> Out { + return out; + } +}; + +template +FMT_CONSTEXPR20 auto write_float(OutputIt out, const DecimalFP& f, + const format_specs& specs, sign s, + int exp_upper, locale_ref loc) -> OutputIt { + if (is_constant_evaluated()) { + return do_write_float>(out, f, specs, s, + exp_upper, loc); + } else { + return do_write_float(out, f, specs, s, exp_upper, loc); + } +} + +template constexpr auto isnan(T value) -> bool { + return value != value; // std::isnan doesn't support __float128. +} + +template +struct has_isfinite : std::false_type {}; + +template +struct has_isfinite> + : std::true_type {}; + +template ::value&& has_isfinite::value)> +FMT_CONSTEXPR20 auto isfinite(T value) -> bool { + constexpr T inf = T(std::numeric_limits::infinity()); + if (is_constant_evaluated()) + return !detail::isnan(value) && value < inf && value > -inf; + return std::isfinite(value); +} +template ::value)> +FMT_CONSTEXPR auto isfinite(T value) -> bool { + T inf = T(std::numeric_limits::infinity()); + // std::isfinite doesn't support __float128. + return !detail::isnan(value) && value < inf && value > -inf; +} + +template ::value)> +FMT_INLINE FMT_CONSTEXPR bool signbit(T value) { + if (is_constant_evaluated()) { +#ifdef __cpp_if_constexpr + if constexpr (std::numeric_limits::is_iec559) { + auto bits = detail::bit_cast(static_cast(value)); + return (bits >> (num_bits() - 1)) != 0; + } +#endif + } + return std::signbit(static_cast(value)); +} + +inline FMT_CONSTEXPR20 void adjust_precision(int& precision, int exp10) { + // Adjust fixed precision by exponent because it is relative to decimal + // point. + if (exp10 > 0 && precision > max_value() - exp10) + FMT_THROW(format_error("number is too big")); + precision += exp10; +} + +class bigint { + private: + // A bigint is a number in the form bigit_[N - 1] ... bigit_[0] * 32^exp_. + using bigit = uint32_t; // A big digit. + using double_bigit = uint64_t; + enum { bigit_bits = num_bits() }; + enum { bigits_capacity = 32 }; + basic_memory_buffer bigits_; + int exp_; + + friend struct formatter; + + FMT_CONSTEXPR auto get_bigit(int i) const -> bigit { + return i >= exp_ && i < num_bigits() ? bigits_[i - exp_] : 0; + } + + FMT_CONSTEXPR void subtract_bigits(int index, bigit other, bigit& borrow) { + auto result = double_bigit(bigits_[index]) - other - borrow; + bigits_[index] = static_cast(result); + borrow = static_cast(result >> (bigit_bits * 2 - 1)); + } + + FMT_CONSTEXPR void remove_leading_zeros() { + int num_bigits = static_cast(bigits_.size()) - 1; + while (num_bigits > 0 && bigits_[num_bigits] == 0) --num_bigits; + bigits_.resize(to_unsigned(num_bigits + 1)); + } + + // Computes *this -= other assuming aligned bigints and *this >= other. + FMT_CONSTEXPR void subtract_aligned(const bigint& other) { + FMT_ASSERT(other.exp_ >= exp_, "unaligned bigints"); + FMT_ASSERT(compare(*this, other) >= 0, ""); + bigit borrow = 0; + int i = other.exp_ - exp_; + for (size_t j = 0, n = other.bigits_.size(); j != n; ++i, ++j) + subtract_bigits(i, other.bigits_[j], borrow); + if (borrow != 0) subtract_bigits(i, 0, borrow); + FMT_ASSERT(borrow == 0, ""); + remove_leading_zeros(); + } + + FMT_CONSTEXPR void multiply(uint32_t value) { + bigit carry = 0; + const double_bigit wide_value = value; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + double_bigit result = bigits_[i] * wide_value + carry; + bigits_[i] = static_cast(result); + carry = static_cast(result >> bigit_bits); + } + if (carry != 0) bigits_.push_back(carry); + } + + template ::value || + std::is_same::value)> + FMT_CONSTEXPR void multiply(UInt value) { + using half_uint = + conditional_t::value, uint64_t, uint32_t>; + const int shift = num_bits() - bigit_bits; + const UInt lower = static_cast(value); + const UInt upper = value >> num_bits(); + UInt carry = 0; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + UInt result = lower * bigits_[i] + static_cast(carry); + carry = (upper * bigits_[i] << shift) + (result >> bigit_bits) + + (carry >> bigit_bits); + bigits_[i] = static_cast(result); + } + while (carry != 0) { + bigits_.push_back(static_cast(carry)); + carry >>= bigit_bits; + } + } + + template ::value || + std::is_same::value)> + FMT_CONSTEXPR void assign(UInt n) { + size_t num_bigits = 0; + do { + bigits_[num_bigits++] = static_cast(n); + n >>= bigit_bits; + } while (n != 0); + bigits_.resize(num_bigits); + exp_ = 0; + } + + public: + FMT_CONSTEXPR bigint() : exp_(0) {} + explicit bigint(uint64_t n) { assign(n); } + + bigint(const bigint&) = delete; + void operator=(const bigint&) = delete; + + FMT_CONSTEXPR void assign(const bigint& other) { + auto size = other.bigits_.size(); + bigits_.resize(size); + auto data = other.bigits_.data(); + copy(data, data + size, bigits_.data()); + exp_ = other.exp_; + } + + template FMT_CONSTEXPR void operator=(Int n) { + FMT_ASSERT(n > 0, ""); + assign(uint64_or_128_t(n)); + } + + FMT_CONSTEXPR auto num_bigits() const -> int { + return static_cast(bigits_.size()) + exp_; + } + + FMT_CONSTEXPR auto operator<<=(int shift) -> bigint& { + FMT_ASSERT(shift >= 0, ""); + exp_ += shift / bigit_bits; + shift %= bigit_bits; + if (shift == 0) return *this; + bigit carry = 0; + for (size_t i = 0, n = bigits_.size(); i < n; ++i) { + bigit c = bigits_[i] >> (bigit_bits - shift); + bigits_[i] = (bigits_[i] << shift) + carry; + carry = c; + } + if (carry != 0) bigits_.push_back(carry); + return *this; + } + + template FMT_CONSTEXPR auto operator*=(Int value) -> bigint& { + FMT_ASSERT(value > 0, ""); + multiply(uint32_or_64_or_128_t(value)); + return *this; + } + + friend FMT_CONSTEXPR auto compare(const bigint& b1, const bigint& b2) -> int { + int num_bigits1 = b1.num_bigits(), num_bigits2 = b2.num_bigits(); + if (num_bigits1 != num_bigits2) return num_bigits1 > num_bigits2 ? 1 : -1; + int i = static_cast(b1.bigits_.size()) - 1; + int j = static_cast(b2.bigits_.size()) - 1; + int end = i - j; + if (end < 0) end = 0; + for (; i >= end; --i, --j) { + bigit b1_bigit = b1.bigits_[i], b2_bigit = b2.bigits_[j]; + if (b1_bigit != b2_bigit) return b1_bigit > b2_bigit ? 1 : -1; + } + if (i != j) return i > j ? 1 : -1; + return 0; + } + + // Returns compare(lhs1 + lhs2, rhs). + friend FMT_CONSTEXPR auto add_compare(const bigint& lhs1, const bigint& lhs2, + const bigint& rhs) -> int { + int max_lhs_bigits = max_of(lhs1.num_bigits(), lhs2.num_bigits()); + int num_rhs_bigits = rhs.num_bigits(); + if (max_lhs_bigits + 1 < num_rhs_bigits) return -1; + if (max_lhs_bigits > num_rhs_bigits) return 1; + double_bigit borrow = 0; + int min_exp = min_of(min_of(lhs1.exp_, lhs2.exp_), rhs.exp_); + for (int i = num_rhs_bigits - 1; i >= min_exp; --i) { + double_bigit sum = double_bigit(lhs1.get_bigit(i)) + lhs2.get_bigit(i); + bigit rhs_bigit = rhs.get_bigit(i); + if (sum > rhs_bigit + borrow) return 1; + borrow = rhs_bigit + borrow - sum; + if (borrow > 1) return -1; + borrow <<= bigit_bits; + } + return borrow != 0 ? -1 : 0; + } + + // Assigns pow(10, exp) to this bigint. + FMT_CONSTEXPR20 void assign_pow10(int exp) { + FMT_ASSERT(exp >= 0, ""); + if (exp == 0) return *this = 1; + int bitmask = 1 << (num_bits() - + countl_zero(static_cast(exp)) - 1); + // pow(10, exp) = pow(5, exp) * pow(2, exp). First compute pow(5, exp) by + // repeated squaring and multiplication. + *this = 5; + bitmask >>= 1; + while (bitmask != 0) { + square(); + if ((exp & bitmask) != 0) *this *= 5; + bitmask >>= 1; + } + *this <<= exp; // Multiply by pow(2, exp) by shifting. + } + + FMT_CONSTEXPR20 void square() { + int num_bigits = static_cast(bigits_.size()); + int num_result_bigits = 2 * num_bigits; + basic_memory_buffer n(std::move(bigits_)); + bigits_.resize(to_unsigned(num_result_bigits)); + auto sum = uint128_t(); + for (int bigit_index = 0; bigit_index < num_bigits; ++bigit_index) { + // Compute bigit at position bigit_index of the result by adding + // cross-product terms n[i] * n[j] such that i + j == bigit_index. + for (int i = 0, j = bigit_index; j >= 0; ++i, --j) { + // Most terms are multiplied twice which can be optimized in the future. + sum += double_bigit(n[i]) * n[j]; + } + bigits_[bigit_index] = static_cast(sum); + sum >>= num_bits(); // Compute the carry. + } + // Do the same for the top half. + for (int bigit_index = num_bigits; bigit_index < num_result_bigits; + ++bigit_index) { + for (int j = num_bigits - 1, i = bigit_index - j; i < num_bigits;) + sum += double_bigit(n[i++]) * n[j--]; + bigits_[bigit_index] = static_cast(sum); + sum >>= num_bits(); + } + remove_leading_zeros(); + exp_ *= 2; + } + + // If this bigint has a bigger exponent than other, adds trailing zero to make + // exponents equal. This simplifies some operations such as subtraction. + FMT_CONSTEXPR void align(const bigint& other) { + int exp_difference = exp_ - other.exp_; + if (exp_difference <= 0) return; + int num_bigits = static_cast(bigits_.size()); + bigits_.resize(to_unsigned(num_bigits + exp_difference)); + for (int i = num_bigits - 1, j = i + exp_difference; i >= 0; --i, --j) + bigits_[j] = bigits_[i]; + memset(bigits_.data(), 0, to_unsigned(exp_difference) * sizeof(bigit)); + exp_ -= exp_difference; + } + + // Divides this bignum by divisor, assigning the remainder to this and + // returning the quotient. + FMT_CONSTEXPR auto divmod_assign(const bigint& divisor) -> int { + FMT_ASSERT(this != &divisor, ""); + if (compare(*this, divisor) < 0) return 0; + FMT_ASSERT(divisor.bigits_[divisor.bigits_.size() - 1u] != 0, ""); + align(divisor); + int quotient = 0; + do { + subtract_aligned(divisor); + ++quotient; + } while (compare(*this, divisor) >= 0); + return quotient; + } +}; + +// format_dragon flags. +enum dragon { + predecessor_closer = 1, + fixup = 2, // Run fixup to correct exp10 which can be off by one. + fixed = 4, +}; + +// Formats a floating-point number using a variation of the Fixed-Precision +// Positive Floating-Point Printout ((FPP)^2) algorithm by Steele & White: +// https://fmt.dev/papers/p372-steele.pdf. +FMT_CONSTEXPR20 inline void format_dragon(basic_fp value, + unsigned flags, int num_digits, + buffer& buf, int& exp10) { + bigint numerator; // 2 * R in (FPP)^2. + bigint denominator; // 2 * S in (FPP)^2. + // lower and upper are differences between value and corresponding boundaries. + bigint lower; // (M^- in (FPP)^2). + bigint upper_store; // upper's value if different from lower. + bigint* upper = nullptr; // (M^+ in (FPP)^2). + // Shift numerator and denominator by an extra bit or two (if lower boundary + // is closer) to make lower and upper integers. This eliminates multiplication + // by 2 during later computations. + bool is_predecessor_closer = (flags & dragon::predecessor_closer) != 0; + int shift = is_predecessor_closer ? 2 : 1; + if (value.e >= 0) { + numerator = value.f; + numerator <<= value.e + shift; + lower = 1; + lower <<= value.e; + if (is_predecessor_closer) { + upper_store = 1; + upper_store <<= value.e + 1; + upper = &upper_store; + } + denominator.assign_pow10(exp10); + denominator <<= shift; + } else if (exp10 < 0) { + numerator.assign_pow10(-exp10); + lower.assign(numerator); + if (is_predecessor_closer) { + upper_store.assign(numerator); + upper_store <<= 1; + upper = &upper_store; + } + numerator *= value.f; + numerator <<= shift; + denominator = 1; + denominator <<= shift - value.e; + } else { + numerator = value.f; + numerator <<= shift; + denominator.assign_pow10(exp10); + denominator <<= shift - value.e; + lower = 1; + if (is_predecessor_closer) { + upper_store = 1ULL << 1; + upper = &upper_store; + } + } + int even = static_cast((value.f & 1) == 0); + if (!upper) upper = &lower; + bool shortest = num_digits < 0; + if ((flags & dragon::fixup) != 0) { + if (add_compare(numerator, *upper, denominator) + even <= 0) { + --exp10; + numerator *= 10; + if (num_digits < 0) { + lower *= 10; + if (upper != &lower) *upper *= 10; + } + } + if ((flags & dragon::fixed) != 0) adjust_precision(num_digits, exp10 + 1); + } + // Invariant: value == (numerator / denominator) * pow(10, exp10). + if (shortest) { + // Generate the shortest representation. + num_digits = 0; + char* data = buf.data(); + for (;;) { + int digit = numerator.divmod_assign(denominator); + bool low = compare(numerator, lower) - even < 0; // numerator <[=] lower. + // numerator + upper >[=] pow10: + bool high = add_compare(numerator, *upper, denominator) + even > 0; + data[num_digits++] = static_cast('0' + digit); + if (low || high) { + if (!low) { + ++data[num_digits - 1]; + } else if (high) { + int result = add_compare(numerator, numerator, denominator); + // Round half to even. + if (result > 0 || (result == 0 && (digit % 2) != 0)) + ++data[num_digits - 1]; + } + buf.try_resize(to_unsigned(num_digits)); + exp10 -= num_digits - 1; + return; + } + numerator *= 10; + lower *= 10; + if (upper != &lower) *upper *= 10; + } + } + // Generate the given number of digits. + exp10 -= num_digits - 1; + if (num_digits <= 0) { + auto digit = '0'; + if (num_digits == 0) { + denominator *= 10; + digit = add_compare(numerator, numerator, denominator) > 0 ? '1' : '0'; + } + buf.push_back(digit); + return; + } + buf.try_resize(to_unsigned(num_digits)); + for (int i = 0; i < num_digits - 1; ++i) { + int digit = numerator.divmod_assign(denominator); + buf[i] = static_cast('0' + digit); + numerator *= 10; + } + int digit = numerator.divmod_assign(denominator); + auto result = add_compare(numerator, numerator, denominator); + if (result > 0 || (result == 0 && (digit % 2) != 0)) { + if (digit == 9) { + const auto overflow = '0' + 10; + buf[num_digits - 1] = overflow; + // Propagate the carry. + for (int i = num_digits - 1; i > 0 && buf[i] == overflow; --i) { + buf[i] = '0'; + ++buf[i - 1]; + } + if (buf[0] == overflow) { + buf[0] = '1'; + if ((flags & dragon::fixed) != 0) + buf.push_back('0'); + else + ++exp10; + } + return; + } + ++digit; + } + buf[num_digits - 1] = static_cast('0' + digit); +} + +// Formats a floating-point number using the hexfloat format. +template ::value)> +FMT_CONSTEXPR20 void format_hexfloat(Float value, format_specs specs, + buffer& buf) { + // float is passed as double to reduce the number of instantiations and to + // simplify implementation. + static_assert(!std::is_same::value, ""); + + using info = dragonbox::float_info; + + // Assume Float is in the format [sign][exponent][significand]. + using carrier_uint = typename info::carrier_uint; + + const auto num_float_significand_bits = detail::num_significand_bits(); + + basic_fp f(value); + f.e += num_float_significand_bits; + if (!has_implicit_bit()) --f.e; + + const auto num_fraction_bits = + num_float_significand_bits + (has_implicit_bit() ? 1 : 0); + const auto num_xdigits = (num_fraction_bits + 3) / 4; + + const auto leading_shift = ((num_xdigits - 1) * 4); + const auto leading_mask = carrier_uint(0xF) << leading_shift; + const auto leading_xdigit = + static_cast((f.f & leading_mask) >> leading_shift); + if (leading_xdigit > 1) f.e -= (32 - countl_zero(leading_xdigit) - 1); + + int print_xdigits = num_xdigits - 1; + if (specs.precision >= 0 && print_xdigits > specs.precision) { + const int shift = ((print_xdigits - specs.precision - 1) * 4); + const auto mask = carrier_uint(0xF) << shift; + const auto v = static_cast((f.f & mask) >> shift); + + if (v >= 8) { + const auto inc = carrier_uint(1) << (shift + 4); + f.f += inc; + f.f &= ~(inc - 1); + } + + // Check long double overflow + if (!has_implicit_bit()) { + const auto implicit_bit = carrier_uint(1) << num_float_significand_bits; + if ((f.f & implicit_bit) == implicit_bit) { + f.f >>= 4; + f.e += 4; + } + } + + print_xdigits = specs.precision; + } + + char xdigits[num_bits() / 4]; + detail::fill_n(xdigits, sizeof(xdigits), '0'); + format_base2e(4, xdigits, f.f, num_xdigits, specs.upper()); + + // Remove zero tail + while (print_xdigits > 0 && xdigits[print_xdigits] == '0') --print_xdigits; + + buf.push_back('0'); + buf.push_back(specs.upper() ? 'X' : 'x'); + buf.push_back(xdigits[0]); + if (specs.alt() || print_xdigits > 0 || print_xdigits < specs.precision) + buf.push_back('.'); + buf.append(xdigits + 1, xdigits + 1 + print_xdigits); + for (; print_xdigits < specs.precision; ++print_xdigits) buf.push_back('0'); + + buf.push_back(specs.upper() ? 'P' : 'p'); + + uint32_t abs_e; + if (f.e < 0) { + buf.push_back('-'); + abs_e = static_cast(-f.e); + } else { + buf.push_back('+'); + abs_e = static_cast(f.e); + } + format_decimal(appender(buf), abs_e, detail::count_digits(abs_e)); +} + +template ::value)> +FMT_CONSTEXPR20 void format_hexfloat(Float value, format_specs specs, + buffer& buf) { + format_hexfloat(static_cast(value), specs, buf); +} + +constexpr auto fractional_part_rounding_thresholds(int index) -> uint32_t { + // For checking rounding thresholds. + // The kth entry is chosen to be the smallest integer such that the + // upper 32-bits of 10^(k+1) times it is strictly bigger than 5 * 10^k. + // It is equal to ceil(2^31 + 2^32/10^(k + 1)). + // These are stored in a string literal because we cannot have static arrays + // in constexpr functions and non-static ones are poorly optimized. + return U"\x9999999a\x828f5c29\x80418938\x80068db9\x8000a7c6\x800010c7" + U"\x800001ae\x8000002b"[index]; +} + +template +FMT_CONSTEXPR20 auto format_float(Float value, int precision, + const format_specs& specs, bool binary32, + buffer& buf) -> int { + // float is passed as double to reduce the number of instantiations. + static_assert(!std::is_same::value, ""); + auto converted_value = convert_float(value); + + const bool fixed = specs.type() == presentation_type::fixed; + if (value == 0) { + if (precision <= 0 || !fixed) { + buf.push_back('0'); + return 0; + } + buf.try_resize(to_unsigned(precision)); + fill_n(buf.data(), precision, '0'); + return -precision; + } + + int exp = 0; + bool use_dragon = true; + unsigned dragon_flags = 0; + if (!is_fast_float() || is_constant_evaluated()) { + const auto inv_log2_10 = 0.3010299956639812; // 1 / log2(10) + using info = dragonbox::float_info; + const auto f = basic_fp(converted_value); + // Compute exp, an approximate power of 10, such that + // 10^(exp - 1) <= value < 10^exp or 10^exp <= value < 10^(exp + 1). + // This is based on log10(value) == log2(value) / log2(10) and approximation + // of log2(value) by e + num_fraction_bits idea from double-conversion. + auto e = (f.e + count_digits<1>(f.f) - 1) * inv_log2_10 - 1e-10; + exp = static_cast(e); + if (e > exp) ++exp; // Compute ceil. + dragon_flags = dragon::fixup; + } else { + // Extract significand bits and exponent bits. + using info = dragonbox::float_info; + auto br = bit_cast(static_cast(value)); + + const uint64_t significand_mask = + (static_cast(1) << num_significand_bits()) - 1; + uint64_t significand = (br & significand_mask); + int exponent = static_cast((br & exponent_mask()) >> + num_significand_bits()); + + if (exponent != 0) { // Check if normal. + exponent -= exponent_bias() + num_significand_bits(); + significand |= + (static_cast(1) << num_significand_bits()); + significand <<= 1; + } else { + // Normalize subnormal inputs. + FMT_ASSERT(significand != 0, "zeros should not appear here"); + int shift = countl_zero(significand); + FMT_ASSERT(shift >= num_bits() - num_significand_bits(), + ""); + shift -= (num_bits() - num_significand_bits() - 2); + exponent = (std::numeric_limits::min_exponent - + num_significand_bits()) - + shift; + significand <<= shift; + } + + // Compute the first several nonzero decimal significand digits. + // We call the number we get the first segment. + const int k = info::kappa - dragonbox::floor_log10_pow2(exponent); + exp = -k; + const int beta = exponent + dragonbox::floor_log2_pow10(k); + uint64_t first_segment; + bool has_more_segments; + int digits_in_the_first_segment; + { + const auto r = dragonbox::umul192_upper128( + significand << beta, dragonbox::get_cached_power(k)); + first_segment = r.high(); + has_more_segments = r.low() != 0; + + // The first segment can have 18 ~ 19 digits. + if (first_segment >= 1000000000000000000ULL) { + digits_in_the_first_segment = 19; + } else { + // When it is of 18-digits, we align it to 19-digits by adding a bogus + // zero at the end. + digits_in_the_first_segment = 18; + first_segment *= 10; + } + } + + // Compute the actual number of decimal digits to print. + if (fixed) adjust_precision(precision, exp + digits_in_the_first_segment); + + // Use Dragon4 only when there might be not enough digits in the first + // segment. + if (digits_in_the_first_segment > precision) { + use_dragon = false; + + if (precision <= 0) { + exp += digits_in_the_first_segment; + + if (precision < 0) { + // Nothing to do, since all we have are just leading zeros. + buf.try_resize(0); + } else { + // We may need to round-up. + buf.try_resize(1); + if ((first_segment | static_cast(has_more_segments)) > + 5000000000000000000ULL) { + buf[0] = '1'; + } else { + buf[0] = '0'; + } + } + } // precision <= 0 + else { + exp += digits_in_the_first_segment - precision; + + // When precision > 0, we divide the first segment into three + // subsegments, each with 9, 9, and 0 ~ 1 digits so that each fits + // in 32-bits which usually allows faster calculation than in + // 64-bits. Since some compiler (e.g. MSVC) doesn't know how to optimize + // division-by-constant for large 64-bit divisors, we do it here + // manually. The magic number 7922816251426433760 below is equal to + // ceil(2^(64+32) / 10^10). + const uint32_t first_subsegment = static_cast( + dragonbox::umul128_upper64(first_segment, 7922816251426433760ULL) >> + 32); + const uint64_t second_third_subsegments = + first_segment - first_subsegment * 10000000000ULL; + + uint64_t prod; + uint32_t digits; + bool should_round_up; + int number_of_digits_to_print = min_of(precision, 9); + + // Print a 9-digits subsegment, either the first or the second. + auto print_subsegment = [&](uint32_t subsegment, char* buffer) { + int number_of_digits_printed = 0; + + // If we want to print an odd number of digits from the subsegment, + if ((number_of_digits_to_print & 1) != 0) { + // Convert to 64-bit fixed-point fractional form with 1-digit + // integer part. The magic number 720575941 is a good enough + // approximation of 2^(32 + 24) / 10^8; see + // https://jk-jeon.github.io/posts/2022/12/fixed-precision-formatting/#fixed-length-case + // for details. + prod = ((subsegment * static_cast(720575941)) >> 24) + 1; + digits = static_cast(prod >> 32); + *buffer = static_cast('0' + digits); + number_of_digits_printed++; + } + // If we want to print an even number of digits from the + // first_subsegment, + else { + // Convert to 64-bit fixed-point fractional form with 2-digits + // integer part. The magic number 450359963 is a good enough + // approximation of 2^(32 + 20) / 10^7; see + // https://jk-jeon.github.io/posts/2022/12/fixed-precision-formatting/#fixed-length-case + // for details. + prod = ((subsegment * static_cast(450359963)) >> 20) + 1; + digits = static_cast(prod >> 32); + write2digits(buffer, digits); + number_of_digits_printed += 2; + } + + // Print all digit pairs. + while (number_of_digits_printed < number_of_digits_to_print) { + prod = static_cast(prod) * static_cast(100); + digits = static_cast(prod >> 32); + write2digits(buffer + number_of_digits_printed, digits); + number_of_digits_printed += 2; + } + }; + + // Print first subsegment. + print_subsegment(first_subsegment, buf.data()); + + // Perform rounding if the first subsegment is the last subsegment to + // print. + if (precision <= 9) { + // Rounding inside the subsegment. + // We round-up if: + // - either the fractional part is strictly larger than 1/2, or + // - the fractional part is exactly 1/2 and the last digit is odd. + // We rely on the following observations: + // - If fractional_part >= threshold, then the fractional part is + // strictly larger than 1/2. + // - If the MSB of fractional_part is set, then the fractional part + // must be at least 1/2. + // - When the MSB of fractional_part is set, either + // second_third_subsegments being nonzero or has_more_segments + // being true means there are further digits not printed, so the + // fractional part is strictly larger than 1/2. + if (precision < 9) { + uint32_t fractional_part = static_cast(prod); + should_round_up = + fractional_part >= fractional_part_rounding_thresholds( + 8 - number_of_digits_to_print) || + ((fractional_part >> 31) & + ((digits & 1) | (second_third_subsegments != 0) | + has_more_segments)) != 0; + } + // Rounding at the subsegment boundary. + // In this case, the fractional part is at least 1/2 if and only if + // second_third_subsegments >= 5000000000ULL, and is strictly larger + // than 1/2 if we further have either second_third_subsegments > + // 5000000000ULL or has_more_segments == true. + else { + should_round_up = second_third_subsegments > 5000000000ULL || + (second_third_subsegments == 5000000000ULL && + ((digits & 1) != 0 || has_more_segments)); + } + } + // Otherwise, print the second subsegment. + else { + // Compilers are not aware of how to leverage the maximum value of + // second_third_subsegments to find out a better magic number which + // allows us to eliminate an additional shift. 1844674407370955162 = + // ceil(2^64/10) < ceil(2^64*(10^9/(10^10 - 1))). + const uint32_t second_subsegment = + static_cast(dragonbox::umul128_upper64( + second_third_subsegments, 1844674407370955162ULL)); + const uint32_t third_subsegment = + static_cast(second_third_subsegments) - + second_subsegment * 10; + + number_of_digits_to_print = precision - 9; + print_subsegment(second_subsegment, buf.data() + 9); + + // Rounding inside the subsegment. + if (precision < 18) { + // The condition third_subsegment != 0 implies that the segment was + // of 19 digits, so in this case the third segment should be + // consisting of a genuine digit from the input. + uint32_t fractional_part = static_cast(prod); + should_round_up = + fractional_part >= fractional_part_rounding_thresholds( + 8 - number_of_digits_to_print) || + ((fractional_part >> 31) & + ((digits & 1) | (third_subsegment != 0) | + has_more_segments)) != 0; + } + // Rounding at the subsegment boundary. + else { + // In this case, the segment must be of 19 digits, thus + // the third subsegment should be consisting of a genuine digit from + // the input. + should_round_up = third_subsegment > 5 || + (third_subsegment == 5 && + ((digits & 1) != 0 || has_more_segments)); + } + } + + // Round-up if necessary. + if (should_round_up) { + ++buf[precision - 1]; + for (int i = precision - 1; i > 0 && buf[i] > '9'; --i) { + buf[i] = '0'; + ++buf[i - 1]; + } + if (buf[0] > '9') { + buf[0] = '1'; + if (fixed) + buf[precision++] = '0'; + else + ++exp; + } + } + buf.try_resize(to_unsigned(precision)); + } + } // if (digits_in_the_first_segment > precision) + else { + // Adjust the exponent for its use in Dragon4. + exp += digits_in_the_first_segment - 1; + } + } + if (use_dragon) { + auto f = basic_fp(); + bool is_predecessor_closer = binary32 ? f.assign(static_cast(value)) + : f.assign(converted_value); + if (is_predecessor_closer) dragon_flags |= dragon::predecessor_closer; + if (fixed) dragon_flags |= dragon::fixed; + // Limit precision to the maximum possible number of significant digits in + // an IEEE754 double because we don't need to generate zeros. + const int max_double_digits = 767; + if (precision > max_double_digits) precision = max_double_digits; + format_dragon(f, dragon_flags, precision, buf, exp); + } + if (!fixed && !specs.alt()) { + // Remove trailing zeros. + auto num_digits = buf.size(); + while (num_digits > 0 && buf[num_digits - 1] == '0') { + --num_digits; + ++exp; + } + buf.try_resize(num_digits); + } + return exp; +} + +// Numbers with exponents greater or equal to the returned value will use +// the exponential notation. +template constexpr auto exp_upper() -> int { + return std::numeric_limits::digits10 != 0 + ? min_of(16, std::numeric_limits::digits10 + 1) + : 16; +} + +template +FMT_CONSTEXPR20 auto write_float(OutputIt out, T value, format_specs specs, + locale_ref loc) -> OutputIt { + // Use signbit because value < 0 is false for NaN. + sign s = detail::signbit(value) ? sign::minus : specs.sign(); + + if (!detail::isfinite(value)) + return write_nonfinite(out, detail::isnan(value), specs, s); + + if (specs.align() == align::numeric && s != sign::none) { + *out++ = detail::getsign(s); + s = sign::none; + if (specs.width != 0) --specs.width; + } + + constexpr int exp_upper = detail::exp_upper(); + int precision = specs.precision; + if (precision < 0) { + if (specs.type() != presentation_type::none) { + precision = 6; + } else if (is_fast_float::value && !is_constant_evaluated()) { + // Use Dragonbox for the shortest format. + using floaty = conditional_t= sizeof(double), double, float>; + auto dec = dragonbox::to_decimal(static_cast(value)); + return write_float(out, dec, specs, s, exp_upper, loc); + } + } + + memory_buffer buffer; + if (specs.type() == presentation_type::hexfloat) { + if (s != sign::none) buffer.push_back(detail::getsign(s)); + format_hexfloat(convert_float(value), specs, buffer); + return write_bytes(out, {buffer.data(), buffer.size()}, + specs); + } + + if (specs.type() == presentation_type::exp) { + if (precision == max_value()) + report_error("number is too big"); + else + ++precision; + if (specs.precision != 0) specs.set_alt(); + } else if (specs.type() == presentation_type::fixed) { + if (specs.precision != 0) specs.set_alt(); + } else if (precision == 0) { + precision = 1; + } + int exp = format_float(convert_float(value), precision, specs, + std::is_same(), buffer); + + specs.precision = precision; + auto f = big_decimal_fp{buffer.data(), static_cast(buffer.size()), exp}; + return write_float(out, f, specs, s, exp_upper, loc); +} + +template ::value)> +FMT_CONSTEXPR20 auto write(OutputIt out, T value, format_specs specs, + locale_ref loc = {}) -> OutputIt { + return specs.localized() && write_loc(out, value, specs, loc) + ? out + : write_float(out, value, specs, loc); +} + +template ::value)> +FMT_CONSTEXPR20 auto write(OutputIt out, T value) -> OutputIt { + if (is_constant_evaluated()) return write(out, value, format_specs()); + + auto s = detail::signbit(value) ? sign::minus : sign::none; + + constexpr auto specs = format_specs(); + using floaty = conditional_t= sizeof(double), double, float>; + using floaty_uint = typename dragonbox::float_info::carrier_uint; + floaty_uint mask = exponent_mask(); + if ((bit_cast(value) & mask) == mask) + return write_nonfinite(out, std::isnan(value), specs, s); + + auto dec = dragonbox::to_decimal(static_cast(value)); + return write_float(out, dec, specs, s, exp_upper(), {}); +} + +template ::value && + !is_fast_float::value)> +inline auto write(OutputIt out, T value) -> OutputIt { + return write(out, value, format_specs()); +} + +template +auto write(OutputIt out, monostate, format_specs = {}, locale_ref = {}) + -> OutputIt { + FMT_ASSERT(false, ""); + return out; +} + +template +FMT_CONSTEXPR auto write(OutputIt out, basic_string_view value) + -> OutputIt { + return copy_noinline(value.begin(), value.end(), out); +} + +template ::value)> +constexpr auto write(OutputIt out, const T& value) -> OutputIt { + return write(out, to_string_view(value)); +} + +// FMT_ENABLE_IF() condition separated to workaround an MSVC bug. +template < + typename Char, typename OutputIt, typename T, + bool check = std::is_enum::value && !std::is_same::value && + mapped_type_constant::value != type::custom_type, + FMT_ENABLE_IF(check)> +FMT_CONSTEXPR auto write(OutputIt out, T value) -> OutputIt { + return write(out, static_cast>(value)); +} + +template ::value)> +FMT_CONSTEXPR auto write(OutputIt out, T value, const format_specs& specs = {}, + locale_ref = {}) -> OutputIt { + return specs.type() != presentation_type::none && + specs.type() != presentation_type::string + ? write(out, value ? 1 : 0, specs, {}) + : write_bytes(out, value ? "true" : "false", specs); +} + +template +FMT_CONSTEXPR auto write(OutputIt out, Char value) -> OutputIt { + auto it = reserve(out, 1); + *it++ = value; + return base_iterator(out, it); +} + +template +FMT_CONSTEXPR20 auto write(OutputIt out, const Char* value) -> OutputIt { + if (value) return write(out, basic_string_view(value)); + report_error("string pointer is null"); + return out; +} + +template ::value)> +auto write(OutputIt out, const T* value, const format_specs& specs = {}, + locale_ref = {}) -> OutputIt { + return write_ptr(out, bit_cast(value), &specs); +} + +template ::value == + type::custom_type && + !std::is_fundamental::value)> +FMT_CONSTEXPR auto write(OutputIt out, const T& value) -> OutputIt { + auto f = formatter(); + auto parse_ctx = parse_context({}); + f.parse(parse_ctx); + auto ctx = basic_format_context(out, {}, {}); + return f.format(value, ctx); +} + +template +using is_builtin = + bool_constant::value || FMT_BUILTIN_TYPES>; + +// An argument visitor that formats the argument and writes it via the output +// iterator. It's a class and not a generic lambda for compatibility with C++11. +template struct default_arg_formatter { + using context = buffered_context; + + basic_appender out; + + void operator()(monostate) { report_error("argument not found"); } + + template ::value)> + void operator()(T value) { + write(out, value); + } + + template ::value)> + void operator()(T) { + FMT_ASSERT(false, ""); + } + + void operator()(typename basic_format_arg::handle h) { + // Use a null locale since the default format must be unlocalized. + auto parse_ctx = parse_context({}); + auto format_ctx = context(out, {}, {}); + h.format(parse_ctx, format_ctx); + } +}; + +template struct arg_formatter { + basic_appender out; + const format_specs& specs; + FMT_NO_UNIQUE_ADDRESS locale_ref locale; + + template ::value)> + FMT_CONSTEXPR FMT_INLINE void operator()(T value) { + detail::write(out, value, specs, locale); + } + + template ::value)> + void operator()(T) { + FMT_ASSERT(false, ""); + } + + void operator()(typename basic_format_arg>::handle) { + // User-defined types are handled separately because they require access + // to the parse context. + } +}; + +struct dynamic_spec_getter { + template ::value)> + FMT_CONSTEXPR auto operator()(T value) -> unsigned long long { + return is_negative(value) ? ~0ull : static_cast(value); + } + + template ::value)> + FMT_CONSTEXPR auto operator()(T) -> unsigned long long { + report_error("width/precision is not integer"); + return 0; + } +}; + +template +FMT_CONSTEXPR auto get_arg(Context& ctx, ID id) -> basic_format_arg { + auto arg = ctx.arg(id); + if (!arg) report_error("argument not found"); + return arg; +} + +template +FMT_CONSTEXPR int get_dynamic_spec( + arg_id_kind kind, const arg_ref& ref, + Context& ctx) { + FMT_ASSERT(kind != arg_id_kind::none, ""); + auto arg = + kind == arg_id_kind::index ? ctx.arg(ref.index) : ctx.arg(ref.name); + if (!arg) report_error("argument not found"); + unsigned long long value = arg.visit(dynamic_spec_getter()); + if (value > to_unsigned(max_value())) + report_error("width/precision is out of range"); + return static_cast(value); +} + +template +FMT_CONSTEXPR void handle_dynamic_spec( + arg_id_kind kind, int& value, + const arg_ref& ref, Context& ctx) { + if (kind != arg_id_kind::none) value = get_dynamic_spec(kind, ref, ctx); +} + +#if FMT_USE_NONTYPE_TEMPLATE_ARGS +template Str> +struct static_named_arg : view { + static constexpr auto name = Str.data; + + const T& value; + static_named_arg(const T& v) : value(v) {} +}; + +template Str> +struct is_named_arg> : std::true_type {}; + +template Str> +struct is_static_named_arg> : std::true_type { +}; + +template Str> +struct udl_arg { + template auto operator=(T&& value) const { + return static_named_arg(std::forward(value)); + } +}; +#else +template struct udl_arg { + const Char* str; + + template auto operator=(T&& value) const -> named_arg { + return {str, std::forward(value)}; + } +}; +#endif // FMT_USE_NONTYPE_TEMPLATE_ARGS + +template struct format_handler { + parse_context parse_ctx; + buffered_context ctx; + + void on_text(const Char* begin, const Char* end) { + copy_noinline(begin, end, ctx.out()); + } + + FMT_CONSTEXPR auto on_arg_id() -> int { return parse_ctx.next_arg_id(); } + FMT_CONSTEXPR auto on_arg_id(int id) -> int { + parse_ctx.check_arg_id(id); + return id; + } + FMT_CONSTEXPR auto on_arg_id(basic_string_view id) -> int { + parse_ctx.check_arg_id(id); + int arg_id = ctx.arg_id(id); + if (arg_id < 0) report_error("argument not found"); + return arg_id; + } + + FMT_INLINE void on_replacement_field(int id, const Char*) { + ctx.arg(id).visit(default_arg_formatter{ctx.out()}); + } + + auto on_format_specs(int id, const Char* begin, const Char* end) + -> const Char* { + auto arg = get_arg(ctx, id); + // Not using a visitor for custom types gives better codegen. + if (arg.format_custom(begin, parse_ctx, ctx)) return parse_ctx.begin(); + + auto specs = dynamic_format_specs(); + begin = parse_format_specs(begin, end, specs, parse_ctx, arg.type()); + if (specs.dynamic()) { + handle_dynamic_spec(specs.dynamic_width(), specs.width, specs.width_ref, + ctx); + handle_dynamic_spec(specs.dynamic_precision(), specs.precision, + specs.precision_ref, ctx); + } + + arg.visit(arg_formatter{ctx.out(), specs, ctx.locale()}); + return begin; + } + + FMT_NORETURN void on_error(const char* message) { report_error(message); } +}; + +using format_func = void (*)(detail::buffer&, int, const char*); +FMT_API void do_report_error(format_func func, int error_code, + const char* message) noexcept; + +FMT_API void format_error_code(buffer& out, int error_code, + string_view message) noexcept; + +template +template +FMT_CONSTEXPR auto native_formatter::format( + const T& val, FormatContext& ctx) const -> decltype(ctx.out()) { + if (!specs_.dynamic()) + return write(ctx.out(), val, specs_, ctx.locale()); + auto specs = format_specs(specs_); + handle_dynamic_spec(specs.dynamic_width(), specs.width, specs_.width_ref, + ctx); + handle_dynamic_spec(specs.dynamic_precision(), specs.precision, + specs_.precision_ref, ctx); + return write(ctx.out(), val, specs, ctx.locale()); +} + +// DEPRECATED! https://github.com/fmtlib/fmt/issues/4292. +template +struct is_locale : std::false_type {}; +template +struct is_locale> : std::true_type {}; + +// DEPRECATED! +template struct vformat_args { + using type = basic_format_args>; +}; +template <> struct vformat_args { + using type = format_args; +}; + +template +void vformat_to(buffer& buf, basic_string_view fmt, + typename vformat_args::type args, locale_ref loc = {}) { + auto out = basic_appender(buf); + parse_format_string( + fmt, format_handler{parse_context(fmt), {out, args, loc}}); +} +} // namespace detail + +FMT_BEGIN_EXPORT + +// A generic formatting context with custom output iterator and character +// (code unit) support. Char is the format string code unit type which can be +// different from OutputIt::value_type. +template class generic_context { + private: + OutputIt out_; + basic_format_args args_; + detail::locale_ref loc_; + + public: + using char_type = Char; + using iterator = OutputIt; + using parse_context_type FMT_DEPRECATED = parse_context; + template + using formatter_type FMT_DEPRECATED = formatter; + enum { builtin_types = FMT_BUILTIN_TYPES }; + + constexpr generic_context(OutputIt out, + basic_format_args args, + detail::locale_ref loc = {}) + : out_(out), args_(args), loc_(loc) {} + generic_context(generic_context&&) = default; + generic_context(const generic_context&) = delete; + void operator=(const generic_context&) = delete; + + constexpr auto arg(int id) const -> basic_format_arg { + return args_.get(id); + } + auto arg(basic_string_view name) const + -> basic_format_arg { + return args_.get(name); + } + constexpr auto arg_id(basic_string_view name) const -> int { + return args_.get_id(name); + } + + constexpr auto out() const -> iterator { return out_; } + + void advance_to(iterator it) { + if (!detail::is_back_insert_iterator()) out_ = it; + } + + constexpr auto locale() const -> detail::locale_ref { return loc_; } +}; + +class loc_value { + private: + basic_format_arg value_; + + public: + template ::value)> + loc_value(T value) : value_(value) {} + + template ::value)> + loc_value(T) {} + + template auto visit(Visitor&& vis) -> decltype(vis(0)) { + return value_.visit(vis); + } +}; + +// A locale facet that formats values in UTF-8. +// It is parameterized on the locale to avoid the heavy include. +template class format_facet : public Locale::facet { + private: + std::string separator_; + std::string grouping_; + std::string decimal_point_; + + protected: + virtual auto do_put(appender out, loc_value val, + const format_specs& specs) const -> bool; + + public: + static FMT_API typename Locale::id id; + + explicit format_facet(Locale& loc); + explicit format_facet(string_view sep = "", std::string grouping = "\3", + std::string decimal_point = ".") + : separator_(sep.data(), sep.size()), + grouping_(grouping), + decimal_point_(decimal_point) {} + + auto put(appender out, loc_value val, const format_specs& specs) const + -> bool { + return do_put(out, val, specs); + } +}; + +#define FMT_FORMAT_AS(Type, Base) \ + template \ + struct formatter : formatter { \ + template \ + FMT_CONSTEXPR auto format(Type value, FormatContext& ctx) const \ + -> decltype(ctx.out()) { \ + return formatter::format(value, ctx); \ + } \ + } + +FMT_FORMAT_AS(signed char, int); +FMT_FORMAT_AS(unsigned char, unsigned); +FMT_FORMAT_AS(short, int); +FMT_FORMAT_AS(unsigned short, unsigned); +FMT_FORMAT_AS(long, detail::long_type); +FMT_FORMAT_AS(unsigned long, detail::ulong_type); +FMT_FORMAT_AS(Char*, const Char*); +FMT_FORMAT_AS(detail::std_string_view, basic_string_view); +FMT_FORMAT_AS(std::nullptr_t, const void*); +FMT_FORMAT_AS(void*, const void*); + +template +struct formatter : formatter, Char> {}; + +template +class formatter, Char> + : public formatter, Char> {}; + +template +struct formatter, Char> : formatter {}; +template +struct formatter, Char> + : formatter {}; + +template +struct formatter + : detail::native_formatter {}; + +template +struct formatter>> + : formatter, Char> { + template + FMT_CONSTEXPR auto format(const T& value, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto&& val = format_as(value); // Make an lvalue reference for format. + return formatter, Char>::format(val, ctx); + } +}; + +/** + * Converts `p` to `const void*` for pointer formatting. + * + * **Example**: + * + * auto s = fmt::format("{}", fmt::ptr(p)); + */ +template auto ptr(T p) -> const void* { + static_assert(std::is_pointer::value, ""); + return detail::bit_cast(p); +} + +/** + * Converts `e` to the underlying type. + * + * **Example**: + * + * enum class color { red, green, blue }; + * auto s = fmt::format("{}", fmt::underlying(color::red)); // s == "0" + */ +template +constexpr auto underlying(Enum e) noexcept -> underlying_t { + return static_cast>(e); +} + +namespace enums { +template ::value)> +constexpr auto format_as(Enum e) noexcept -> underlying_t { + return static_cast>(e); +} +} // namespace enums + +#ifdef __cpp_lib_byte +template <> struct formatter : formatter { + static auto format_as(std::byte b) -> unsigned char { + return static_cast(b); + } + template + auto format(std::byte b, Context& ctx) const -> decltype(ctx.out()) { + return formatter::format(format_as(b), ctx); + } +}; +#endif + +struct bytes { + string_view data; + + inline explicit bytes(string_view s) : data(s) {} +}; + +template <> struct formatter { + private: + detail::dynamic_format_specs<> specs_; + + public: + FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* { + return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, + detail::type::string_type); + } + + template + auto format(bytes b, FormatContext& ctx) const -> decltype(ctx.out()) { + auto specs = specs_; + detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, + specs.width_ref, ctx); + detail::handle_dynamic_spec(specs.dynamic_precision(), specs.precision, + specs.precision_ref, ctx); + return detail::write_bytes(ctx.out(), b.data, specs); + } +}; + +// group_digits_view is not derived from view because it copies the argument. +template struct group_digits_view { + T value; +}; + +/** + * Returns a view that formats an integer value using ',' as a + * locale-independent thousands separator. + * + * **Example**: + * + * fmt::print("{}", fmt::group_digits(12345)); + * // Output: "12,345" + */ +template auto group_digits(T value) -> group_digits_view { + return {value}; +} + +template struct formatter> : formatter { + private: + detail::dynamic_format_specs<> specs_; + + public: + FMT_CONSTEXPR auto parse(parse_context<>& ctx) -> const char* { + return parse_format_specs(ctx.begin(), ctx.end(), specs_, ctx, + detail::type::int_type); + } + + template + auto format(group_digits_view view, FormatContext& ctx) const + -> decltype(ctx.out()) { + auto specs = specs_; + detail::handle_dynamic_spec(specs.dynamic_width(), specs.width, + specs.width_ref, ctx); + detail::handle_dynamic_spec(specs.dynamic_precision(), specs.precision, + specs.precision_ref, ctx); + auto arg = detail::make_write_int_arg(view.value, specs.sign()); + return detail::write_int( + ctx.out(), static_cast>(arg.abs_value), + arg.prefix, specs, detail::digit_grouping("\3", ",")); + } +}; + +template struct nested_view { + const formatter* fmt; + const T* value; +}; + +template +struct formatter, Char> { + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + return ctx.begin(); + } + template + auto format(nested_view view, FormatContext& ctx) const + -> decltype(ctx.out()) { + return view.fmt->format(*view.value, ctx); + } +}; + +template struct nested_formatter { + private: + basic_specs specs_; + int width_; + formatter formatter_; + + public: + constexpr nested_formatter() : width_(0) {} + + FMT_CONSTEXPR auto parse(parse_context& ctx) -> const Char* { + auto it = ctx.begin(), end = ctx.end(); + if (it == end) return it; + auto specs = format_specs(); + it = detail::parse_align(it, end, specs); + specs_ = specs; + Char c = *it; + auto width_ref = detail::arg_ref(); + if ((c >= '0' && c <= '9') || c == '{') { + it = detail::parse_width(it, end, specs, width_ref, ctx); + width_ = specs.width; + } + ctx.advance_to(it); + return formatter_.parse(ctx); + } + + template + auto write_padded(FormatContext& ctx, F write) const -> decltype(ctx.out()) { + if (width_ == 0) return write(ctx.out()); + auto buf = basic_memory_buffer(); + write(basic_appender(buf)); + auto specs = format_specs(); + specs.width = width_; + specs.copy_fill_from(specs_); + specs.set_align(specs_.align()); + return detail::write( + ctx.out(), basic_string_view(buf.data(), buf.size()), specs); + } + + auto nested(const T& value) const -> nested_view { + return nested_view{&formatter_, &value}; + } +}; + +inline namespace literals { +#if FMT_USE_NONTYPE_TEMPLATE_ARGS +template constexpr auto operator""_a() { + using char_t = remove_cvref_t; + return detail::udl_arg(); +} +#else +/** + * User-defined literal equivalent of `fmt::arg`. + * + * **Example**: + * + * using namespace fmt::literals; + * fmt::print("The answer is {answer}.", "answer"_a=42); + */ +constexpr auto operator""_a(const char* s, size_t) -> detail::udl_arg { + return {s}; +} +#endif // FMT_USE_NONTYPE_TEMPLATE_ARGS +} // namespace literals + +/// A fast integer formatter. +class format_int { + private: + // Buffer should be large enough to hold all digits (digits10 + 1), + // a sign and a null character. + enum { buffer_size = std::numeric_limits::digits10 + 3 }; + mutable char buffer_[buffer_size]; + char* str_; + + template + FMT_CONSTEXPR20 auto format_unsigned(UInt value) -> char* { + auto n = static_cast>(value); + return detail::do_format_decimal(buffer_, n, buffer_size - 1); + } + + template + FMT_CONSTEXPR20 auto format_signed(Int value) -> char* { + auto abs_value = static_cast>(value); + bool negative = value < 0; + if (negative) abs_value = 0 - abs_value; + auto begin = format_unsigned(abs_value); + if (negative) *--begin = '-'; + return begin; + } + + public: + FMT_CONSTEXPR20 explicit format_int(int value) : str_(format_signed(value)) {} + FMT_CONSTEXPR20 explicit format_int(long value) + : str_(format_signed(value)) {} + FMT_CONSTEXPR20 explicit format_int(long long value) + : str_(format_signed(value)) {} + FMT_CONSTEXPR20 explicit format_int(unsigned value) + : str_(format_unsigned(value)) {} + FMT_CONSTEXPR20 explicit format_int(unsigned long value) + : str_(format_unsigned(value)) {} + FMT_CONSTEXPR20 explicit format_int(unsigned long long value) + : str_(format_unsigned(value)) {} + + /// Returns the number of characters written to the output buffer. + FMT_CONSTEXPR20 auto size() const -> size_t { + return detail::to_unsigned(buffer_ - str_ + buffer_size - 1); + } + + /// Returns a pointer to the output buffer content. No terminating null + /// character is appended. + FMT_CONSTEXPR20 auto data() const -> const char* { return str_; } + + /// Returns a pointer to the output buffer content with terminating null + /// character appended. + FMT_CONSTEXPR20 auto c_str() const -> const char* { + buffer_[buffer_size - 1] = '\0'; + return str_; + } + + /// Returns the content of the output buffer as an `std::string`. + inline auto str() const -> std::string { return {str_, size()}; } +}; + +#define FMT_STRING_IMPL(s, base) \ + [] { \ + /* Use the hidden visibility as a workaround for a GCC bug (#1973). */ \ + /* Use a macro-like name to avoid shadowing warnings. */ \ + struct FMT_VISIBILITY("hidden") FMT_COMPILE_STRING : base { \ + using char_type = fmt::remove_cvref_t; \ + constexpr explicit operator fmt::basic_string_view() const { \ + return fmt::detail::compile_string_to_view(s); \ + } \ + }; \ + using FMT_STRING_VIEW = \ + fmt::basic_string_view; \ + fmt::detail::ignore_unused(FMT_STRING_VIEW(FMT_COMPILE_STRING())); \ + return FMT_COMPILE_STRING(); \ + }() + +/** + * Constructs a legacy compile-time format string from a string literal `s`. + * + * **Example**: + * + * // A compile-time error because 'd' is an invalid specifier for strings. + * std::string s = fmt::format(FMT_STRING("{:d}"), "foo"); + */ +#define FMT_STRING(s) FMT_STRING_IMPL(s, fmt::detail::compile_string) + +FMT_API auto vsystem_error(int error_code, string_view fmt, format_args args) + -> std::system_error; + +/** + * Constructs `std::system_error` with a message formatted with + * `fmt::format(fmt, args...)`. + * `error_code` is a system error code as given by `errno`. + * + * **Example**: + * + * // This throws std::system_error with the description + * // cannot open file 'madeup': No such file or directory + * // or similar (system message may vary). + * const char* filename = "madeup"; + * FILE* file = fopen(filename, "r"); + * if (!file) + * throw fmt::system_error(errno, "cannot open file '{}'", filename); + */ +template +auto system_error(int error_code, format_string fmt, T&&... args) + -> std::system_error { + return vsystem_error(error_code, fmt.str, vargs{{args...}}); +} + +/** + * Formats an error message for an error returned by an operating system or a + * language runtime, for example a file opening error, and writes it to `out`. + * The format is the same as the one used by `std::system_error(ec, message)` + * where `ec` is `std::error_code(error_code, std::generic_category())`. + * It is implementation-defined but normally looks like: + * + * : + * + * where `` is the passed message and `` is the system + * message corresponding to the error code. + * `error_code` is a system error code as given by `errno`. + */ +FMT_API void format_system_error(detail::buffer& out, int error_code, + const char* message) noexcept; + +// Reports a system error without throwing an exception. +// Can be used to report errors from destructors. +FMT_API void report_system_error(int error_code, const char* message) noexcept; + +template ::value)> +inline auto vformat(const Locale& loc, string_view fmt, format_args args) + -> std::string { + auto buf = memory_buffer(); + detail::vformat_to(buf, fmt, args, detail::locale_ref(loc)); + return {buf.data(), buf.size()}; +} + +template ::value)> +FMT_INLINE auto format(const Locale& loc, format_string fmt, T&&... args) + -> std::string { + return vformat(loc, fmt.str, vargs{{args...}}); +} + +template ::value)> +auto vformat_to(OutputIt out, const Locale& loc, string_view fmt, + format_args args) -> OutputIt { + auto&& buf = detail::get_buffer(out); + detail::vformat_to(buf, fmt, args, detail::locale_ref(loc)); + return detail::get_iterator(buf, out); +} + +template ::value&& + detail::is_locale::value)> +FMT_INLINE auto format_to(OutputIt out, const Locale& loc, + format_string fmt, T&&... args) -> OutputIt { + return fmt::vformat_to(out, loc, fmt.str, vargs{{args...}}); +} + +template ::value)> +FMT_NODISCARD FMT_INLINE auto formatted_size(const Locale& loc, + format_string fmt, + T&&... args) -> size_t { + auto buf = detail::counting_buffer<>(); + detail::vformat_to(buf, fmt.str, vargs{{args...}}, + detail::locale_ref(loc)); + return buf.count(); +} + +FMT_API auto vformat(string_view fmt, format_args args) -> std::string; + +/** + * Formats `args` according to specifications in `fmt` and returns the result + * as a string. + * + * **Example**: + * + * #include + * std::string message = fmt::format("The answer is {}.", 42); + */ +template +FMT_NODISCARD FMT_INLINE auto format(format_string fmt, T&&... args) + -> std::string { + return vformat(fmt.str, vargs{{args...}}); +} + +/** + * Converts `value` to `std::string` using the default format for type `T`. + * + * **Example**: + * + * std::string answer = fmt::to_string(42); + */ +template ::value)> +FMT_NODISCARD auto to_string(T value) -> std::string { + // The buffer should be large enough to store the number including the sign + // or "false" for bool. + char buffer[max_of(detail::digits10() + 2, 5)]; + return {buffer, detail::write(buffer, value)}; +} + +template ::value)> +FMT_NODISCARD auto to_string(const T& value) -> std::string { + return to_string(format_as(value)); +} + +template ::value && + !detail::use_format_as::value)> +FMT_NODISCARD auto to_string(const T& value) -> std::string { + auto buffer = memory_buffer(); + detail::write(appender(buffer), value); + return {buffer.data(), buffer.size()}; +} + +FMT_END_EXPORT +FMT_END_NAMESPACE + +#ifdef FMT_HEADER_ONLY +# define FMT_FUNC inline +# include "format-inl.h" +#endif + +// Restore _LIBCPP_REMOVE_TRANSITIVE_INCLUDES. +#ifdef FMT_REMOVE_TRANSITIVE_INCLUDES +# undef _LIBCPP_REMOVE_TRANSITIVE_INCLUDES +#endif + +#endif // FMT_FORMAT_H_ diff --git a/sdk/samples/common/vas_format.h b/sdk/samples/common/vas_format.h new file mode 100644 index 000000000..f1c809f79 --- /dev/null +++ b/sdk/samples/common/vas_format.h @@ -0,0 +1,114 @@ +#ifndef VAS_FORMAT_H +#define VAS_FORMAT_H + +#include +#include +#include +#include +#include +#ifndef FMT_HEADER_ONLY +#define FMT_HEADER_ONLY +#endif +#include "../asrun/vendor/fmt/format.h" + +namespace vas { + +// These details are pinned to the vendored fmt version. Parse syntax and types +// without rendering dummy values or allocating an output of user-supplied width. +class FormatChecker { + fmt::detail::compile_parse_context context; + const fmt::detail::type *types; + int count; + + void checkDynamic(fmt::arg_id_kind kind, const fmt::detail::arg_ref &ref) { + if (kind == fmt::arg_id_kind::none) return; + if (kind == fmt::arg_id_kind::name) on_error("named arguments are not supported"); + if (ref.index < 0 || ref.index >= count) on_error("argument not found"); + const auto type = types[ref.index]; + if (type != fmt::detail::type::int_type && type != fmt::detail::type::uint_type && + type != fmt::detail::type::long_long_type && type != fmt::detail::type::ulong_long_type) + on_error("width/precision is not integer"); + } +public: + FormatChecker(fmt::string_view text, const fmt::detail::type *types, int count) + : context(text, count, types), types(types), count(count) {} + void on_text(const char *, const char *) {} + int on_arg_id() { return context.next_arg_id(); } + int on_arg_id(int id) { context.check_arg_id(id); return id; } + int on_arg_id(fmt::string_view) { on_error("named arguments are not supported"); return 0; } + void on_replacement_field(int, const char *) {} + const char *on_format_specs(int id, const char *begin, const char *end) { + context.advance_to(begin); + fmt::detail::dynamic_format_specs specs; + const char *result = fmt::detail::parse_format_specs(begin, end, specs, context, types[id]); + // At runtime fmt's base parse_context does not perform consteval checks. + checkDynamic(specs.dynamic_width(), specs.width_ref); + checkDynamic(specs.dynamic_precision(), specs.precision_ref); + return result; + } + void on_error(const char *message) { throw fmt::format_error(message); } +}; + +inline int ValidateFormat(const char *text, asUINT length, const int *ids, asUINT count, + char *error, asUINT capacity, void *param) { + try { + const int stringType = static_cast(param)->GetTypeIdByDecl("string"); + std::vector types; + types.reserve(count); + for (asUINT i = 0; i < count; ++i) { + using fmt::detail::type; + switch (ids[i]) { + case asTYPEID_BOOL: types.push_back(type::bool_type); break; + case asTYPEID_INT8: case asTYPEID_INT16: case asTYPEID_INT32: types.push_back(type::int_type); break; + case asTYPEID_UINT8: case asTYPEID_UINT16: case asTYPEID_UINT32: types.push_back(type::uint_type); break; + case asTYPEID_INT64: types.push_back(type::long_long_type); break; + case asTYPEID_UINT64: types.push_back(type::ulong_long_type); break; + case asTYPEID_FLOAT: types.push_back(type::float_type); break; + case asTYPEID_DOUBLE: types.push_back(type::double_type); break; + default: + if (ids[i] != stringType) throw fmt::format_error("unsupported argument type"); + types.push_back(type::string_type); + } + } + if (text) { + fmt::string_view format(text, length); + FormatChecker checker(format, types.data(), static_cast(count)); + fmt::detail::parse_format_string(format, checker); + } + return asSUCCESS; + } catch (const std::exception &exception) { + if (capacity) { + const size_t size = (std::min)(std::strlen(exception.what()), size_t(capacity - 1)); + std::memcpy(error, exception.what(), size); + error[size] = 0; + } + return asERROR; + } +} + +// Primitive values live inside format_arg; string_view borrows the script's +// string only until the synchronous call completes. Large calls grow safely. +class FormatArguments { + typedef fmt::basic_format_arg Argument; + Argument inlineArgs[16]; + std::vector overflow; + Argument *args; + int count; +public: + explicit FormatArguments(int count) : args(inlineArgs), count(count) { + if (count > 16) { overflow.resize(count); args = overflow.data(); } + } + template void set(int index, T value) { args[index] = Argument(value); } + fmt::format_args view() const { return fmt::format_args(args, count); } + FormatArguments(const FormatArguments &) = delete; + FormatArguments &operator=(const FormatArguments &) = delete; +}; + +inline void FormatTo(fmt::memory_buffer &output, fmt::string_view format, + const FormatArguments &arguments, bool newline) { + fmt::vformat_to(std::back_inserter(output), format, arguments.view()); + if (newline) output.push_back('\n'); +} + +} // namespace vas +#endif diff --git a/sdk/samples/common/vas_preprocessor.h b/sdk/samples/common/vas_preprocessor.h new file mode 100644 index 000000000..b1e183483 --- /dev/null +++ b/sdk/samples/common/vas_preprocessor.h @@ -0,0 +1,487 @@ +#ifndef VAS_PREPROCESSOR_H +#define VAS_PREPROCESSOR_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vas { + +// Tool-layer preprocessing. The embeddable upstream builder remains unchanged. +class Preprocessor { +public: + enum DependencyKind { Quoted, System, Module }; + struct Statistics { uint64_t tokens = 0, expansions = 0, outputBytes = 0, fastSections = 0; } stats; + struct Span { size_t begin, end, original; bool linear; }; + struct Section { + std::string name, raw, output; + int lineOffset = 0; + std::vector rawLines, outputLines; + std::vector spans; + }; + struct Origin { Section *section = nullptr; size_t offset = 0; }; + typedef std::function Loader; + typedef std::function Pragma; +private: + struct Token { std::string_view text; asETokenClass kind; Origin origin; bool linear = true; }; + struct Macro { + bool function = false; + std::vector parameters; + std::vector body; + std::vector slots; + Origin definition; + }; + struct Conditional { bool parent, active, taken, seenElse = false; Origin origin; }; + asIScriptEngine *engine = nullptr; + std::map sections; + std::unordered_map macros; + static constexpr size_t maxTokens = 1000000, maxOutput = 64 * 1024 * 1024; + size_t expansionWork = 0; + + static bool trivia(const Token &token) { return token.kind == asTC_WHITESPACE || token.kind == asTC_COMMENT; } + static size_t next(const std::vector &tokens, size_t i) { + while (i < tokens.size() && trivia(tokens[i])) ++i; + return i; + } + static std::vector lines(const std::string &text) { + std::vector result(1, 0); + for (size_t i = 0; i < text.size(); ++i) if (text[i] == '\n') result.push_back(i + 1); + return result; + } + static void position(const Origin &origin, int &row, int &column) { + const auto &starts = origin.section->rawLines; + size_t line = size_t(std::upper_bound(starts.begin(), starts.end(), origin.offset) - starts.begin() - 1); + row = int(line + 1) + origin.section->lineOffset; + column = int(origin.offset - starts[line] + 1); + } + static std::string location(const Origin &origin) { + int row, column; position(origin, row, column); + return origin.section->name + ":" + std::to_string(row) + ":" + std::to_string(column); + } + [[noreturn]] void fail(const Origin &origin, const std::string &message) { + int row, column; position(origin, row, column); + engine->WriteMessage(origin.section->name.c_str(), row, column, asMSGTYPE_ERROR, message.c_str()); + throw Failure(); + } + struct Failure {}; + std::vector lex(Section §ion) { + std::vector result; + // Most script tokens average more than four bytes; reserve once without + // a second lexer pass. Views borrow the immutable section buffer. + result.reserve((std::min)(section.raw.size() / 4 + 1, size_t(65536))); + for (size_t offset = 0; offset < section.raw.size();) { + asUINT length = 0; + auto kind = engine->ParseToken(section.raw.data() + offset, section.raw.size() - offset, &length); + if (!length) fail({§ion, offset}, "Preprocessor lexer made no progress"); + result.push_back({std::string_view(section.raw.data() + offset, length), kind, {§ion, offset}}); + offset += length; + ++stats.tokens; + if (result.size() > maxTokens) fail({§ion, offset}, "Section exceeds one million preprocessing tokens"); + } + return result; + } + void append(Section §ion, const Token &token) { + if (token.text.size() > maxOutput - section.output.size()) fail(token.origin, "Preprocessed section exceeds 64 MiB"); + size_t begin = section.output.size(); + section.output.append(token.text.data(), token.text.size()); + // Unmodified ranges coalesce: ordinary files need one mapping span, + // rather than a per-byte or per-token source map. + if (!section.spans.empty()) { + Span &last = section.spans.back(); + if (last.end == begin && ((!last.linear && !token.linear && last.original == token.origin.offset) || + (last.linear && token.linear && last.original + (last.end - last.begin) == token.origin.offset))) { + last.end = section.output.size(); return; + } + } + section.spans.push_back({begin, section.output.size(), token.origin.offset, token.linear}); + } + void blank(Section §ion, size_t begin, size_t end) { + if (end - begin > maxOutput - section.output.size()) fail({§ion, begin}, "Preprocessed section exceeds 64 MiB"); + size_t outputBegin = section.output.size(); + for (size_t i = begin; i < end; ++i) section.output.push_back(section.raw[i] == '\n' ? '\n' : ' '); + section.spans.push_back({outputBegin, section.output.size(), begin, true}); + } + static bool same(const Macro &a, const Macro &b) { + if (a.function != b.function || a.parameters != b.parameters || a.body.size() != b.body.size()) return false; + for (size_t i = 0; i < a.body.size(); ++i) if (a.body[i].text != b.body[i].text) return false; + return true; + } + void define(const std::vector &tokens, size_t begin, size_t end) { + begin = next(tokens, begin); + if (begin >= end || tokens[begin].kind != asTC_IDENTIFIER) fail(tokens[begin - 1].origin, "Expected a macro name"); + const Token &name = tokens[begin++]; + Macro macro; macro.definition = name.origin; + // Function macros require the opening parenthesis to touch the name. + if (begin < end && tokens[begin].text == "(" && tokens[begin].origin.offset == name.origin.offset + name.text.size()) { + macro.function = true; ++begin; + begin = next(tokens, begin); + if (begin < end && tokens[begin].text != ")") { + for (;;) { + if (begin >= end || tokens[begin].kind != asTC_IDENTIFIER) fail(name.origin, "Expected a macro parameter name"); + if (std::find(macro.parameters.begin(), macro.parameters.end(), tokens[begin].text) != macro.parameters.end()) + fail(tokens[begin].origin, "Duplicate macro parameter"); + macro.parameters.push_back(tokens[begin++].text); + begin = next(tokens, begin); + if (begin < end && tokens[begin].text == ")") break; + if (begin >= end || tokens[begin].text != ",") fail(name.origin, "Expected ',' or ')' in macro parameters"); + begin = next(tokens, begin + 1); + } + } + if (begin >= end || tokens[begin].text != ")") fail(name.origin, "Unclosed macro parameter list"); + ++begin; + } + for (; begin < end; ++begin) { + if (trivia(tokens[begin]) || tokens[begin].text == "\\") continue; + if (tokens[begin].text == "#" || tokens[begin].text == "##" || tokens[begin].text == "...") + fail(tokens[begin].origin, "Stringizing, token pasting and variadic macros are not supported"); + macro.body.push_back(tokens[begin]); + auto param = tokens[begin].kind == asTC_IDENTIFIER ? std::find(macro.parameters.begin(), macro.parameters.end(), tokens[begin].text) : macro.parameters.end(); + macro.slots.push_back(param == macro.parameters.end() ? -1 : int(param - macro.parameters.begin())); + } + auto existing = macros.find(name.text); + if (existing != macros.end() && !same(existing->second, macro)) + fail(name.origin, "Conflicting macro '" + std::string(name.text) + "'; previous definition at " + location(existing->second.definition)); + if (existing == macros.end()) macros.emplace(name.text, std::move(macro)); + } + std::vector> arguments(const std::vector &tokens, size_t &i, const Origin &origin) { + std::vector> result(1); + int depth = 1; + ++i; + for (; i < tokens.size(); ++i) { + const Token &token = tokens[i]; + if (token.text == "(") ++depth; + if (token.text == ")" && --depth == 0) { ++i; return result; } + // Only a closing parenthesis decrements nesting. + if (token.text == "," && depth == 1) result.emplace_back(); + else result.back().push_back(token); + } + fail(origin, "Unclosed function macro invocation"); + } + std::vector expand(const std::vector &tokens, std::vector &disabled, unsigned depth = 0) { + std::vector result; + result.reserve(tokens.size()); + for (size_t i = 0; i < tokens.size();) { + const Token &token = tokens[i]; + if (token.kind != asTC_IDENTIFIER || !macros.count(token.text) || std::find(disabled.begin(), disabled.end(), token.text) != disabled.end()) { + if (++expansionWork > maxTokens) fail(token.origin, "Macro expansion work limit exceeded"); + result.push_back(token); ++i; continue; + } + auto expanded = expandAt(tokens, i, disabled, depth); + result.insert(result.end(), expanded.begin(), expanded.end()); + } + return result; + } + std::vector expandAt(const std::vector &tokens, size_t &i, std::vector &disabled, unsigned depth) { + const Token &token = tokens[i++]; + if (++expansionWork > maxTokens) fail(token.origin, "Macro expansion work limit exceeded"); + auto found = token.kind == asTC_IDENTIFIER ? macros.find(token.text) : macros.end(); + if (found == macros.end() || std::find(disabled.begin(), disabled.end(), token.text) != disabled.end()) return {token}; + if (depth >= 64) fail(token.origin, "Macro expansion depth exceeds 64"); + const Macro ¯o = found->second; + std::vector> args; + if (macro.function) { + size_t open = next(tokens, i); + if (open >= tokens.size() || tokens[open].text != "(") return {token}; + i = open; + args = arguments(tokens, i, token.origin); + if (macro.parameters.empty() && args.size() == 1 && next(args[0], 0) == args[0].size()) args.clear(); + if (args.size() != macro.parameters.size()) fail(token.origin, "Wrong number of arguments for macro '" + std::string(token.text) + "'"); + } + ++stats.expansions; + std::vector replacement; + replacement.reserve(macro.body.size()); + std::vector expandedArgs(args.size(), false); + for (size_t part = 0; part < macro.body.size(); ++part) { + Token body = macro.body[part]; + if (macro.slots[part] >= 0) { + size_t index = size_t(macro.slots[part]); + if (!expandedArgs[index]) { + bool containsMacro = std::any_of(args[index].begin(), args[index].end(), [this](const Token &item) { return item.kind == asTC_IDENTIFIER && macros.count(item.text); }); + if (containsMacro) args[index] = expand(args[index], disabled, depth + 1); + expandedArgs[index] = true; + } + replacement.insert(replacement.end(), args[index].begin(), args[index].end()); + } else { + body.origin = token.origin; + body.linear = false; + replacement.push_back(body); + } + } + disabled.push_back(token.text); + std::vector output = expand(replacement, disabled, depth + 1); + // An object macro may alias a function macro. Its invocation arguments + // belong to the surrounding stream, not to the replacement body. + size_t last = output.size(); + while (last && trivia(output[last - 1])) --last; + if (!macro.function && last && next(tokens, i) < tokens.size() && tokens[next(tokens, i)].text == "(") { + auto alias = macros.find(output[last - 1].text); + if (alias != macros.end() && alias->second.function && std::find(disabled.begin(), disabled.end(), output[last - 1].text) == disabled.end()) { + size_t end = next(tokens, i); + size_t after = end; arguments(tokens, after, token.origin); + std::vector call(1, output[last - 1]); + call.insert(call.end(), tokens.begin() + end, tokens.begin() + after); + auto aliasDisabled = disabled; aliasDisabled.pop_back(); + auto value = expand(call, aliasDisabled, depth + 1); + output.resize(last - 1); output.insert(output.end(), value.begin(), value.end()); i = after; + } + } + disabled.pop_back(); + return output; + } + class Expression { + const std::vector &tokens; + size_t index = 0; + unsigned nesting = 0; + static int precedence(std::string_view op) { + if (op == "||") return 1; if (op == "&&") return 2; if (op == "|") return 3; + if (op == "^") return 4; if (op == "&") return 5; if (op == "==" || op == "!=") return 6; + if (op == "<" || op == ">" || op == "<=" || op == ">=") return 7; + if (op == "<<" || op == ">>") return 8; if (op == "+" || op == "-") return 9; + if (op == "*" || op == "/" || op == "%") return 10; return 0; + } + bool take(std::string_view text) { if (index < tokens.size() && tokens[index].text == text) { ++index; return true; } return false; } + int64_t primary(bool evaluate) { + struct Guard { + unsigned &depth; + explicit Guard(unsigned &value) : depth(value) { if (++depth > 128) throw std::runtime_error("#if expression nesting exceeds 128"); } + ~Guard() { --depth; } + } guard(nesting); + if (take("!")) return !primary(evaluate); + if (take("~")) return ~primary(evaluate); + if (take("+")) return primary(evaluate); + if (take("-")) return int64_t(uint64_t(0) - uint64_t(primary(evaluate))); + if (take("(")) { int64_t value = binary(1, evaluate); if (!take(")")) throw std::runtime_error("Expected ')' in #if"); return value; } + if (index == tokens.size()) throw std::runtime_error("Missing operand in #if"); + const Token &token = tokens[index++]; + if (token.text == "true") return 1; + if (token.text == "false" || token.kind == asTC_IDENTIFIER) return 0; + std::string text(token.text); size_t end = 0; + text.erase(std::remove(text.begin(), text.end(), '\''), text.end()); + // Match VAS radix prefixes and decimal leading zeros, rather than + // inheriting C's implicit octal interpretation from strtoull(base=0). + int radix = 10; + if (text.size() > 2 && text[0] == '0') { + char prefix = text[1]; + if (prefix == 'x' || prefix == 'X') radix = 16; + else if (prefix == 'b' || prefix == 'B') radix = 2; + else if (prefix == 'o' || prefix == 'O') radix = 8; + else if (prefix == 'd' || prefix == 'D') radix = 10; + if (prefix == 'x' || prefix == 'X' || prefix == 'b' || prefix == 'B' || + prefix == 'o' || prefix == 'O' || prefix == 'd' || prefix == 'D') text.erase(0, 2); + } + uint64_t value; + try { value = std::stoull(text, &end, radix); } catch (...) { throw std::runtime_error("Expected an integer in #if"); } + while (end < text.size() && (text[end] == 'u' || text[end] == 'U' || text[end] == 'l' || text[end] == 'L')) ++end; + if (end != text.size()) throw std::runtime_error("Expected an integer in #if"); + return int64_t(value); + } + int64_t binary(int minimum, bool evaluate) { + int64_t lhs = primary(evaluate); + while (index < tokens.size()) { + auto op = tokens[index].text; int priority = precedence(op); + if (priority < minimum) break; + ++index; + bool rightEval = evaluate && !(op == "&&" && !lhs) && !(op == "||" && lhs); + int64_t rhs = binary(priority + 1, rightEval); + if (!evaluate) { lhs = 0; continue; } + if (op == "&&") lhs = lhs && rhs; else if (op == "||") lhs = lhs || rhs; + else if (op == "+") lhs = int64_t(uint64_t(lhs) + uint64_t(rhs)); + else if (op == "-") lhs = int64_t(uint64_t(lhs) - uint64_t(rhs)); + else if (op == "*") lhs = int64_t(uint64_t(lhs) * uint64_t(rhs)); + else if (op == "/" || op == "%") { + if (!rhs) throw std::runtime_error("Division by zero in #if"); + if (lhs == INT64_MIN && rhs == -1) throw std::runtime_error("Integer division overflow in #if"); + lhs = op == "/" ? lhs / rhs : lhs % rhs; + } else if (op == "<<" || op == ">>") { + if (rhs < 0 || rhs >= 64) throw std::runtime_error("Invalid shift in #if"); + lhs = op == "<<" ? int64_t(uint64_t(lhs) << rhs) : lhs >> rhs; + } else if (op == "==") lhs = lhs == rhs; else if (op == "!=") lhs = lhs != rhs; + else if (op == "<") lhs = lhs < rhs; else if (op == ">") lhs = lhs > rhs; + else if (op == "<=") lhs = lhs <= rhs; else if (op == ">=") lhs = lhs >= rhs; + else if (op == "&") lhs &= rhs; else if (op == "|") lhs |= rhs; else if (op == "^") lhs ^= rhs; + } + return lhs; + } + public: + explicit Expression(const std::vector &tokens) : tokens(tokens) {} + bool value() { int64_t result = binary(1, true); if (index != tokens.size()) throw std::runtime_error("Unexpected token in #if"); return result != 0; } + }; + bool condition(std::vector tokens, const Origin &origin) { + try { + std::vector defined; + for (size_t i = 0; i < tokens.size(); ++i) { + if (trivia(tokens[i])) continue; + Token token = tokens[i]; + if (token.text == "defined") { + i = next(tokens, i + 1); bool parenthesis = i < tokens.size() && tokens[i].text == "("; + if (parenthesis) i = next(tokens, i + 1); + if (i >= tokens.size() || tokens[i].kind != asTC_IDENTIFIER) throw std::runtime_error("Expected a name after defined"); + token.text = macros.count(tokens[i].text) ? "1" : "0"; token.kind = asTC_VALUE; token.linear = false; + if (parenthesis) { i = next(tokens, i + 1); if (i >= tokens.size() || tokens[i].text != ")") throw std::runtime_error("Expected ')' after defined"); } + } + defined.push_back(token); + } + std::vector disabled; + auto expanded = expand(defined, disabled); + expanded.erase(std::remove_if(expanded.begin(), expanded.end(), trivia), expanded.end()); + return Expression(expanded).value(); + } catch (const std::exception &error) { fail(origin, error.what()); } + } + static size_t directiveEnd(const std::vector &tokens, size_t begin) { + size_t end = begin; + for (; end < tokens.size(); ++end) { + if (tokens[end].kind != asTC_WHITESPACE || tokens[end].text.find('\n') == std::string_view::npos) continue; + if (end > begin && tokens[end - 1].text == "\\") continue; + break; + } + return end; + } +public: + bool canSkip(std::string_view code) const { + return macros.empty() && code.find('#') == std::string_view::npos && code.find("import") == std::string_view::npos; + } + void reset(asIScriptEngine *value) { macros.clear(); sections.clear(); stats = {}; expansionWork = 0; engine = value; } + void defineWord(const std::string &name) { + auto §ion = sections[""]; section.name = ""; section.raw = name; section.rawLines = {0}; + Macro macro; macro.definition = {§ion, 0}; macro.body.push_back({"1", asTC_VALUE, macro.definition, false}); macro.slots.push_back(-1); + macros.emplace(std::string_view(section.raw), std::move(macro)); + } + bool process(const std::string &name, const std::string &raw, int lineOffset, const Loader &load, const Pragma &pragma) { + auto §ion = sections[name]; section.name = name; section.raw = raw; section.lineOffset = lineOffset; section.rawLines = lines(raw); section.output.reserve(raw.size()); + if (raw.size() > maxOutput) { engine->WriteMessage(name.c_str(), 0, 0, asMSGTYPE_ERROR, "Source section exceeds 64 MiB"); return false; } + std::vector tokens; + try { tokens = lex(section); } catch (const Failure &) { return false; } + std::vector stack; + int braces = 0; + try { + for (size_t i = 0; i < tokens.size();) { + const Token &token = tokens[i]; + bool active = stack.empty() || stack.back().active; + if (token.text == "#") { + size_t word = next(tokens, i + 1), end = directiveEnd(tokens, word); + if (word >= tokens.size()) { append(section, token); ++i; continue; } + auto directive = tokens[word].text; + size_t arg = next(tokens, word + 1); + if (directive != "include") arg = (std::min)(arg, end); + size_t finish = end < tokens.size() ? tokens[end].origin.offset : raw.size(); + if (directive == "if" || directive == "ifdef" || directive == "ifndef") { + bool value = false; + if (directive != "if") { + if (arg >= end || tokens[arg].kind != asTC_IDENTIFIER || next(tokens, arg + 1) < end) fail(token.origin, "Expected one name in conditional directive"); + value = macros.count(tokens[arg].text) != 0; + if (directive == "ifndef") value = !value; + } else if (active) value = condition(std::vector(tokens.begin() + arg, tokens.begin() + end), token.origin); + if (stack.size() >= 128) fail(token.origin, "Conditional nesting exceeds 128"); + stack.push_back({active, active && value, active && value, false, token.origin}); + } else if (directive == "else" || directive == "elif") { + if (stack.empty() || stack.back().seenElse) fail(token.origin, "Unmatched or duplicate #else/#elif"); + auto &branch = stack.back(); + bool value = directive == "else" || (branch.parent && !branch.taken && condition(std::vector(tokens.begin() + arg, tokens.begin() + end), token.origin)); + branch.active = branch.parent && !branch.taken && value; branch.taken |= branch.active; + if (directive == "else") { branch.seenElse = true; if (arg < end) fail(token.origin, "Unexpected tokens after #else"); } + } else if (directive == "endif") { + if (stack.empty()) fail(token.origin, "Unmatched #endif"); + if (arg < end) fail(token.origin, "Unexpected tokens after #endif"); stack.pop_back(); + } else if (!active) { + // Inactive directives do not resolve files or define macros. + } else if (directive == "define") define(tokens, word + 1, end); + else if (directive == "undef") { + if (arg >= end || tokens[arg].kind != asTC_IDENTIFIER || next(tokens, arg + 1) < end) fail(token.origin, "Expected one name after #undef"); + macros.erase(tokens[arg].text); + } else if (directive == "include") { + // Like the existing builder, include filenames may start + // on a subsequent line; tokens after the filename remain code. + if (arg < tokens.size() && tokens[arg].kind == asTC_VALUE && tokens[arg].text.size() > 2 && (tokens[arg].text[0] == '"' || tokens[arg].text[0] == '\'')) { + std::string path(tokens[arg].text.substr(1, tokens[arg].text.size() - 2)); + if (path.find_first_of("\r\n") != std::string::npos) fail(token.origin, "Newline in include filename"); + if (load(path, Quoted, token.origin) < 0) throw Failure(); + finish = tokens[arg].origin.offset + tokens[arg].text.size(); end = arg + 1; + } else if (arg < tokens.size() && tokens[arg].text == "<") { + size_t close = arg + 1; std::string path; + for (; close < tokens.size() && tokens[close].text != ">"; ++close) { + if (trivia(tokens[close])) fail(token.origin, "Whitespace in angle include filename"); + path.append(tokens[close].text); + } + if (close == tokens.size() || path.empty()) fail(token.origin, "Invalid angle include"); + if (load(path, System, token.origin) < 0) throw Failure(); + finish = tokens[close].origin.offset + 1; end = close + 1; + } else { append(section, token); ++i; continue; } + } else if (directive == "pragma") { + std::string text = arg < end ? std::string(raw.data() + tokens[arg].origin.offset, finish - tokens[arg].origin.offset) : ""; + if (!pragma || pragma(text) < 0) fail(token.origin, "Invalid #pragma directive"); + } else if (directive == "error") { + fail(token.origin, "#error " + std::string(raw.data() + tokens[word].origin.offset + directive.size(), finish - tokens[word].origin.offset - directive.size())); + } else { append(section, token); ++i; continue; } + blank(section, token.origin.offset, finish); i = end; continue; + } + if (!active) { blank(section, token.origin.offset, token.origin.offset + token.text.size()); ++i; } + else if (token.text == "import") { + size_t part = next(tokens, i + 1), end = part; std::string path; + if (part < tokens.size() && tokens[part].kind == asTC_IDENTIFIER) { + path = std::string(tokens[part].text); end = next(tokens, part + 1); + while (end < tokens.size() && tokens[end].text == ".") { + size_t identifier = next(tokens, end + 1); + if (identifier == tokens.size() || tokens[identifier].kind != asTC_IDENTIFIER) break; + path += "/"; path.append(tokens[identifier].text); end = next(tokens, identifier + 1); + } + } + if (!path.empty() && end < tokens.size() && tokens[end].text == ";") { + if (braces) fail(token.origin, "Module imports must be at file scope"); + if (load(path + ".vas", Module, token.origin) < 0) throw Failure(); + blank(section, token.origin.offset, tokens[end].origin.offset + 1); i = end + 1; + } else { append(section, token); ++i; } + } else { + auto found = token.kind == asTC_IDENTIFIER ? macros.find(token.text) : macros.end(); + if (found == macros.end()) { append(section, token); ++i; if (token.text == "{") ++braces; if (token.text == "}") --braces; } + else { + std::vector disabled; + auto expanded = expandAt(tokens, i, disabled, 0); + size_t endOffset = tokens[i - 1].origin.offset + tokens[i - 1].text.size(); + size_t newlines = size_t(std::count(raw.begin() + token.origin.offset, raw.begin() + endOffset, '\n')); + // Separators prevent adjacent expansions from accidentally + // forming a different lexer token (e.g. '+' then '+'). + Token space{" ", asTC_WHITESPACE, token.origin, false}; append(section, space); + for (auto value : expanded) { + if (trivia(value)) continue; + if (value.text.find('\n') != std::string_view::npos) + fail(token.origin, "Use escaped \\n instead of physical newlines in macro literals"); + if (value.origin.section != §ion) value.origin = token.origin; + value.linear = false; append(section, value); append(section, space); + if (value.text == "{") ++braces; if (value.text == "}") --braces; + } + Token newline{"\n", asTC_WHITESPACE, token.origin, false}; + for (size_t line = 0; line < newlines; ++line) append(section, newline); + } + } + } + if (!stack.empty()) fail(stack.back().origin, "Unclosed conditional directive"); + section.outputLines = lines(section.output); stats.outputBytes += section.output.size(); + return true; + } catch (const Failure &) { return false; } + } + const std::string &output(const std::string &name) const { return sections.at(name).output; } + void remap(asSMessageInfo &message) const { + auto found = sections.find(message.section ? message.section : ""); + if (found == sections.end() || message.row <= found->second.lineOffset || message.col <= 0) return; + const Section §ion = found->second; + if (section.outputLines.empty()) return; // preprocessing diagnostics are already original + size_t line = size_t(message.row - section.lineOffset - 1); + if (line >= section.outputLines.size()) return; + size_t offset = section.outputLines[line] + size_t(message.col - 1); + auto span = std::upper_bound(section.spans.begin(), section.spans.end(), offset, + [](size_t value, const Span &item) { return value < item.begin; }); + if (span == section.spans.begin()) return; --span; + if (offset > span->end) return; + Origin origin{const_cast
(§ion), span->original + (span->linear ? offset - span->begin : 0)}; + position(origin, message.row, message.col); + } +}; +} +#endif diff --git a/sdk/samples/common/vas_scriptbuilder.h b/sdk/samples/common/vas_scriptbuilder.h index 8b17bf520..a2f9783ae 100644 --- a/sdk/samples/common/vas_scriptbuilder.h +++ b/sdk/samples/common/vas_scriptbuilder.h @@ -3,7 +3,10 @@ #include "../../add_on/scriptbuilder/scriptbuilder.h" #include "vas_paths.h" +#include "vas_preprocessor.h" #include +#include +#include #ifdef _WIN32 #include #else @@ -40,6 +43,63 @@ class ScriptBuilder : public CScriptBuilder public: typedef void (*SectionLoadedCallback)(const std::string §ion, const std::string &code, bool regularFile, void *param); ScriptBuilder() : loadedCallback(0), loadedParam(0), inspectFileType(false) {} + ~ScriptBuilder() + { + if (diagnosticCallback && GetEngine()) + GetEngine()->SetMessageCallback(asFUNCTION(diagnosticCallback), diagnosticParam, asCALL_CDECL); + } + int StartNewModule(asIScriptEngine *value, const char *name) + { + int result = CScriptBuilder::StartNewModule(value, name); + preprocessor.reset(value); + for (const auto &word : definedWords) preprocessor.defineWord(word); + seen.clear(); normalized.clear(); resolutions.clear(); searchPaths.clear(); + rootsInitialized = false; fileReads = 0; loadDepth = 0; dependencyKind = Preprocessor::Quoted; + return result; + } + void DefineWord(const char *word) + { + CScriptBuilder::DefineWord(word); + if (GetEngine()) preprocessor.defineWord(word); + } + void SetMappedMessageCallback(void (*callback)(const asSMessageInfo *, void *), void *param) + { + diagnosticCallback = callback; diagnosticParam = param; + GetEngine()->SetMessageCallback(asMETHOD(ScriptBuilder, MappedMessage), this, asCALL_THISCALL); + } + uint64_t GetFileReadCount() const { return fileReads; } + const Preprocessor::Statistics &GetPreprocessingStatistics() const { return preprocessor.stats; } + void AddSearchPath(const std::string &path) { configuredPaths.push_back(path); resolutions.clear(); rootsInitialized = false; } + Preprocessor::DependencyKind GetDependencyKind() const { return dependencyKind; } + const std::string &GetResolutionError() const { return resolutionError; } + std::string ResolveDependency(const char *requested, const char *from) + { + std::string path = requested ? requested : "", parent = from ? from : ""; + parent.resize(parent.find_last_of("/\\") == std::string::npos ? 0 : parent.find_last_of("/\\") + 1); + std::string key = std::to_string(int(dependencyKind)) + "|" + parent + "|" + path; + resolutionError.clear(); + auto cached = resolutions.find(key); + if (cached != resolutions.end()) return cached->second; + if (path.empty()) return path; + if (path[0] == '/' || path[0] == '\\' || path.find(':') != std::string::npos) return Normalize(path); + std::string local = Normalize(parent + path); + if (dependencyKind != Preprocessor::System && (Exists(local) || path.size() < 4 || path.substr(path.size() - 4) != ".vas")) + return resolutions.emplace(key, local).first->second; + std::string result; + for (const auto &root : searchPaths) + { + std::string candidate = Normalize(root + "/" + path); + if (!Exists(candidate)) continue; + if (!result.empty() && Identity(result) != Identity(candidate)) + { + resolutionError = "Ambiguous module/include '" + path + "': '" + result + "' and '" + candidate + "'"; + return ""; + } + result = candidate; + } + if (result.empty()) result = dependencyKind == Preprocessor::System && !searchPaths.empty() ? Normalize(searchPaths[0] + "/" + path) : local; + return resolutions.emplace(key, result).first->second; + } void SetSectionLoadedCallback(SectionLoadedCallback callback, void *param, bool inspectType = false) { loadedCallback = callback; @@ -50,7 +110,8 @@ class ScriptBuilder : public CScriptBuilder int AddSectionFromFile(const char *filename) { std::string section; - if( !ScriptSectionPath(filename, section) ) + section = Normalize(filename ? filename : ""); + if( section.empty() ) { GetEngine()->WriteMessage(filename, 0, 0, asMSGTYPE_ERROR, "Failed to resolve script path"); return -1; @@ -58,10 +119,12 @@ class ScriptBuilder : public CScriptBuilder // Use the builder's own comparison rules and skip before reading again. // AddSectionFromMemory records the name before processing nested includes, // so repeated includes and cycles remain include-once. - if( includedScripts.find(section) != includedScripts.end() ) return 0; + if (seen.count(Identity(section))) return 0; + if (!rootsInitialized) InitializeRoots(section); FILE *file = OpenFile(section.c_str(), "rb"); if( file == 0 ) return ReportFileError(section, "Failed to open script file '"); + ++fileReads; // Classify the opened handle, not a path that may have been replaced. // Unknown or non-file streams retain load events but provide no digest. // Only report mode requests this probe; ordinary tools keep the original @@ -79,6 +142,18 @@ class ScriptBuilder : public CScriptBuilder } std::string code; + // Reserve from the opened handle; keep chunked reads and EOF/error checks + // so a concurrent size change cannot truncate the actual loaded bytes. +#ifdef _WIN32 + LARGE_INTEGER sizeHint; + HANDLE sizeHandle = reinterpret_cast(_get_osfhandle(_fileno(file))); + if (GetFileSizeEx(sizeHandle, &sizeHint) && sizeHint.QuadPart > 0) + code.reserve(static_cast((std::min)(sizeHint.QuadPart, LONGLONG(64 * 1024 * 1024)))); +#else + struct stat sizeHint; + if (fstat(fileno(file), &sizeHint) == 0 && sizeHint.st_size > 0) + code.reserve(static_cast((std::min)(sizeHint.st_size, off_t(64 * 1024 * 1024)))); +#endif char buffer[4096]; size_t count; bool tooLarge = false; @@ -101,8 +176,117 @@ class ScriptBuilder : public CScriptBuilder if( loadedCallback ) loadedCallback(section, code, regularFile, loadedParam); return AddSectionFromMemory(section.c_str(), code.c_str(), static_cast(code.size())); } + int AddSectionFromMemory(const char *sectionName, const char *code, unsigned length = 0, int lineOffset = 0) + { + const std::string name(sectionName); + if (!seen.insert(Identity(name)).second) return 0; + IncludeIfNotAlreadyIncluded(sectionName); + if (++loadDepth > 128) { --loadDepth; return ReportFileError(name, "Import/include nesting exceeds 128 in '"); } + size_t size = length ? length : std::strlen(code); + if (preprocessor.canSkip(std::string_view(code, size))) + { + ++preprocessor.stats.fastSections; preprocessor.stats.outputBytes += size; --loadDepth; + return ProcessScriptSection(code, static_cast(size), sectionName, lineOffset) < 0 ? -1 : 1; + } + bool accepted = preprocessor.process(name, std::string(code, size), lineOffset, + [this](const std::string &path, Preprocessor::DependencyKind kind, const Preprocessor::Origin &origin) + { + auto previous = dependencyKind; dependencyKind = kind; + int result; + if (includeCallback) result = includeCallback(path.c_str(), origin.section->name.c_str(), this, includeParam); + else { + std::string resolved = ResolveDependency(path.c_str(), origin.section->name.c_str()); + if (resolved.empty() && !resolutionError.empty()) { + GetEngine()->WriteMessage(origin.section->name.c_str(), 0, 0, asMSGTYPE_ERROR, resolutionError.c_str()); + result = -1; + } else result = AddSectionFromFile(resolved.c_str()); + } + dependencyKind = previous; + return result; + }, [this](const std::string &text) { return pragmaCallback ? pragmaCallback(text, *this, pragmaParam) : -1; }); + --loadDepth; + if (!accepted) return -1; + const auto &output = preprocessor.output(name); + return ProcessScriptSection(output.c_str(), static_cast(output.size()), sectionName, lineOffset) < 0 ? -1 : 1; + } private: + Preprocessor preprocessor; + std::unordered_set seen; + std::unordered_map normalized, resolutions; + std::vector configuredPaths, searchPaths; + std::string resolutionError; + bool rootsInitialized = false; + unsigned loadDepth = 0; + uint64_t fileReads = 0; + Preprocessor::DependencyKind dependencyKind = Preprocessor::Quoted; + void (*diagnosticCallback)(const asSMessageInfo *, void *) = nullptr; + void *diagnosticParam = nullptr; + void MappedMessage(const asSMessageInfo *message) + { + asSMessageInfo mapped = *message; + preprocessor.remap(mapped); + diagnosticCallback(&mapped, diagnosticParam); + } + static std::string Identity(std::string path) + { +#ifdef _WIN32 + for (char &c : path) if (c >= 'A' && c <= 'Z') c += 'a' - 'A'; +#endif + return path; + } + std::string Normalize(const std::string &path) + { + auto found = normalized.find(path); + if (found != normalized.end()) return found->second; + std::string result; + if (!ScriptSectionPath(path.c_str(), result)) return ""; + return normalized.emplace(path, result).first->second; + } + static bool Exists(const std::string &path) + { +#ifdef _WIN32 + std::wstring native; + if (!ToWide(path.c_str(), native)) return false; + DWORD attributes = GetFileAttributesW(native.c_str()); + return attributes != INVALID_FILE_ATTRIBUTES && !(attributes & FILE_ATTRIBUTE_DIRECTORY); +#else + struct stat info; + return stat(path.c_str(), &info) == 0 && !S_ISDIR(info.st_mode); +#endif + } + void InitializeRoots(const std::string &entry) + { + std::string directory = entry.substr(0, entry.find_last_of('/')); + searchPaths = {directory}; + for (const auto &path : configuredPaths) searchPaths.push_back(Normalize(path)); + std::string environment; +#ifdef _WIN32 + DWORD length = GetEnvironmentVariableW(L"VAS_INCLUDE_PATH", nullptr, 0); + if (length) + { + std::vector buffer(length); + DWORD count = GetEnvironmentVariableW(L"VAS_INCLUDE_PATH", buffer.data(), length); + if (count && count < length) ToUtf8(buffer.data(), environment); + } + const char separator = ';'; +#else + if (const char *value = std::getenv("VAS_INCLUDE_PATH")) environment = value; + const char separator = ':'; +#endif + for (size_t begin = 0; begin < environment.size();) + { + size_t end = environment.find(separator, begin); + std::string path = environment.substr(begin, end - begin); + if (!path.empty()) + { + bool absolute = path[0] == '/' || path[0] == '\\' || path.find(':') != std::string::npos; + searchPaths.push_back(Normalize(absolute ? path : directory + "/" + path)); + } + if (end == std::string::npos) break; begin = end + 1; + } + rootsInitialized = true; + } SectionLoadedCallback loadedCallback; void *loadedParam; bool inspectFileType; diff --git a/templates/rider/vas-starter/.vas/bin/vasbuild.exe b/templates/rider/vas-starter/.vas/bin/vasbuild.exe index e65ecad42..192fbfeb8 100644 Binary files a/templates/rider/vas-starter/.vas/bin/vasbuild.exe and b/templates/rider/vas-starter/.vas/bin/vasbuild.exe differ diff --git a/templates/rider/vas-starter/.vas/bin/vasrun.exe b/templates/rider/vas-starter/.vas/bin/vasrun.exe index 236c619f9..38c3e6097 100644 Binary files a/templates/rider/vas-starter/.vas/bin/vasrun.exe and b/templates/rider/vas-starter/.vas/bin/vasrun.exe differ diff --git a/templates/rider/vas-starter/.vas/vasbuild.config.txt b/templates/rider/vas-starter/.vas/vasbuild.config.txt index bce3a74af..49761ab26 100644 --- a/templates/rider/vas-starter/.vas/vasbuild.config.txt +++ b/templates/rider/vas-starter/.vas/vasbuild.config.txt @@ -82,8 +82,6 @@ objmthd "array" "int findByRef(uint, const T&in) const" objmthd "array" "bool opEquals(const array&in) const" objmthd "array" "bool isEmpty() const" objmthd "array" "void sort(array::less&in, uint = 0, uint = uint ( - 1 ))" -objmthd "array" "uint get_length() const" -objmthd "array" "void set_length(uint)" // Type members objbeh "string" 2 "void string()" @@ -96,8 +94,6 @@ objmthd "string" "int opCmp(const string&in) const" objmthd "string" "string opAdd(const string&in) const" objmthd "string" "uint length() const" objmthd "string" "void resize(uint)" -objmthd "string" "uint get_length() const" -objmthd "string" "void set_length(uint)" objmthd "string" "bool isEmpty() const" objmthd "string" "uint8& opIndex(uint)" objmthd "string" "const uint8& opIndex(uint) const" @@ -214,7 +210,31 @@ func "int64 parseInt(const string&in, uint = 10, uint&out = 0)" func "uint64 parseUInt(const string&in, uint = 10, uint&out = 0)" func "double parseFloat(const string&in, uint&out = 0)" func "string join(const array&in, const string&in)" -func "void print(const string&in)" +formatfunc "void print(const string&in format, const ?&in ...)" +func "void print(int8)" +func "void print(uint8)" +func "void print(int16)" +func "void print(uint16)" +func "void print(int)" +func "void print(uint)" +func "void print(int64)" +func "void print(uint64)" +func "void print(float)" +func "void print(double)" +func "void print(bool)" +formatfunc "void println(const string&in format, const ?&in ...)" +func "void println()" +func "void println(int8)" +func "void println(uint8)" +func "void println(int16)" +func "void println(uint16)" +func "void println(int)" +func "void println(uint)" +func "void println(int64)" +func "void println(uint64)" +func "void println(float)" +func "void println(double)" +func "void println(bool)" func "string getInput()" func "array@ getCommandLineArgs()" func "int exec(const string&in)" diff --git a/tests/vasbuild/assert_arena.cmake b/tests/vasbuild/assert_arena.cmake new file mode 100644 index 000000000..4f219e716 --- /dev/null +++ b/tests/vasbuild/assert_arena.cmake @@ -0,0 +1,70 @@ +cmake_minimum_required(VERSION 3.21) +file(MAKE_DIRECTORY "${TEST_ROOT}") +set(entry "${SOURCE_ROOT}/examples/arena/main.vas") +set(config "${SOURCE_ROOT}/sdk/samples/asbuild/bin/config.txt") +# This uses arrays, strings and script classes: the same source must compile +# against each shipped API config AND run against the actual registered host. +foreach(host IN ITEMS "sdk/samples/asbuild/bin/config.txt" + "App1/.vas/vasbuild.config.txt" "templates/rider/vas-starter/.vas/vasbuild.config.txt" + "tools/rider-plugin/src/main/resources/runtime/windows-x64/vasbuild.config.txt") + execute_process(COMMAND "${VASBUILD}" "${SOURCE_ROOT}/${host}" "${entry}" "${TEST_ROOT}/arena.vasbc" + RESULT_VARIABLE status OUTPUT_VARIABLE out ERROR_VARIABLE err ENCODING UTF-8 TIMEOUT 20) + if(NOT status EQUAL 0) + message(FATAL_ERROR "Arena failed to compile against ${host}\n${out}\n${err}") + endif() +endforeach() +function(run expected_status expected) + execute_process(COMMAND "${VASRUN}" "${entry}" ${ARGN} + RESULT_VARIABLE status OUTPUT_VARIABLE out ERROR_VARIABLE err ENCODING UTF-8 TIMEOUT 20) + string(REPLACE "\r\n" "\n" out "${out}") + if(NOT status EQUAL expected_status OR NOT out STREQUAL expected) + message(FATAL_ERROR "Arena runtime mismatch for ${ARGN} (${status})\nExpected:\n${expected}\nActual:\n${out}\n${err}") + endif() +endfunction() +file(READ "${SOURCE_ROOT}/examples/arena/expected-quiet.txt" quiet) +string(REPLACE "\r\n" "\n" quiet "${quiet}") +run(0 "${quiet}" --quiet) +run(0 "SELF_TEST passed=23 failed=0\n" --self-test) +set(batch "BATCH count=2000 wins=654 losses=1346 draws=0 checksum=9933226\n") +run(0 "${batch}" --batch 2000) +run(0 "BATCH count=1 wins=0 losses=1 draws=0 checksum=16\n" --batch 1) +set(usage "用法:vasrun main.vas [--quiet | --self-test | --batch 1..100000]\n") +foreach(count IN ITEMS 0 -1 100001 2oops "") + run(2 "${usage}" --batch "${count}") +endforeach() +run(2 "${usage}" --unknown) +run(2 "${usage}" --batch) + +# All imported source files must remain in the native dependency report. +execute_process(COMMAND "${VASBUILD}" --report=jsonl "${config}" "${entry}" "${TEST_ROOT}/arena.vasbc" + RESULT_VARIABLE status OUTPUT_VARIABLE report ERROR_VARIABLE err ENCODING UTF-8 TIMEOUT 20) +string(REGEX MATCHALL "\"type\":\"section_loaded\"" sections "${report}") +list(LENGTH sections count) +if(NOT status EQUAL 0 OR NOT count EQUAL 9 OR NOT report MATCHES "\"dependenciesComplete\":true") + message(FATAL_ERROR "Arena dependency closure changed\n${report}\n${err}") +endif() + +set(ENV{VAS_INCLUDE_PATH} "${SOURCE_ROOT}/examples/arena") +# Compile-time logging elimination must not change simulation state or RNG use. +file(WRITE "${TEST_ROOT}/silent.vas" "#define VAS_ARENA_VERBOSE 0\n#include \"${entry}\"\n") +execute_process(COMMAND "${VASBUILD}" "${config}" "${TEST_ROOT}/silent.vas" "${TEST_ROOT}/silent.vasbc" + RESULT_VARIABLE status OUTPUT_VARIABLE out ERROR_VARIABLE err ENCODING UTF-8 TIMEOUT 20) +if(NOT status EQUAL 0) + message(FATAL_ERROR "Logging-off variant compilation failed\n${out}\n${err}") +endif() +execute_process(COMMAND "${VASRUN}" "${TEST_ROOT}/silent.vas" --batch 2000 + RESULT_VARIABLE status OUTPUT_VARIABLE out ERROR_VARIABLE err ENCODING UTF-8 TIMEOUT 20) +string(REPLACE "\r\n" "\n" out "${out}") +if(NOT status EQUAL 0 OR NOT out STREQUAL batch) + message(FATAL_ERROR "Logging-off variant changed combat results\n${out}\n${err}") +endif() + +# Deliberately change configuration without editing the executable example. +foreach(override IN ITEMS "VAS_ARENA_MAX_ROUNDS 0" "VAS_ARENA_VERBOSE 2") + file(WRITE "${TEST_ROOT}/invalid.vas" "#define ${override}\n#include \"${entry}\"\n") + execute_process(COMMAND "${VASBUILD}" "${config}" "${TEST_ROOT}/invalid.vas" "${TEST_ROOT}/invalid.vasbc" + RESULT_VARIABLE status OUTPUT_VARIABLE out ERROR_VARIABLE err ENCODING UTF-8 TIMEOUT 20) + if(status EQUAL 0 OR NOT "${out}${err}" MATCHES "#error") + message(FATAL_ERROR "Invalid arena configuration was not rejected\n${out}\n${err}") + endif() +endforeach() diff --git a/tests/vasbuild/assert_modules.cmake b/tests/vasbuild/assert_modules.cmake new file mode 100644 index 000000000..2af1a1b1d --- /dev/null +++ b/tests/vasbuild/assert_modules.cmake @@ -0,0 +1,146 @@ +cmake_minimum_required(VERSION 3.21) +file(MAKE_DIRECTORY "${TEST_ROOT}/pkg" "${TEST_ROOT}/search-a" "${TEST_ROOT}/search-b") +file(WRITE "${TEST_ROOT}/constants.vas" "#define BASE 10\n#define LABEL \"math\"\n") +file(WRITE "${TEST_ROOT}/math.vas" "import constants;\n#define SUM(a,b) ((a)+(b))\n#define ALIAS SUM\nint add(int a,int b){ return a+b; }\n") +file(WRITE "${TEST_ROOT}/pkg/tool.vas" "#define TOOL_VERSION 2\nint tool(){return 9;}\n") +set(config "${SOURCE_ROOT}/sdk/samples/asbuild/bin/config.txt") +function(check name code expected) + file(WRITE "${TEST_ROOT}/main.vas" "${code}\n") + execute_process(COMMAND "${VASBUILD}" "${config}" "${TEST_ROOT}/main.vas" "${TEST_ROOT}/main.vasbc" + RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err TIMEOUT 20 ENCODING UTF-8) + if(NOT result EQUAL 0) + message(FATAL_ERROR "${name} compilation failed (${result})\n${out}\n${err}") + endif() + execute_process(COMMAND "${VASRUN}" "${TEST_ROOT}/main.vas" + RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err TIMEOUT 20 ENCODING UTF-8) + string(REPLACE "\r\n" "\n" out "${out}") + if(NOT result EQUAL 0 OR NOT out STREQUAL expected) + message(FATAL_ERROR "${name} runtime mismatch (${result})\n${out}\n${err}") + endif() +endfunction() +function(reject name code expected) + file(WRITE "${TEST_ROOT}/main.vas" "${code}\n") + foreach(tool IN ITEMS "${VASBUILD}" "${VASRUN}") + if(tool STREQUAL VASBUILD) + set(args "${config}" "${TEST_ROOT}/main.vas" "${TEST_ROOT}/bad.vasbc") + else() + set(args "${TEST_ROOT}/main.vas") + endif() + execute_process(COMMAND "${tool}" ${args} RESULT_VARIABLE result + OUTPUT_VARIABLE out ERROR_VARIABLE err TIMEOUT 20 ENCODING UTF-8) + if(result EQUAL 0 OR NOT "${out}${err}" MATCHES "${expected}") + message(FATAL_ERROR "${name} was not rejected cleanly by ${tool} (${result})\n${out}\n${err}") + endif() + endforeach() +endfunction() + +foreach(form IN ITEMS "import math;" "#include \"math.vas\"" "#include ") + check("equivalent-${form}" "${form}\nvoid main(){println(\"{} {} {}\", add(20,22), SUM(50,22), LABEL);}" "42 72 math\n") +endforeach() +check(dedup-and-transitive [=[ +import math; +#include "./math.vas" +#include +import constants; +import pkg.tool; +#if defined(BASE) && SUM(1,2) == 3 && TOOL_VERSION >= 2 +void main(){println("{} {} {}", BASE, ALIAS(2,3), tool());} +#else +#error dependency macros not visible +#endif +]=] "10 5 9\n") +check(nested-arguments [=[ +import math; +#define INC(x) ((x)+1) +#define VALUE 7 +#define MULTILINE(x) ((x) + \ + VALUE) +void main(){println("{} {} {} {}", INC(INC(1)), SUM(add(1,2), SUM(3,4)), MULTILINE(2), ALIAS(ALIAS(1,2),3));} +]=] "3 10 9 6\n") +check(vas-integer-radices [=[ +#if 0b1010 == 10 && 0o12 == 10 && 0d10 == 10 && 0xA == 10 && 010 == 10 && 1'000 == 1000 +void main(){println(42);} +#else +#error radix mismatch +#endif +]=] "42\n") +check(conditional-and-undef [=[ +#define EMPTY +#define FLAG 3 +#if 1 || (1 / 0) +#if 0 && (1 / 0) +#error short circuit failed +#elif FLAG * 2 == 6 && (0x10 >> 1) == 8 +#define SELECT 42 +#else +#error wrong branch +#endif +#endif +#ifdef EMPTY +#undef EMPTY +#endif +#ifndef EMPTY +void main(){println(SELECT);} +#endif +]=] "42\n") +# The module name uses underscores so that the file mapping is unambiguous. +file(WRITE "${TEST_ROOT}/cycle_a.vas" "#define CYCLE_BEFORE 7\nimport cycle_b;\n#define CYCLE_AFTER 9\n") +file(WRITE "${TEST_ROOT}/cycle_b.vas" "import cycle_a;\n#if defined(CYCLE_AFTER)\n#error forward macro became visible\n#endif\n#define CYCLE_OTHER CYCLE_BEFORE\n") +check(cycles "import cycle_a;\nvoid main(){println(\"{} {} {}\", CYCLE_BEFORE, CYCLE_AFTER, CYCLE_OTHER);}" "7 9 7\n") +check(trivia-and-literals [=[ +// import never_loaded; +/* #include */ +#if 0 +import missing; +#include +#define POISON 1 +#endif +#define TOKEN 7 +void main(){println("TOKEN import missing;", 1); println(TOKEN);} +]=] "TOKEN import missing;\n7\n") +check(identical-redefinition "#define A(x) ((x)+1)\n#define A(x) (( x ) + 1)\nvoid main(){println(A(1));}" "2\n") +check(recursion-stops "#define SELF SELF\n#define FIRST SECOND\n#define SECOND FIRST\nint SELF=3; int FIRST=7;\nvoid main(){println(\"{} {}\", SELF, FIRST);}" "3 7\n") +file(WRITE "${TEST_ROOT}/conflict.vas" "#define FLAG 2\n") +reject(conflict "#define FLAG 1\nimport conflict;\nvoid main(){}" "Conflicting macro.*previous definition at.*main.vas:1") +reject(arity "import math;\nvoid main(){println(SUM(1));}" "Wrong number of arguments") +reject(unclosed-call "import math;\nvoid main(){println(SUM(1,2;}" "Unclosed function macro") +reject(unclosed-if "#if 1\nvoid main(){}" "Unclosed conditional") +reject(unmatched-else "#else\nvoid main(){}" "Unmatched") +reject(duplicate-else "#if 0\n#else\n#else\n#endif\nvoid main(){}" "Unmatched or duplicate") +reject(empty-define "#define\nvoid main(){}" "Expected a macro name") +reject(empty-if "#if\n#endif\nvoid main(){}" "Missing operand") +reject(division-by-zero "#if 1/0\n#endif\nvoid main(){}" "Division by zero") +reject(invalid-shift "#if 1 << 64\n#endif\nvoid main(){}" "Invalid shift") +reject(function-import "void main(){ import math; }" "Module imports must be at file scope") +reject(missing-module "import missing;\nvoid main(){}" "Failed to open script file") +reject(pasting "#define JOIN(a,b) a ## b\nvoid main(){}" "not supported") +reject(variadic "#define LOG(...) 1\nvoid main(){}" "Expected a macro parameter") +string(REPEAT "!" 140 deep_expression) +reject(expression-limit "#if ${deep_expression}1\n#endif\nvoid main(){}" "expression nesting exceeds") + +# Engine diagnostics after expansion must point to the original byte column, +# including Unicode before the macro and before the later offending token. +file(WRITE "${TEST_ROOT}/main.vas" "#define LONG_NAME 1\nvoid main(){ int value = LONG_NAME; /*漢字*/ missing(); }\n") +execute_process(COMMAND "${VASBUILD}" --report=jsonl "${config}" "${TEST_ROOT}/main.vas" "${TEST_ROOT}/bad.vasbc" + RESULT_VARIABLE result OUTPUT_VARIABLE report ERROR_VARIABLE err TIMEOUT 20 ENCODING UTF-8) +string(HEX "void main(){ int value = LONG_NAME; /*漢字*/ " prefix_hex) +string(LENGTH "${prefix_hex}" prefix_length) +math(EXPR expected_column "${prefix_length} / 2 + 1") +if(result EQUAL 0 OR NOT report MATCHES "\"row\":2,\"column\":${expected_column}") + message(FATAL_ERROR "Original column mapping lost after macro expansion\n${report}\n${err}") +endif() + +# Macro-generated invalid literals also use the invocation's original location. +reject(format-macro "#define BAD println(\"{}\")\nvoid main(){ BAD; }" "println: argument not found") + +file(WRITE "${TEST_ROOT}/search-a/external.vas" "#define EXTERNAL 17\n") +file(WRITE "${TEST_ROOT}/search-b/external.vas" "#define EXTERNAL 19\n") +set(ENV{VAS_INCLUDE_PATH} "search-a") +check(search-root "#include \nvoid main(){println(EXTERNAL);}" "17\n") +if(WIN32) + set(ENV{VAS_INCLUDE_PATH} "search-a;search-b") +else() + set(ENV{VAS_INCLUDE_PATH} "search-a:search-b") +endif() +reject(ambiguity "import external;\nvoid main(){}" "Ambiguous module/include") +unset(ENV{VAS_INCLUDE_PATH}) diff --git a/tests/vasbuild/assert_print_primitives.cmake b/tests/vasbuild/assert_print_primitives.cmake new file mode 100644 index 000000000..33d2e72e0 --- /dev/null +++ b/tests/vasbuild/assert_print_primitives.cmake @@ -0,0 +1,23 @@ +cmake_minimum_required(VERSION 3.21) + +file(MAKE_DIRECTORY "${TEST_ROOT}") +set(script "${SOURCE_ROOT}/tests/vasbuild/fixtures/print_primitives.vas") +# Every shipped host configuration must accept the same primitive calls as vasrun. +foreach(config IN ITEMS + "sdk/samples/asbuild/bin/config.txt" + "tools/rider-plugin/src/main/resources/runtime/windows-x64/vasbuild.config.txt" + "templates/rider/vas-starter/.vas/vasbuild.config.txt" + "App1/.vas/vasbuild.config.txt") + execute_process(COMMAND "${VASBUILD}" "${SOURCE_ROOT}/${config}" "${script}" "${TEST_ROOT}/primitives.vasbc" + RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err ENCODING UTF-8 TIMEOUT 20) + if(NOT "${result}" STREQUAL "0") + message(FATAL_ERROR "Primitive print build failed for ${config} (${result})\n${out}\n${err}") + endif() +endforeach() + +execute_process(COMMAND "${VASRUN}" "${script}" + RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err ENCODING UTF-8 TIMEOUT 20) +set(expected "72|72|-2147483648|4294967295|-9223372036854775808|18446744073709551615|1.25|-2.5|true|false|-128|255|-32768|65535|72|string\n") +if(NOT "${result}" STREQUAL "0" OR NOT "${out}" STREQUAL "${expected}") + message(FATAL_ERROR "Primitive print run failed (${result})\nExpected: ${expected}\nActual: ${out}\n${err}") +endif() diff --git a/tests/vasbuild/assert_println.cmake b/tests/vasbuild/assert_println.cmake new file mode 100644 index 000000000..866d1b4ba --- /dev/null +++ b/tests/vasbuild/assert_println.cmake @@ -0,0 +1,123 @@ +cmake_minimum_required(VERSION 3.21) +file(MAKE_DIRECTORY "${TEST_ROOT}") +set(script "${SOURCE_ROOT}/tests/vasbuild/fixtures/println.vas") +foreach(config IN ITEMS + "sdk/samples/asbuild/bin/config.txt" + "tools/rider-plugin/src/main/resources/runtime/windows-x64/vasbuild.config.txt" + "templates/rider/vas-starter/.vas/vasbuild.config.txt" + "App1/.vas/vasbuild.config.txt") + execute_process(COMMAND "${VASBUILD}" "${SOURCE_ROOT}/${config}" "${script}" "${TEST_ROOT}/println.vasbc" + RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err ENCODING UTF-8 TIMEOUT 20) + if(NOT "${result}" STREQUAL "0") + message(FATAL_ERROR "println build failed for ${config} (${result})\n${out}\n${err}") + endif() +endforeach() + +# Compare hex bytes to retain embedded NULs and verify exactly one added newline. +execute_process(COMMAND "${VASRUN}" "${script}" RESULT_VARIABLE result + OUTPUT_FILE "${TEST_ROOT}/output.txt" ERROR_VARIABLE err TIMEOUT 20) +set(expected "72\nresult = 72\nABC + 72 ASDA\nABC + 72 ASDA\nhex=0048, pi=3.14\nworld hello world\n{} {data}\n| x|y |\n0048 3.142\n漢字😀 文字😀\nline\n\n\n\n") +string(HEX "${expected}" expected_hex) +string(APPEND expected_hex "6100620a") +set(tail "0 1 2 3 4 5 6 7 8 9 10 11\n-128\n255\n-32768\n65535\n-2147483648\n4294967295\n-9223372036854775808\n18446744073709551615\n1.25\n-2.5\ntrue\nfalse\n-128|255|-32768|65535|-2147483648|4294967295|-9223372036854775808|18446744073709551615|1.25|-2.5|true\nprint still has no newline|ABC + 72 ASDA|ABC + 72 ASDA|hex=0048, pi=3.14|{} {data}|漢字😀 文字😀") +string(HEX "${tail}" tail_hex) +string(APPEND expected_hex "${tail_hex}") +file(READ "${TEST_ROOT}/output.txt" actual_hex HEX) +# Text-mode stdout translates logical LF to CRLF on Windows. +if(WIN32) + string(REPLACE "0d0a" "0a" actual_hex "${actual_hex}") +endif() +if(NOT "${result}" STREQUAL "0" OR NOT "${actual_hex}" STREQUAL "${expected_hex}") + message(FATAL_ERROR "println output mismatch (${result})\nExpected hex: ${expected_hex}\nActual hex: ${actual_hex}\n${err}") +endif() + +# Literal syntax, argument indices and type errors must fail during compilation, +# including code that never executes. Test both the runner and exported configs. +set(error_calls + "FUNCTION(\"partial {\")" + "FUNCTION(\"partial }\")" + "FUNCTION(\"partial {}\")" + "FUNCTION(\"partial {1}\", 72)" + "FUNCTION(\"partial {} {0}\", 72)" + "FUNCTION(\"partial {:d}\", \"text\")" + "FUNCTION(\"partial {:q}\", 72)" + "FUNCTION(\"partial {:{}d}\", 72)" + "FUNCTION(\"partial {:{}d}\", 72, true)" + "FUNCTION(\"partial {0:.{1}f}\", 1.0, \"bad\")" + "FUNCTION(\"partial {name}\", 72)" + "FUNCTION(\"partial {}\", array())" + "FUNCTION((\"partial \" \"{}\"))") +foreach(call IN LISTS error_calls) + foreach(function IN ITEMS print println) + string(REPLACE "FUNCTION" "${function}" actual_call "${call}") + file(WRITE "${TEST_ROOT}/invalid.vas" "void main() { if(false) { ${actual_call}; } }\n") + execute_process(COMMAND "${VASBUILD}" "${SOURCE_ROOT}/sdk/samples/asbuild/bin/config.txt" + "${TEST_ROOT}/invalid.vas" "${TEST_ROOT}/invalid.vasbc" + RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err ENCODING UTF-8 TIMEOUT 20) + if("${result}" STREQUAL "0" OR NOT "${out}${err}" MATCHES "${function}:") + message(FATAL_ERROR "Invalid literal compiled: ${actual_call} (${result})\n${out}\n${err}") + endif() + execute_process(COMMAND "${VASRUN}" "${TEST_ROOT}/invalid.vas" + RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err ENCODING UTF-8 TIMEOUT 20) + if("${result}" STREQUAL "0" OR NOT "${out}${err}" MATCHES "ERR.*${function}:" OR out MATCHES "script exception") + message(FATAL_ERROR "Runner did not reject literal at build time: ${actual_call}\n${out}\n${err}") + endif() + endforeach() +endforeach() + +# Dynamic text is checked at runtime. Invalid values (e.g. negative width) also +# remain runtime errors; neither path may emit a partially formatted message. +set(runtime_calls + "string f = \"partial {\"\; FUNCTION(f)" + "string f = \"partial {}\"\; FUNCTION(f)" + "string f = \"partial {:d}\"\; FUNCTION(f, \"bad\")" + "FUNCTION(\"partial {:{}d}\", 72, -1)") +foreach(call IN LISTS runtime_calls) + foreach(function IN ITEMS print println) + string(REPLACE "FUNCTION" "${function}" actual_call "${call}") + file(WRITE "${TEST_ROOT}/dynamic.vas" "void main() { ${actual_call}; print(\"unreachable marker\"); }\n") + execute_process(COMMAND "${VASBUILD}" "${SOURCE_ROOT}/sdk/samples/asbuild/bin/config.txt" + "${TEST_ROOT}/dynamic.vas" "${TEST_ROOT}/dynamic.vasbc" + RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err ENCODING UTF-8 TIMEOUT 20) + if(NOT "${result}" STREQUAL "0") + message(FATAL_ERROR "Dynamic/value error incorrectly rejected at compilation\n${out}\n${err}") + endif() + execute_process(COMMAND "${VASRUN}" "${TEST_ROOT}/dynamic.vas" + RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err ENCODING UTF-8 TIMEOUT 20) + if("${result}" STREQUAL "0" OR NOT out MATCHES "${function}:" OR out MATCHES "partial |unreachable marker") + message(FATAL_ERROR "Dynamic format did not fail cleanly\n${out}\n${err}") + endif() + endforeach() +endforeach() + +# Valid literal forms, dynamic values, extra unused arguments, and fallback sizes. +file(WRITE "${TEST_ROOT}/valid.vas" "void main() { +" + "println(\"no placeholders\", 123); +" + "println(\"{0} {0}\", 7); +" + "println(\"{:{}.{}f}\", 1.25, 8, 2); +" + "println(format: \"ok\"); +" + "string f = \"{}\"; println(f, 7); +" + "string s; s.resize(600); for(uint i=0; i<600; ++i) s[i]=120; println(\"{}\", s); +" + "println(\"{16}\", 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16); +" + "}\n") +execute_process(COMMAND "${VASBUILD}" "${SOURCE_ROOT}/sdk/samples/asbuild/bin/config.txt" + "${TEST_ROOT}/valid.vas" "${TEST_ROOT}/valid.vasbc" + RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err ENCODING UTF-8 TIMEOUT 20) +if(NOT "${result}" STREQUAL "0") + message(FATAL_ERROR "Valid format rejected\n${out}\n${err}") +endif() +execute_process(COMMAND "${VASRUN}" "${TEST_ROOT}/valid.vas" + RESULT_VARIABLE result OUTPUT_VARIABLE out ERROR_VARIABLE err ENCODING UTF-8 TIMEOUT 20) +string(REPEAT "x" 600 long_text) +string(REPLACE "\r\n" "\n" out "${out}") +if(NOT "${result}" STREQUAL "0" OR NOT out STREQUAL "no placeholders\n7 7\n 1.25\nok\n7\n${long_text}\n16\n") + message(FATAL_ERROR "Valid/dynamic/large format mismatch\n${out}\n${err}") +endif() diff --git a/tests/vasbuild/fixtures/print_primitives.vas b/tests/vasbuild/fixtures/print_primitives.vas new file mode 100644 index 000000000..d8466e326 --- /dev/null +++ b/tests/vasbuild/fixtures/print_primitives.vas @@ -0,0 +1,22 @@ +void main() +{ + int result2 = 50 + 22; + print(72); print("|"); print(result2); print("|"); + int signedValue = -2147483647 - 1; + uint unsignedValue = 4294967295; + int64 signedWide = int64(-9223372036854775807) - 1; + uint64 unsignedWide = 18446744073709551615; + print(signedValue); print("|"); print(unsignedValue); print("|"); + print(signedWide); print("|"); print(unsignedWide); print("|"); + float singleValue = 1.25f; + double doubleValue = -2.5; + print(singleValue); print("|"); print(doubleValue); print("|"); + print(true); print("|"); print(false); print("|"); + int8 smallSigned = -128; + uint8 smallUnsigned = 255; + int16 shortSigned = -32768; + uint16 shortUnsigned = 65535; + print(smallSigned); print("|"); print(smallUnsigned); print("|"); + print(shortSigned); print("|"); print(shortUnsigned); print("|"); + print("" + result2); print("|string\n"); +} diff --git a/tests/vasbuild/fixtures/println.vas b/tests/vasbuild/fixtures/println.vas new file mode 100644 index 000000000..8de764012 --- /dev/null +++ b/tests/vasbuild/fixtures/println.vas @@ -0,0 +1,35 @@ +void main() +{ + int result2 = 72; + println(result2); + println("result = {}", result2); + println("ABC + " + result2 + " ASDA"); + println("ABC + {} ASDA", result2); + println("hex={:04X}, pi={:.2f}", result2, 3.14159); + println("{1} {0} {1}", "hello", "world"); + println("{{}} {}", "{data}"); + println("|{:>5}|{:<5}|", "x", "y"); + println("{:0{}X} {:.{}f}", result2, 4, 3.14159, 3); + println("漢字😀 {}", "文字😀"); + println("line\n"); + println(""); + println(); + println("{}", "a\0b"); + println("{} {} {} {} {} {} {} {} {} {} {} {}", 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11); + int8 i8 = -128; uint8 u8 = 255; + int16 i16 = -32768; uint16 u16 = 65535; + int i32 = -2147483647 - 1; uint u32 = 4294967295; + int64 i64 = int64(-9223372036854775807) - 1; + uint64 u64 = 18446744073709551615; + float f = 1.25f; double d = -2.5; + println(i8); println(u8); println(i16); println(u16); + println(i32); println(u32); println(i64); println(u64); + println(f); println(d); println(true); println(false); + println("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}", i8, u8, i16, u16, i32, u32, i64, u64, f, d, true); + print("print still has no newline"); + print("|ABC + " + result2 + " ASDA"); + print("|ABC + {} ASDA", result2); + print("|hex={:04X}, pi={:.2f}", result2, 3.14159); + print("|{{}} {}", "{data}"); + print("|漢字😀 {}", "文字😀"); +} diff --git a/tests/vasbuild/test_format_performance.cpp b/tests/vasbuild/test_format_performance.cpp new file mode 100644 index 000000000..d7f11b261 --- /dev/null +++ b/tests/vasbuild/test_format_performance.cpp @@ -0,0 +1,159 @@ +// Include the implementation to measure the actual registered concatenation +// callbacks against their former ostringstream implementation. +#include "../../sdk/add_on/scriptstdstring/scriptstdstring.cpp" +#include "../../sdk/add_on/scripthelper/scripthelper.h" +#include "../../sdk/samples/common/vas_format.h" +#include "../../sdk/samples/asrun/vendor/fmt/args.h" +#include +#include +#include +#include +#include + +static bool counting = false; +static size_t allocations = 0; +void *operator new(size_t size) { + if (void *p = std::malloc(size ? size : 1)) { if (counting) ++allocations; return p; } + throw std::bad_alloc(); +} +void *operator new[](size_t size) { return ::operator new(size); } +void operator delete(void *p) noexcept { std::free(p); } +void operator delete[](void *p) noexcept { std::free(p); } +void operator delete(void *p, size_t) noexcept { std::free(p); } +void operator delete[](void *p, size_t) noexcept { std::free(p); } + +static void require(bool condition, const char *message) { + if (!condition) { std::cerr << message << '\n'; std::exit(1); } +} +template static std::string oldText(T value) { + std::ostringstream stream; stream << value; return stream.str(); +} +template static void checkText(T value) { + NumericText text(value); + require(std::string(text.data(), text.length()) == oldText(value), "numeric output changed"); +} +struct Grouped : std::numpunct { + char do_decimal_point() const override { return ','; } + char do_thousands_sep() const override { return '_'; } + std::string do_grouping() const override { return "\3"; } +}; +struct LongNumber : std::num_put { + iter_type do_put(iter_type out, std::ios_base &, char_type, double) const override { + for (int i = 0; i < 200; ++i) *out++ = 'x'; + return out; + } +}; +static void numericRegression() { + checkText((std::numeric_limits::min)()); + checkText((std::numeric_limits::max)()); + checkText((std::numeric_limits::max)()); + checkText(asINT64(0)); + const double values[] = {0, -0.0, 1.23456789, 1e-9, 1e20, + (std::numeric_limits::max)(), (std::numeric_limits::min)(), + std::numeric_limits::denorm_min(), std::numeric_limits::infinity(), + -std::numeric_limits::infinity(), std::numeric_limits::quiet_NaN()}; + for (double value : values) { checkText(value); checkText(float(value)); } + std::locale previous = std::locale::global(std::locale(std::locale::classic(), new Grouped)); + checkText(asINT64(-123456789)); checkText(asQWORD(123456789)); checkText(12345.6789); + std::locale::global(std::locale(std::locale::classic(), new LongNumber)); + checkText(1.25); // A host facet exceeding the stack buffer must remain valid. + std::locale::global(previous); + require(AddStringBool("[", true) == "[true", "bool append changed"); + require(AddBoolString(false, "]") == "false]", "bool prepend changed"); + std::string value; + AssignInt64ToString((std::numeric_limits::min)(), value); + AddAssignUInt64ToString((std::numeric_limits::max)(), value); + require(value == "-922337203685477580818446744073709551615", "assignment/append changed"); +} + +static void dummy(asIScriptGeneric *) {} +static void compilerRegression() { + asIScriptEngine *engine = asCreateScriptEngine(); + int invalid = engine->RegisterGlobalFunction("void invalid(int value, const ?&in ...)", + asFUNCTION(dummy), asCALL_GENERIC); + require(invalid >= 0, "primitive variadic registration failed"); + require(engine->GetFunctionById(invalid)->SetFormatStringValidator(vas::ValidateFormat, engine) == asINVALID_ARG, + "missing string type accepted a primitive format parameter"); + RegisterStdString(engine); + int id = engine->RegisterGlobalFunction("void checked(const string &in format, const ?&in ...)", + asFUNCTION(dummy), asCALL_GENERIC); + require(id >= 0, "registration failed"); + require(engine->GetFunctionById(id)->SetFormatStringValidator(vas::ValidateFormat, engine) == 0, + "opt-in failed"); + int ordinary = engine->RegisterGlobalFunction("void ordinary(const string &in, const ?&in ...)", + asFUNCTION(dummy), asCALL_GENERIC); + require(ordinary >= 0, "ordinary registration failed"); + auto build = [engine](const char *code) { + auto *module = engine->GetModule("test", asGM_ALWAYS_CREATE); + module->AddScriptSection("test", code); + return module->Build(); + }; + require(build("void main(){ ordinary(\"{}\"); }") >= 0, "unmarked function was checked"); + require(build("namespace custom { void print(const string &in) {} } void main(){ custom::print(\"{\"); }") >= 0, + "script function was checked by name"); + require(build("void main(){ checked(format: \"ok\"); }") >= 0, "named fixed parameter failed"); + require(build("void main(){ checked(format: \"{}\"); }") < 0, "named literal skipped validation"); + require(build("void main(){ checked(\"{}\", 7); }") >= 0, "valid primitive failed"); + std::stringstream config; + require(WriteConfigToStream(engine, config) >= 0, "config export failed"); + require(config.str().find("formatfunc \"void checked") != std::string::npos, "metadata not exported"); + asIScriptEngine *consumer = asCreateScriptEngine(); + require(ConfigEngineFromStream(consumer, config, "test", GetStdStringFactorySingleton(), + vas::ValidateFormat, consumer) >= 0, "metadata import failed"); + auto *module = consumer->GetModule("test", asGM_ALWAYS_CREATE); + module->AddScriptSection("test", "void main(){ checked(\"{}\"); }"); + require(module->Build() < 0, "export/import silently lost checks"); + consumer->ShutDownAndRelease(); + config.clear(); config.seekg(0); + consumer = asCreateScriptEngine(); + require(ConfigEngineFromStream(consumer, config, "test", GetStdStringFactorySingleton()) < 0, + "missing validator silently accepted formatfunc"); + consumer->ShutDownAndRelease(); + engine->ShutDownAndRelease(); +} + +template static size_t measure(const char *name, F operation) { + const int iterations = 10000; + volatile size_t checksum = 0; + operation(); // warm up library state + allocations = 0; + auto begin = std::chrono::steady_clock::now(); + counting = true; + for (int i = 0; i < iterations; ++i) checksum = checksum + operation(); + counting = false; + auto elapsed = std::chrono::duration_cast(std::chrono::steady_clock::now() - begin).count(); + std::cout << name << ": " << allocations << " allocations / " << iterations + << " calls, " << elapsed << " us, checksum=" << checksum << '\n'; + return allocations; +} + +int main() { + numericRegression(); + compilerRegression(); + const std::string prefix(80, 'x'); + const asINT64 number = (std::numeric_limits::min)(); + auto oldConcat = [&] { std::ostringstream stream; stream << number; return (prefix + stream.str()).size(); }; + auto newConcat = [&] { return AddStringInt64(prefix, number).size(); }; + require(AddStringInt64(prefix, number) == prefix + oldText(number), "concatenation changed"); + size_t oldCount = measure("old integer concatenation", oldConcat); + size_t newCount = measure("new integer concatenation", newConcat); + // libc++ can keep the old 20-byte conversion inside its larger string buffer. + require(newCount <= oldCount, "integer allocation count regressed"); + auto oldFormat = [&] { + fmt::dynamic_format_arg_store args; + args.push_back(prefix); args.push_back(number); + return fmt::vformat("{} {}", args).size(); + }; + const std::string expected = fmt::vformat("{} {}", fmt::make_format_args(prefix, number)); + auto measuredFormat = [&] { + vas::FormatArguments args(2); + args.set(0, fmt::string_view(prefix.data(), prefix.size())); args.set(1, number); + fmt::memory_buffer buffer; vas::FormatTo(buffer, "{} {}", args, false); + require(fmt::string_view(buffer.data(), buffer.size()) == fmt::string_view(expected), "format changed"); + return buffer.size(); + }; + oldCount = measure("old format construction (excluding I/O)", oldFormat); + newCount = measure("new format construction (excluding I/O)", measuredFormat); + require(newCount == 0 && oldCount > newCount, "inline format path allocated"); + return 0; +} diff --git a/tests/vasbuild/test_module_performance.cpp b/tests/vasbuild/test_module_performance.cpp new file mode 100644 index 000000000..e885756c4 --- /dev/null +++ b/tests/vasbuild/test_module_performance.cpp @@ -0,0 +1,145 @@ +#include "../../sdk/samples/common/vas_scriptbuilder.h" +#include +#include +#include + +static void check(bool value, const char *message) { + if (!value) { std::cerr << message << '\n'; std::exit(1); } +} +static void message(const asSMessageInfo *info, void *) { + if (info->type == asMSGTYPE_ERROR) std::cerr << info->section << ':' << info->row << ':' << info->col << ' ' << info->message << '\n'; +} +static void write(const std::string &path, const std::string &text) { + FILE *file = vas::OpenFile(path.c_str(), "wb"); check(file != nullptr, "Cannot create benchmark fixture"); + check(std::fwrite(text.data(), 1, text.size(), file) == text.size(), "Cannot write benchmark fixture"); + check(std::fclose(file) == 0, "Cannot close benchmark fixture"); +} +static int oldInclude(const char *name, const char *from, CScriptBuilder *builder, void *) { + std::string parent(from); parent.resize(parent.find_last_of("/\\") + 1); + return builder->AddSectionFromFile((parent + name).c_str()); +} +static int run(asIScriptEngine *engine, asIScriptModule *module) { + auto *context = engine->CreateContext(); + check(context->Prepare(module->GetFunctionByDecl("int main()")) >= 0, "Cannot prepare benchmark"); + check(context->Execute() == asEXECUTION_FINISHED, "Cannot execute benchmark"); + int result = int(context->GetReturnDWord()); context->Release(); return result; +} +static void benchmark(const char *label, const std::string &file, bool modern, int expected, uint64_t reads) { + std::vector loads, compiles; + uint64_t tokens = 0, expansions = 0, fastSections = 0; + // One warm-up and three runs: OS cache is warm for both builders. No fragile + // timing threshold in CI; semantic, read-count and reset checks are gates. + for (int iteration = 0; iteration < 4; ++iteration) { + auto *engine = asCreateScriptEngine(); + engine->SetMessageCallback(asFUNCTION(message), nullptr, asCALL_CDECL); + auto begin = std::chrono::steady_clock::now(); + if (modern) { + vas::ScriptBuilder builder; + check(builder.StartNewModule(engine, "bench") >= 0, "Cannot start modern builder"); + builder.SetMappedMessageCallback(message, nullptr); + check(builder.AddSectionFromFile(file.c_str()) > 0, "Modern preprocessing failed"); + auto loaded = std::chrono::steady_clock::now(); + check(builder.BuildModule() >= 0, "Modern compilation failed"); + auto compiled = std::chrono::steady_clock::now(); + check(run(engine, builder.GetModule()) == expected, "Modern output changed"); + check(builder.GetFileReadCount() == reads, "Repeated import reread a source file"); + tokens = builder.GetPreprocessingStatistics().tokens; + expansions = builder.GetPreprocessingStatistics().expansions; + fastSections = builder.GetPreprocessingStatistics().fastSections; + if (iteration) { + loads.push_back(std::chrono::duration_cast(loaded - begin).count()); + compiles.push_back(std::chrono::duration_cast(compiled - loaded).count()); + } + } else { + CScriptBuilder builder; + check(builder.StartNewModule(engine, "bench") >= 0, "Cannot start reference builder"); + builder.SetIncludeCallback(oldInclude, nullptr); + check(builder.AddSectionFromFile(file.c_str()) > 0, "Reference preprocessing failed"); + auto loaded = std::chrono::steady_clock::now(); + check(builder.BuildModule() >= 0, "Reference compilation failed"); + auto compiled = std::chrono::steady_clock::now(); + check(run(engine, builder.GetModule()) == expected, "Reference output changed"); + if (iteration) { + loads.push_back(std::chrono::duration_cast(loaded - begin).count()); + compiles.push_back(std::chrono::duration_cast(compiled - loaded).count()); + } + } + engine->ShutDownAndRelease(); + } + std::sort(loads.begin(), loads.end()); std::sort(compiles.begin(), compiles.end()); + std::cout << label << ": load/preprocess median=" << loads[1] << " us, compile median=" << compiles[1] << " us"; + if (modern) std::cout << ", actual file reads=" << reads << ", lexed tokens=" << tokens + << ", expansions=" << expansions << ", fast sections=" << fastSections; + std::cout << '\n'; +} +int main(int argc, char **argv) { + check(argc == 2, "Expected benchmark directory"); + // The reference SDK loader treats MinGW relative paths as executable-relative. + // Give both builders the same native absolute path for a fair comparison. + std::string root; + check(vas::AbsolutePath(argv[1], root), "Cannot resolve benchmark directory"); + const std::string file = root + "/bench.vas", dependency = root + "/math.vas"; + std::string plain; + for (int i = 0; i < 2000; ++i) plain += "int value" + std::to_string(i) + "(){return " + std::to_string(i) + ";}\n"; + plain += "int main(){return value42();}\n"; + write(file, plain); + benchmark("reference plain source (2000 functions)", file, false, 42, 1); + benchmark("modern plain source (fast path)", file, true, 42, 1); + write(dependency, "int add(int a,int b){return a+b;}\n"); + std::string quoted, mixed; + for (int i = 0; i < 10000; ++i) { + quoted += "#include \"math.vas\"\n"; + mixed += i % 3 == 0 ? "import math;\n" : i % 3 == 1 ? "#include \"math.vas\"\n" : "#include \n"; + } + const std::string entry = "int main(){return add(20,22);}\n"; + write(file, quoted + entry); + benchmark("reference repeated includes (10000)", file, false, 42, 2); + benchmark("modern repeated includes (10000)", file, true, 42, 2); + write(file, mixed + entry); + benchmark("modern mixed imports/includes (10000)", file, true, 42, 2); + std::string expanded = "int main(){int sum=0;\n", macro = "#define SUM(a,b) ((a)+(b))\nint main(){int sum=0;\n"; + for (int i = 0; i < 10000; ++i) { expanded += "sum += ((1)+(2));\n"; macro += "sum += SUM(1,2);\n"; } + expanded += "return sum;}\n"; macro += "return sum;}\n"; + write(file, expanded); + benchmark("modern already expanded source (10000 expressions)", file, true, 30000, 1); + write(file, macro); + benchmark("modern function macros (10000 calls)", file, true, 30000, 1); + // Reusing a builder must clear the macro and positive resolution caches. + auto *engine = asCreateScriptEngine(); + engine->SetMessageCallback(asFUNCTION(message), nullptr, asCALL_CDECL); + { + vas::ScriptBuilder builder; + write(dependency, "#define VALUE 7\n"); write(file, "import math;\nint main(){return VALUE;}\n"); + for (int expected : {7, 9}) { + write(dependency, "#define VALUE " + std::to_string(expected) + "\n"); + check(builder.StartNewModule(engine, "reset") >= 0, "Cannot reset builder"); + builder.SetMappedMessageCallback(message, nullptr); + check(builder.AddSectionFromFile(file.c_str()) > 0 && builder.BuildModule() >= 0, "Rebuild failed"); + check(run(engine, builder.GetModule()) == expected, "Rebuild used a stale macro/source cache"); + check(builder.GetFileReadCount() == 2, "Rebuild did not reread both inputs"); + } + std::vector referenceCode; + for (bool useMacro : {false, true}) { + check(builder.StartNewModule(engine, "bytecode") >= 0, "Cannot start bytecode check"); + std::string source = useMacro ? "#define SUM(a,b) ((a)+(b))\nint main(){int x=7;return SUM(x,3);}" : + "int main(){int x=7;return ((x)+(3));}"; + check(builder.AddSectionFromMemory("memory", source.c_str()) >= 0 && builder.BuildModule() >= 0, "Bytecode check compilation failed"); + auto *function = builder.GetModule()->GetFunctionByDecl("int main()"); + asUINT count = 0; auto *code = function->GetByteCode(&count); + std::vector instructions(code, code + count); + if (useMacro) check(instructions == referenceCode, "Macro expansion changed runtime bytecode"); + else referenceCode = std::move(instructions); + check(run(engine, builder.GetModule()) == 10, "Bytecode check output changed"); + } + builder.StartNewModule(engine, "native-import"); + check(builder.AddSectionFromMemory("memory", "import int host(int) from \"other\"; int main(){return 42;}") >= 0 && builder.BuildModule() >= 0, + "Legacy function import grammar changed"); + check(builder.GetModule()->GetImportedFunctionCount() == 1, "Native function import was consumed as a module import"); + builder.StartNewModule(engine, "define-word"); builder.DefineWord("HOST_FLAG"); + check(builder.AddSectionFromMemory("memory", "#if HOST_FLAG\nint main(){return 42;}\n#endif\n") >= 0 && builder.BuildModule() >= 0, + "Host DefineWord compatibility failed"); + check(run(engine, builder.GetModule()) == 42, "Host define value changed"); + } + engine->ShutDownAndRelease(); + std::cout << "Rebuild cache invalidation, identical runtime bytecode, native function import and host DefineWord checks passed.\n"; +} diff --git a/tools/ide-artifacts/test_stage.py b/tools/ide-artifacts/test_stage.py index 1854baa2a..75d902cf2 100644 --- a/tools/ide-artifacts/test_stage.py +++ b/tools/ide-artifacts/test_stage.py @@ -2,6 +2,7 @@ import contextlib import io import json +import re from pathlib import Path import stat import struct @@ -46,13 +47,17 @@ def raw_named_zip(name, local_name=None): return bytes(data) +VSCODE_VERSION = stage.read_json(stage.ROOT / "tools/vscode-extension/package.json")["version"] +RIDER_VERSION = re.search(r'^version = "([^\"]+)"$', (stage.ROOT / "tools/rider-plugin/build.gradle.kts").read_text(), re.M)[1] + + def vscode_entries(): root = stage.ROOT / "tools/vscode-extension" entries = [(f"extension/{name}", (root / name).read_bytes()) for name in ( "LICENSE.md", "package.json", "language-configuration.json", "syntaxes/vas.tmLanguage.json", "snippets/vas.code-snippets")] entries += [("extension/readme.md", (root / "README.md").read_bytes())] entries += [(f"extension/src/{p.name}", p.read_bytes()) for p in (root / "src").glob("*.js")] - entries += [("[Content_Types].xml", b""), ("extension.vsixmanifest", b'')] + entries += [("[Content_Types].xml", b""), ("extension.vsixmanifest", f''.encode())] return entries @@ -62,9 +67,9 @@ def rider_entries(): for p in (root / "src/main/resources").rglob("*") if p.is_file() and p.name != "plugin.xml"] entries += [(p.relative_to(root / "src/main/java").with_suffix(".class").as_posix(), b"synthetic-class") for p in (root / "src/main/java").rglob("*.java")] - entries += [("META-INF/plugin.xml", b'com.verseangelscript.language0.5.6')] + entries += [("META-INF/plugin.xml", f'com.verseangelscript.language{RIDER_VERSION}'.encode())] prefix = "verse-angelscript-rider/lib/" - return [(prefix + "verse-angelscript-rider-0.5.6.jar", zipped(entries)), + return [(prefix + f"verse-angelscript-rider-{RIDER_VERSION}.jar", zipped(entries)), # The official Gson 2.13.2 JAR also ships this consumer ProGuard file. (prefix + "gson-2.13.2.jar", zipped([("com/google/gson/Gson.class", b"synthetic-class"), ("META-INF/proguard/gson.pro", b"-keepattributes Signature\n")])), @@ -148,7 +153,7 @@ def test_untracked_production_tree_files_are_never_allowlisted(self): def test_vscode_only_current_production_bytes(self): entries = vscode_entries() - self.assertEqual(stage.vscode_package(zipped(entries)), ("0.1.0", {"vscodeEngine": "^1.96.0"})) + self.assertEqual(stage.vscode_package(zipped(entries)), (VSCODE_VERSION, {"vscodeEngine": "^1.96.0"})) for member in ("extension/test/private.js", "extension/.env", "extension/node_modules/sdk/index.js", "private.key"): with self.subTest(member=member), self.assertRaisesRegex(ValueError, "payload"): stage.vscode_package(zipped(entries + [(member, b"private")])) @@ -174,7 +179,7 @@ def test_rider_rejects_sdk_and_nested_test_or_private_payload(self): def test_gson_proguard_entry_is_allowed_only_in_gson(self): entries = rider_entries() - self.assertEqual(stage.rider_package(zipped(entries))[0], "0.5.6") + self.assertEqual(stage.rider_package(zipped(entries))[0], RIDER_VERSION) # Do not broaden this exception to unrelated ProGuard data or another JAR. for index, member in ((1, "META-INF/proguard/private.pro"), (1, "META-INF/private.txt"), diff --git a/tools/rider-plugin/README.md b/tools/rider-plugin/README.md index ca7059c7f..b33ed11b7 100644 --- a/tools/rider-plugin/README.md +++ b/tools/rider-plugin/README.md @@ -39,11 +39,11 @@ $env:JAVA_HOME = 'C:\Path\To\JDK-25' **Settings | Plugins | 齿轮菜单 | Install Plugin from Disk** -选择本次 `build/distributions` 生成的 ZIP 后按提示重启 Rider。仓库 `plugins/rider/VerseAngelScript-Rider-Plugin-0.5.6.zip` 是较早的已检入包,不能代表当前源码;源码版本号未变也不表示包内容相同。也可使用目标提交对应的完整成功 CI 运行所附安装产物(保留 7 天);核对其中 manifest 与 SHA-256,解压 Actions 外层包后选择内部插件 ZIP。 +选择本次 `build/distributions` 生成的 ZIP 后按提示重启 Rider。仓库 `plugins/rider/VerseAngelScript-Rider-Plugin-0.5.6.zip` 是较早的已检入包,不能代表当前 0.5.9 源码。也可使用目标提交对应的完整成功 CI 运行所附安装产物(保留 7 天);核对其中 manifest 与 SHA-256,解压 Actions 外层包后选择内部插件 ZIP。 ## 后台诊断与项目安全 -打开或编辑 `.vas` 文件触发的后台编译诊断,仅在 Rider 已信任项目且已配置 builder 路径时运行。项目配置中的可执行文件路径本身不代表信任;未信任或已释放的项目不会启动后台编译器。插件会在收集输入、处理排队请求和启动进程之前重新检查,不会自动更改信任状态或弹出信任提示。 +打开或编辑 `.vas` 文件触发的后台编译诊断,仅在 Rider 已信任项目且已配置应用级 Compiler executable 或既有项目 builder 路径时运行。项目配置中的可执行文件路径本身不代表信任;未信任或已释放的项目不会启动后台编译器。插件会在收集输入、处理排队请求和启动进程之前重新检查,不会自动更改信任状态或弹出信任提示。 显式 **Build/Run** 动作和起步项目生成器保持原有行为。原生 Rider 信任回归测试使用隔离的测试信任存储与项目级记录启动器,检查未信任文件的打开/编辑、排队请求、恢复信任后的普通高亮及诊断范围;不会执行项目提供的测试二进制文件。 @@ -161,3 +161,10 @@ CI 保留 Gradle、既有 trust gate、新 project-build gate 各自失败状态 编辑事件仍可执行,以及合并、上限、取消和队列退出竞态。新增原生宿主案例 `keepsFilesystemValidationOffEdt` 使用实际构建和后台检查观察器验证对应适配链路;该案例 仍需在真实 Rider Solution Host 中运行后才能计为宿主通过。 + + +当前源码 0.5.9 补齐 `import Foo.Bar;`/include 依赖导航、导出宏候选、命名空间/简单对象成员补全、类型/函数/宏语义颜色和 Go to Symbol。原有函数 `import ... from ...` 仍进入索引。条件编译尚无编译器绑定,导航展示已知候选,重命名仍须通过覆盖预检。安装本次 `build/distributions/verse-angelscript-rider-0.5.9.zip` 并重启后生效;详细验证与性能见 [语言服务说明](../../docs/ide-language-support.md)。 + +当前源码还提供原生符号配对/成对退格/块缩进、函数调用补全、参数提示与即时结构错误标记。后台检查镜像未保存的 import/include 依赖,拒绝发布过期快照。配置与验证见 [语言服务说明](../../docs/ide-language-support.md)。 + +0.5.9 修复宏/条件指令模块的原生 Find Usages:只读搜索与重命名覆盖预检分别处理,Code Vision 计数及调用导航同步恢复。`RunBatch` 跨模块调用由真实 Rider FindUsagesManager 的已注册 handler 验证。 diff --git a/tools/rider-plugin/build.gradle.kts b/tools/rider-plugin/build.gradle.kts index 325438241..665e4d104 100644 --- a/tools/rider-plugin/build.gradle.kts +++ b/tools/rider-plugin/build.gradle.kts @@ -7,7 +7,7 @@ plugins { } group = "com.verseangelscript" -version = "0.5.6" +version = "0.5.9" repositories { mavenCentral() @@ -76,8 +76,12 @@ intellijPlatform { """.trimIndent() changeNotes = """ - Adds a Rider Solution Host integration test for nested include and declaration - navigation, while retaining the strict .vas entry/include validation. +

0.5.9: Native Find Usages, Code Vision and caller navigation now use + a read-only source search through import/include modules with macros. + Rename keeps the complete-coverage preflight and ambiguous bindings remain filtered.

+ Adds native typing pairs, paired backspace, block Enter indentation, + function insertion and parameter help, instant structural errors and + compiler diagnostics from unsaved module snapshots. """.trimIndent() } } diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/diagnostics/VasExternalAnnotator.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/diagnostics/VasExternalAnnotator.java index 5f32d408b..894774985 100644 --- a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/diagnostics/VasExternalAnnotator.java +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/diagnostics/VasExternalAnnotator.java @@ -17,9 +17,12 @@ import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.verseangelscript.rider.build.VasSettingsState; +import com.verseangelscript.rider.build.VasToolchainSettings; +import com.verseangelscript.rider.index.VasIncludeScanner; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; @@ -28,14 +31,13 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import java.util.Map; +import java.util.HashMap; public final class VasExternalAnnotator extends ExternalAnnotator< VasExternalAnnotator.Request, @@ -43,9 +45,6 @@ public final class VasExternalAnnotator extends ExternalAnnotator< > { private static final int TIMEOUT_MS = 20_000; private static final Key TEST_LAUNCHER = Key.create("vas.diagnostics.testLauncher"); - private static final Pattern INCLUDE = Pattern.compile( - "(?m)^\\s*#include\\s+\"([^\"]+)\"" - ); @Override public @Nullable Request collectInformation(@NotNull PsiFile file) { @@ -57,7 +56,20 @@ public final class VasExternalAnnotator extends ExternalAnnotator< if (virtualFile == null || project.getBasePath() == null) { return null; } - return new Request(project, virtualFile, file.getText()); + Map unsaved = new HashMap<>(); + var documents = FileDocumentManager.getInstance(); + long bytes = 0; + for (Document document : documents.getUnsavedDocuments()) { + VirtualFile open = documents.getFile(document); + if (open != null && open.getExtension() != null && open.getExtension().equalsIgnoreCase("vas") + && open.getPath().startsWith(project.getBasePath() + "/") && document.getTextLength() <= 4 * 1024 * 1024) { + bytes += document.getTextLength(); + if (unsaved.size() >= 256 || bytes > 16 * 1024 * 1024) break; + unsaved.put(open.getPath(), document.getText()); + } + } + unsaved.put(virtualFile.getPath(), file.getText()); + return new Request(project, virtualFile, file.getText(), Map.copyOf(unsaved)); } @Override @@ -92,7 +104,7 @@ public final class VasExternalAnnotator extends ExternalAnnotator< request.sourceText(), toolchain.root(), temporaryRoot, - new HashSet<>() + new HashSet<>(), request.openSources(), new long[] {0} ); Path output = temporaryRoot.resolve("out/diagnostics.vasbc"); @@ -105,6 +117,10 @@ public final class VasExternalAnnotator extends ExternalAnnotator< ) .withWorkDirectory(temporaryRoot.toFile()) .withCharset(StandardCharsets.UTF_8); + List includeRoots = new ArrayList<>(); + for (Path parent = temporarySource.getParent(); parent != null && parent.startsWith(temporaryRoot); parent = parent.getParent()) + includeRoots.add(parent.toString()); + commandLine.withEnvironment("VAS_INCLUDE_PATH", String.join(java.io.File.pathSeparator, includeRoots)); ProgressManager.checkCanceled(); // Recheck after preparing the snapshot, immediately before starting a process. if (!canRunDiagnostics(request.project())) { @@ -135,7 +151,7 @@ public final class VasExternalAnnotator extends ExternalAnnotator< currentFileDiagnostics.add(diagnostic); } } - return new Result(List.copyOf(currentFileDiagnostics)); + return new Result(List.copyOf(currentFileDiagnostics), request.sourceText(), request.openSources()); } catch (ExecutionException | IOException ignored) { return null; } finally { @@ -156,6 +172,12 @@ public void apply( if (document == null) { return; } + if (result.sourceText() != null && !document.getText().equals(result.sourceText())) return; + for (var snapshot : result.openSources().entrySet()) { + VirtualFile open = com.intellij.openapi.vfs.LocalFileSystem.getInstance().findFileByPath(snapshot.getKey()); + Document cached = open == null ? null : FileDocumentManager.getInstance().getCachedDocument(open); + if (cached != null && !cached.getText().equals(snapshot.getValue())) return; + } for (VasCompilerDiagnostic diagnostic : result.diagnostics()) { TextRange range = diagnosticRange(document, diagnostic.line(), diagnostic.column()); @@ -217,12 +239,14 @@ interface ProcessLauncher { // A configured path is necessary but not proof of consent: vas.xml may come // from the project itself. The caller must also check actual project trust. // The explicit Build action is a separate, user-initiated operation. - if (settings.builderPath == null || settings.builderPath.isBlank()) { + String configuredBuilder = settings.builderPath; + if (configuredBuilder == null || configuredBuilder.isBlank()) configuredBuilder = VasToolchainSettings.getInstance().compilerPath; + if (configuredBuilder == null || configuredBuilder.isBlank()) { return null; } Path root = projectRoot; - Path builder = resolveConfiguredPath(root, settings.builderPath, ""); + Path builder = resolveConfiguredPath(root, configuredBuilder, ""); Path config = resolveConfiguredPath(root, settings.configPath, ".vas/vasbuild.config.txt"); if (settings.configPath == null || settings.configPath.isBlank()) { if (!Files.isRegularFile(config)) { @@ -246,32 +270,50 @@ private static void copyIncludes( String sourceText, Path actualRoot, Path temporaryRoot, - Set visited + Set visited, Map openSources, long[] bytes ) throws IOException { Path normalizedSource = actualSource.toAbsolutePath().normalize(); if (!visited.add(normalizedSource)) { return; } - - Matcher matcher = INCLUDE.matcher(sourceText); - while (matcher.find()) { - Path included = normalizedSource.getParent().resolve(matcher.group(1)).normalize(); + bytes[0] += sourceText.length(); + if (visited.size() > 256 || bytes[0] > 16 * 1024 * 1024) throw new IOException("Diagnostic snapshot limit exceeded"); + for (var dependency : VasIncludeScanner.scan(sourceText).includes()) { + Path included = normalizedSource.getParent().resolve(dependency.path()).normalize(); + if (!Files.isRegularFile(included) || dependency.kind() == VasIncludeScanner.Kind.SYSTEM) { + Set matches = new java.util.LinkedHashSet<>(); + for (Path parent = normalizedSource.getParent(); parent != null && parent.startsWith(actualRoot); parent = parent.getParent()) { + Path candidate = parent.resolve(dependency.path()).normalize(); + if (candidate.startsWith(actualRoot) && Files.isRegularFile(candidate)) matches.add(candidate); + } + if (matches.size() != 1) continue; + included = matches.iterator().next(); + } if (!included.startsWith(actualRoot) || !Files.isRegularFile(included)) { continue; } - Path target = temporarySource.getParent().resolve(matcher.group(1)).normalize(); + Path target = temporaryRoot.resolve(actualRoot.relativize(included)).normalize(); if (!target.startsWith(temporaryRoot)) { continue; } Files.createDirectories(target.getParent()); - Files.copy(included, target, StandardCopyOption.REPLACE_EXISTING); + String text = openSources.get(included.toString().replace('\\', '/')); + if (text == null) text = openSources.get(included.toString()); + if (text == null) for (var snapshot : openSources.entrySet()) { + if (snapshot.getKey().replace('\\', '/').equalsIgnoreCase(included.toString().replace('\\', '/'))) { text = snapshot.getValue(); break; } + } + if (text == null) { + if (Files.size(included) > 4 * 1024 * 1024) throw new IOException("Diagnostic source limit exceeded"); + text = Files.readString(included, StandardCharsets.UTF_8); + } + Files.writeString(target, text, StandardCharsets.UTF_8); copyIncludes( included, target, - Files.readString(included, StandardCharsets.UTF_8), + text, actualRoot, temporaryRoot, - visited + visited, openSources, bytes ); } } @@ -296,11 +338,14 @@ private static void deleteTemporaryTree(@Nullable Path root) { public record Request( @NotNull Project project, @NotNull VirtualFile file, - @NotNull String sourceText + @NotNull String sourceText, + @NotNull Map openSources ) { + public Request(Project project, VirtualFile file, String sourceText) { this(project, file, sourceText, Map.of()); } } - public record Result(@NotNull List diagnostics) { + public record Result(@NotNull List diagnostics, @Nullable String sourceText, @NotNull Map openSources) { + public Result(List diagnostics) { this(diagnostics, null, Map.of()); } } private record Toolchain(@NotNull Path root, @NotNull Path builder, @NotNull Path config) { diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasCompletionSelection.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasCompletionSelection.java new file mode 100644 index 000000000..9e915dfeb --- /dev/null +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasCompletionSelection.java @@ -0,0 +1,23 @@ +package com.verseangelscript.rider.index; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; + +/** Reuses navigation's scope/member rules without selecting a call overload. */ +public final class VasCompletionSelection { + private VasCompletionSelection() { } + + public static List select(List local, List dependencies, + int offset, VasUsageContext usage) { + var source = local.stream().map(symbol -> new VasSymbolSelection.Candidate<>(symbol, symbol)).toList(); + var included = dependencies.stream().map(symbol -> new VasSymbolSelection.Candidate<>(symbol, symbol)).toList(); + var context = new VasUsageContext(VasUsageContext.NOT_A_CALL, usage.qualifier(), usage.access(), usage.container()); + LinkedHashSet names = new LinkedHashSet<>(); + local.forEach(symbol -> names.add(symbol.name())); + dependencies.forEach(symbol -> names.add(symbol.name())); + List result = new ArrayList<>(); + for (String name : names) result.addAll(VasSymbolSelection.select(source, included, name, offset, context)); + return result; + } +} diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasDependencyPaths.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasDependencyPaths.java new file mode 100644 index 000000000..0217e5109 --- /dev/null +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasDependencyPaths.java @@ -0,0 +1,56 @@ +package com.verseangelscript.rider.index; + +import com.intellij.openapi.progress.ProgressManager; +import com.intellij.openapi.vfs.LocalFileSystem; +import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.psi.PsiFile; + +import java.io.File; +import java.util.LinkedHashSet; +import java.util.Set; + +/** Read-only editor search hints. Does not claim compiler dependency/rename coverage. */ +public final class VasDependencyPaths { + private VasDependencyPaths() { } + + public static VirtualFile resolve(PsiFile source, VirtualFile entryDirectory, + String path, VasIncludeScanner.Kind kind) { + VirtualFile file = source.getVirtualFile(); + if (file == null || file.getParent() == null || path.startsWith("/") || path.indexOf(':') >= 0) return null; + String normalized = path.replace('\\', '/'); + if (kind != VasIncludeScanner.Kind.SYSTEM) { + VirtualFile local = file.getParent().findFileByRelativePath(normalized); + if (isFile(local)) return local; + } + Set roots = new LinkedHashSet<>(); + if (entryDirectory != null) roots.add(entryDirectory); + // A library opened independently has no selected compilation unit. Retain + // possible entry roots up to the project boundary instead of searching the disk. + for (VirtualFile parent = file.getParent(); parent != null; parent = parent.getParent()) { + roots.add(parent); + if (parent.findChild("vas-project.json") != null || parent.findChild(".git") != null + || parent.getPath().equals(source.getProject().getBasePath())) break; + } + String environment = System.getenv("VAS_INCLUDE_PATH"); + if (environment != null) { + for (String value : environment.split(java.util.regex.Pattern.quote(File.pathSeparator))) { + if (value.isBlank()) continue; + File directory = new File(value); + if (!directory.isAbsolute() && entryDirectory != null) directory = new File(entryDirectory.getPath(), value); + VirtualFile root = LocalFileSystem.getInstance().findFileByPath(directory.getPath().replace('\\', '/')); + if (root != null) roots.add(root); + } + } + Set matches = new LinkedHashSet<>(); + for (VirtualFile root : roots) { + ProgressManager.checkCanceled(); + VirtualFile target = root.findFileByRelativePath(normalized); + if (isFile(target)) matches.add(target); + } + return matches.size() == 1 ? matches.iterator().next() : null; + } + + private static boolean isFile(VirtualFile file) { + return file != null && file.isValid() && !file.isDirectory(); + } +} diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasIncludeScanner.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasIncludeScanner.java index e450142d0..41d684add 100644 --- a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasIncludeScanner.java +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasIncludeScanner.java @@ -7,13 +7,18 @@ import java.util.List; /** - * Bounded dependency extraction matching scriptbuilder's ordinary #include syntax. + * Bounded extraction of VAS module imports and quoted/angle includes. * Directive names touch '#'; a single quoted value may follow immediately or after * whitespace, including newlines. Comments are not whitespace within a directive. * Unknown preprocessing is reported, never treated as a complete dependency graph. */ public final class VasIncludeScanner { - public record Include(String path, int offset, int pathStart, int pathEnd, int end) { } + public enum Kind { QUOTED, SYSTEM, MODULE } + public record Include(String path, int offset, int pathStart, int pathEnd, int end, Kind kind) { + public Include(String path, int offset, int pathStart, int pathEnd, int end) { + this(path, offset, pathStart, pathEnd, end, Kind.QUOTED); + } + } public record Problem(int offset, String message) { } public record Result(List includes, List problems) { public Result { @@ -90,6 +95,7 @@ public static Result scan(CharSequence source) { default -> "Unsupported preprocessor directive #" + directive; }; problems.add(new Problem(start, reason)); + offset = lineEnd(source, offset); continue; } // scriptbuilder skips one tokenizer whitespace token. A BOM is @@ -101,6 +107,16 @@ public static Result scan(CharSequence source) { offset++; } } + if (offset < length && source.charAt(offset) == '<') { + int pathStart = ++offset; + while (offset < length && source.charAt(offset) != '>' && !isWhitespace(source.charAt(offset))) offset++; + if (offset < length && offset > pathStart && source.charAt(offset) == '>') { + includes.add(new Include(source.subSequence(pathStart, offset).toString(), start, pathStart, offset, ++offset, Kind.SYSTEM)); + } else { + problems.add(new Problem(start, "Invalid angle include path")); + } + continue; + } if (offset == length || source.charAt(offset) != '\'' && source.charAt(offset) != '"') { problems.add(new Problem(start, "Expected a quoted include path")); continue; @@ -124,8 +140,37 @@ public static Result scan(CharSequence source) { } else if (isIdentifierPart(character)) { int start = offset; offset = identifierEnd(source, offset); + String scannedWord = source.subSequence(start, offset).toString(); + if (scannedWord.equals("import")) { + int nameStart = skipTrivia(source, offset); + int cursor = nameStart; + StringBuilder path = new StringBuilder(); + boolean completeName = false; + while (cursor < length && isIdentifierPart(source.charAt(cursor)) && !isDigit(source.charAt(cursor), 10)) { + int nameEnd = identifierEnd(source, cursor); + String part = source.subSequence(cursor, nameEnd).toString(); + if (VasKeywords.RESERVED.contains(part)) break; + if (!path.isEmpty()) path.append('/'); + path.append(part); + cursor = skipTrivia(source, nameEnd); + if (cursor < length && source.charAt(cursor) == '.') cursor = skipTrivia(source, cursor + 1); + else { completeName = true; break; } + } + if (completeName && !path.isEmpty() && cursor < length && source.charAt(cursor) == ';') { + if (bracketDepth > 0 || parenthesisDepth > 0 || !containerBlocks.isEmpty()) { + problems.add(new Problem(start, "Module imports must be at file scope")); + } else { + int nameEnd = cursor; + while (nameEnd > nameStart && isWhitespace(source.charAt(nameEnd - 1))) nameEnd--; + includes.add(new Include(path + ".vas", start, nameStart, nameEnd, cursor + 1, Kind.MODULE)); + } + offset = cursor + 1; + statementStart = true; + continue; + } + } if (bracketDepth == 0) { - String token = source.subSequence(start, offset).toString(); + String token = scannedWord; if (statementStart && (token.equals("class") || token.equals("interface") || token.equals("namespace"))) { containerHeader = true; @@ -164,6 +209,20 @@ public static Result scan(CharSequence source) { return new Result(includes, problems); } + private static int skipTrivia(CharSequence source, int offset) { + for (;;) { + while (offset < source.length() && isWhitespace(source.charAt(offset))) offset++; + if (startsWith(source, offset, "//")) { offset = lineEnd(source, offset + 2); continue; } + if (startsWith(source, offset, "/*")) { + int end = offset + 2; + while (end < source.length() && !startsWith(source, end, "*/")) end++; + offset = Math.min(source.length(), end + 2); + continue; + } + return offset; + } + } + private static Quoted quoted(CharSequence source, int start) { int length = source.length(); boolean heredoc = startsWith(source, start, "\"\"\""); diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasMacroScanner.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasMacroScanner.java new file mode 100644 index 000000000..66566904b --- /dev/null +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasMacroScanner.java @@ -0,0 +1,33 @@ +package com.verseangelscript.rider.index; + +import com.verseangelscript.rider.lang.VasLexer; +import com.verseangelscript.rider.lang.VasTypes; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + +/** Source declarations only: conditional activation and expansion belong to the compiler. */ +public final class VasMacroScanner { + public record Macro(String name, int offset, String declaration) { } + private static final Pattern DEFINE = Pattern.compile("^#define[ \\t]+([A-Za-z_][A-Za-z_0-9]*)(.*)"); + + private VasMacroScanner() { } + + public static List scan(CharSequence source) { + List result = new ArrayList<>(); + VasLexer lexer = new VasLexer(); + lexer.start(source); + while (lexer.getTokenType() != null) { + if (lexer.getTokenType() == VasTypes.PREPROCESSOR) { + String text = source.subSequence(lexer.getTokenStart(), lexer.getTokenEnd()).toString(); + var match = DEFINE.matcher(text); + if (match.find()) { + result.add(new Macro(match.group(1), lexer.getTokenStart() + match.start(1), text)); + } + } + lexer.advance(); + } + return List.copyOf(result); + } +} diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolIndex.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolIndex.java index eaba7ae73..16d303d70 100644 --- a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolIndex.java +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolIndex.java @@ -31,6 +31,9 @@ public final class VasSymbolIndex extends ScalarIndexExtension { names.put(symbol.name(), null); } } + for (VasMacroScanner.Macro macro : VasMacroScanner.scan(inputData.getContentAsText())) { + names.put(macro.name(), null); + } return names; }; } @@ -52,6 +55,6 @@ public boolean dependsOnFileContent() { @Override public int getVersion() { - return 4; + return 6; } } diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolKind.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolKind.java index 0a1cac492..ff610482e 100644 --- a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolKind.java +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolKind.java @@ -4,6 +4,7 @@ public enum VasSymbolKind { CLASS("class"), INTERFACE("interface"), ENUM("enum"), + ENUM_MEMBER("enum value"), NAMESPACE("namespace"), TYPE_ALIAS("type alias"), FUNCTION("function"), diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolResolver.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolResolver.java index afe261d84..feae7db78 100644 --- a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolResolver.java +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolResolver.java @@ -4,13 +4,15 @@ import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; -import com.intellij.psi.PsiReference; import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.psi.util.CachedValuesManager; +import com.intellij.psi.util.CachedValueProvider; +import com.intellij.psi.util.PsiModificationTracker; import com.intellij.util.indexing.FileBasedIndex; import org.jetbrains.annotations.NotNull; @@ -70,6 +72,12 @@ private VasSymbolResolver() { if (psiFile == null) { continue; } + for (VasMacroScanner.Macro macro : VasMacroScanner.scan(psiFile.getText())) { + if (macro.name().equals(name)) { + PsiElement element = psiFile.findElementAt(macro.offset()); + if (element != null) declarations.add(element); + } + } for (VasSymbol symbol : VasSymbolScanner.scan(psiFile.getText())) { if (symbol.name().equals(name) && symbol.isProjectVisible()) { PsiElement element = psiFile.findElementAt(symbol.offset()); @@ -83,16 +91,41 @@ private VasSymbolResolver() { } public static @NotNull List findDeclarations(@NotNull PsiElement usage) { - PsiFile file = usage.getContainingFile(); - if (file == null) { - return List.of(); + return selectDeclarations(usage, true); + } + + /** Navigation may show known source candidates; destructive rename still needs complete coverage. */ + public static @NotNull List findNavigationDeclarations(@NotNull PsiElement usage) { + List symbols = selectDeclarations(usage, false); + if (!symbols.isEmpty() || usage.getContainingFile() == null) return symbols; + return findMacroDeclarations(usage.getContainingFile(), usage.getText()); + } + + public static List findMacroDeclarations(PsiFile source, String name) { + List macros = new ArrayList<>(); + for (PsiFile file : navigationFiles(source)) { + for (VasMacroScanner.Macro macro : VasMacroScanner.scan(file.getText())) { + if (macro.name().equals(name)) { + PsiElement target = file.findElementAt(macro.offset()); + if (target != null) macros.add(target); + } + } } + return macros; + } + + public static List navigationFiles(PsiFile source) { + List files = new ArrayList<>(); + files.add(source); + files.addAll(inspectDependencyClosure(source).includedFiles()); + return files; + } + private static List selectDeclarations(PsiElement usage, boolean requireComplete) { + PsiFile file = usage.getContainingFile(); + if (file == null) return List.of(); DependencyClosure closure = inspectDependencyClosure(file); - if (!closure.complete()) { - // Missing dependencies may contain another viable declaration. - return List.of(); - } + if (requireComplete && !closure.complete()) return List.of(); List> source = candidatesInFile(file); List> included = new ArrayList<>(); closure.includedFiles().forEach(includedFile -> included.addAll(candidatesInFile(includedFile))); @@ -101,6 +134,10 @@ private VasSymbolResolver() { } private static List> candidatesInFile(PsiFile file) { + return CachedValuesManager.getCachedValue(file, () -> CachedValueProvider.Result.create(computeCandidates(file), file)); + } + + private static List> computeCandidates(PsiFile file) { List> candidates = new ArrayList<>(); for (VasSymbol symbol : VasSymbolScanner.scan(file.getText())) { PsiElement element = file.findElementAt(symbol.offset()); @@ -131,6 +168,11 @@ private static List> candidatesInFile(P * callbacks or conditional compilation configuration. */ public static @NotNull DependencyClosure inspectDependencyClosure(@NotNull PsiFile sourceFile) { + return CachedValuesManager.getCachedValue(sourceFile, () -> CachedValueProvider.Result.create( + computeDependencyClosure(sourceFile), PsiModificationTracker.MODIFICATION_COUNT, VirtualFileManager.VFS_STRUCTURE_MODIFICATIONS)); + } + + private static DependencyClosure computeDependencyClosure(PsiFile sourceFile) { List includedFiles = new ArrayList<>(); List problems = new ArrayList<>(); Set visited = new HashSet<>(); @@ -140,9 +182,16 @@ private static List> candidatesInFile(P } pending.add(sourceFile); PsiManager psiManager = PsiManager.getInstance(sourceFile.getProject()); + VirtualFile entryDirectory = sourceFile.getVirtualFile() == null ? null : sourceFile.getVirtualFile().getParent(); + int sourceBytes = 0; while (!pending.isEmpty()) { ProgressManager.checkCanceled(); PsiFile file = pending.removeFirst(); + sourceBytes += file.getTextLength(); + if (visited.size() > 256 || sourceBytes > 16 * 1024 * 1024) { + problems.add(new DependencyProblem(file, 0, "Editor dependency budget exceeded")); + break; + } VasIncludeScanner.Result scan = VasIncludeScanner.scan(file.getText()); for (VasIncludeScanner.Problem problem : scan.problems()) { problems.add(new DependencyProblem(file, problem.offset(), problem.message())); @@ -160,11 +209,17 @@ private static List> candidatesInFile(P problems.add(new DependencyProblem(file, include.offset(), "Unsupported include path: " + path)); continue; } - VirtualFile included = virtualFile.getParent().findFileByRelativePath(path.replace('\\', '/')); + VirtualFile included = VasDependencyPaths.resolve(file, entryDirectory, path, include.kind()); if (included == null || !included.isValid() || included.isDirectory()) { problems.add(new DependencyProblem(file, include.offset(), "Unresolved include: " + path)); continue; } + VirtualFile local = virtualFile.getParent().findFileByRelativePath(path.replace('\\', '/')); + VirtualFile entry = entryDirectory == null ? null : entryDirectory.findFileByRelativePath(path.replace('\\', '/')); + if (include.kind() == VasIncludeScanner.Kind.SYSTEM && System.getenv("VAS_INCLUDE_PATH") != null + || !included.equals(entry) && (include.kind() == VasIncludeScanner.Kind.SYSTEM || !included.equals(local))) { + problems.add(new DependencyProblem(file, include.offset(), "Editor search hints require compiler entry-root verification")); + } if (included.getFileType() != com.verseangelscript.rider.VasFileType.INSTANCE) { problems.add(new DependencyProblem(file, include.offset(), "Include is not a VAS source: " + path)); continue; @@ -224,7 +279,7 @@ && findIncludedDeclarations(source, declaration.getText()).stream() return Optional.empty(); } int offset = element.getTextOffset(); - return VasSymbolScanner.scan(file.getText()).stream() + return candidatesInFile(file).stream().map(VasSymbolSelection.Candidate::symbol) .filter(symbol -> symbol.offset() == offset) .findFirst(); } @@ -333,9 +388,8 @@ private static boolean compatibleContainers(String left, String right) { public static @NotNull List findCallers(@NotNull PsiElement callable) { LinkedHashSet callers = new LinkedHashSet<>(); - for (PsiReference reference : ReferencesSearch.search(callable).findAll()) { - findEnclosingFunction(reference.getElement()).ifPresent(callers::add); - } + VasUsageSearch.process(callable, com.intellij.psi.search.PsiSearchHelper.getInstance(callable.getProject()).getUseScope(callable), + usage -> { findEnclosingFunction(usage).ifPresent(callers::add); return true; }); return List.copyOf(callers); } @@ -358,7 +412,7 @@ private static boolean compatibleContainers(String left, String right) { if (findSymbol(identifier).isPresent()) { continue; } - List targets = findDeclarations(identifier); + List targets = findNavigationDeclarations(identifier); if (targets.size() != 1) { continue; } diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolScanner.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolScanner.java index 0f9dbeca7..3f0ac4103 100644 --- a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolScanner.java +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolScanner.java @@ -39,6 +39,14 @@ private VasSymbolScanner() { Set functionBodies = functionBodies(tokens, lifecycleNames); Map containerScopes = containerScopes(tokens); Deque braceStack = new ArrayDeque<>(); + Set enumBodies = new HashSet<>(); + for (int index = 0; index < tokens.size(); index++) { + if (!"enum".equals(tokens.get(index).text())) continue; + int cursor = index + 1; + while (cursor < tokens.size() && tokens.get(cursor).type() != VasTypes.LBRACE && !";".equals(tokens.get(cursor).text())) cursor++; + if (cursor < tokens.size() && tokens.get(cursor).type() == VasTypes.LBRACE) enumBodies.add(cursor); + } + int parenthesisDepth = 0, bracketDepth = 0; for (int index = 0; index < tokens.size(); index++) { Token token = tokens.get(index); @@ -97,7 +105,15 @@ private VasSymbolScanner() { } } else if (token.type() == VasTypes.IDENTIFIER) { Token next = tokenAt(tokens, index + 1); - if (next != null && next.type() == VasTypes.LPAREN + if (!braceStack.isEmpty() && enumBodies.contains(braceStack.getLast()) && parenthesisDepth == 0 && bracketDepth == 0 + && (index == braceStack.getLast() + 1 || ",".equals(tokens.get(index - 1).text())) + && next != null && (next.type() == VasTypes.RBRACE || Set.of(",", "=").contains(next.text()))) { + String enumType = containerName(braceStack, containerScopes); + int separator = enumType.lastIndexOf("::"); + String owner = separator < 0 ? "" : enumType.substring(0, separator); + add(symbols, declarationOffsets, token, VasSymbolKind.ENUM_MEMBER, braceDepth, -1, -1, + true, true, owner, enumType, -1, -1, List.of()); + } else if (next != null && next.type() == VasTypes.LPAREN && looksLikeFunctionDeclaration(tokens, index)) { int bodyIndex = functionBodyIndex(tokens, index); Scope bodyScope = scopeForBrace(tokens, bodyIndex, matchingBraces); @@ -143,9 +159,11 @@ && looksLikeFunctionDeclaration(tokens, index)) { } } - if (token.type() == VasTypes.LBRACE) { - braceStack.addLast(index); - } + if (token.type() == VasTypes.LBRACE) braceStack.addLast(index); + if (token.type() == VasTypes.LPAREN) parenthesisDepth++; + if (token.type() == VasTypes.RPAREN) parenthesisDepth = Math.max(0, parenthesisDepth - 1); + if (token.type() == VasTypes.LBRACKET) bracketDepth++; + if (token.type() == VasTypes.RBRACKET) bracketDepth = Math.max(0, bracketDepth - 1); } return List.copyOf(symbols); } @@ -286,6 +304,13 @@ && looksLikeFunctionDeclaration(tokens, index) } private static boolean looksLikeFunctionDeclaration(List tokens, int nameIndex) { + if (tokens instanceof TokenList analyzed) { + return analyzed.functionDeclarations.computeIfAbsent(nameIndex, index -> computeFunctionDeclaration(tokens, index)); + } + return computeFunctionDeclaration(tokens, nameIndex); + } + + private static boolean computeFunctionDeclaration(List tokens, int nameIndex) { Token previous = tokenAt(tokens, nameIndex - 1); if (previous == null || NON_DECLARATION_CALL_PREFIXES.contains(previous.text())) { return false; @@ -308,7 +333,10 @@ private static boolean looksLikeFunctionDeclaration(List tokens, int name tailIndex++; } Token tail = tokenAt(tokens, tailIndex); - if (tail == null || !(tail.type() == VasTypes.LBRACE || ";".equals(tail.text()))) { + boolean functionImport = tail != null && "from".equals(tail.text()) + && tokenAt(tokens, tailIndex + 1) != null && tokens.get(tailIndex + 1).type() == VasTypes.STRING + && tokenAt(tokens, tailIndex + 2) != null && ";".equals(tokens.get(tailIndex + 2).text()); + if (tail == null || !(tail.type() == VasTypes.LBRACE || ";".equals(tail.text()) || functionImport)) { return false; } @@ -320,6 +348,10 @@ private static boolean looksLikeFunctionDeclaration(List tokens, int name if (typeStart < 0 || !isStatementDeclarationHead(tokens, typeStart)) { return false; } + if (tokens instanceof TokenList analyzed) { + int brace = analyzed.enclosingBrace[typeStart]; + return brace < 0 || containerScopes(tokens).containsKey(brace); + } Deque braces = new ArrayDeque<>(); for (int index = 0; index < typeStart; index++) { if (tokens.get(index).type() == VasTypes.LBRACE) { @@ -459,7 +491,7 @@ private static boolean isParameterDeclarationHead(List tokens, int typeSt private static boolean isStatementDeclarationHead(List tokens, int typeStart) { int head = typeStart - 1; while (head >= 0) { - if (Set.of("private", "protected", "public", "shared", "external", "explicit") + if (Set.of("private", "protected", "public", "shared", "external", "explicit", "import") .contains(tokens.get(head).text())) { head--; } else if (tokens.get(head).type() == VasTypes.RBRACKET) { @@ -560,6 +592,7 @@ && looksLikeVariableDeclaration(tokens, index)) { } private static int matchingRightParen(List tokens, int leftParenIndex) { + if (tokens instanceof TokenList analyzed) return analyzed.parenthesisPairs.getOrDefault(leftParenIndex, -1); int depth = 0; for (int index = leftParenIndex; index < tokens.size(); index++) { IElementType type = tokens.get(index).type(); @@ -573,6 +606,7 @@ private static int matchingRightParen(List tokens, int leftParenIndex) { } private static Map matchingBraces(List tokens) { + if (tokens instanceof TokenList analyzed) return analyzed.bracePairs; Map pairs = new HashMap<>(); Deque stack = new ArrayDeque<>(); for (int index = 0; index < tokens.size(); index++) { @@ -603,6 +637,14 @@ && tokenAt(tokens, index + 1).type() == VasTypes.LPAREN } private static Map containerScopes(List tokens) { + if (tokens instanceof TokenList analyzed) { + if (analyzed.containers == null) analyzed.containers = computeContainerScopes(tokens); + return analyzed.containers; + } + return computeContainerScopes(tokens); + } + + private static Map computeContainerScopes(List tokens) { Map scopes = new HashMap<>(); for (int index = 0; index < tokens.size(); index++) { Token token = tokens.get(index); @@ -969,7 +1011,7 @@ private static Token tokenAt(List tokens, int index) { private static List tokenize(CharSequence source) { VasLexer lexer = new VasLexer(); lexer.start(source); - List tokens = new ArrayList<>(); + TokenList tokens = new TokenList(); while (lexer.getTokenType() != null) { IElementType type = lexer.getTokenType(); if (type != TokenType.WHITE_SPACE && type != VasTypes.COMMENT @@ -995,9 +1037,32 @@ private static List tokenize(CharSequence source) { } lexer.advance(); } + tokens.finish(); return tokens; } + /** Per-scan immutable topology; no global state or cross-document lifetime. */ + private static final class TokenList extends ArrayList { + private final Map bracePairs = new HashMap<>(); + private final Map parenthesisPairs = new HashMap<>(); + private final Map functionDeclarations = new HashMap<>(); + private Map containers; + private int[] enclosingBrace; + + private void finish() { + enclosingBrace = new int[size()]; + Deque braces = new ArrayDeque<>(), parentheses = new ArrayDeque<>(); + for (int index = 0; index < size(); index++) { + enclosingBrace[index] = braces.isEmpty() ? -1 : braces.getLast(); + IElementType type = get(index).type(); + if (type == VasTypes.LBRACE) braces.addLast(index); + else if (type == VasTypes.RBRACE && !braces.isEmpty()) bracePairs.put(braces.removeLast(), index); + if (type == VasTypes.LPAREN) parentheses.addLast(index); + else if (type == VasTypes.RPAREN && !parentheses.isEmpty()) parenthesisPairs.put(parentheses.removeLast(), index); + } + } + } + private record Token(IElementType type, String text, int start, int end) { } diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolSelection.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolSelection.java index 12b7a6a07..92101a564 100644 --- a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolSelection.java +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasSymbolSelection.java @@ -128,7 +128,8 @@ private static String resolveContainer( return qualified; } return matches.size() == 1 && (matches.get(0).symbol().kind() == VasSymbolKind.CLASS - || matches.get(0).symbol().kind() == VasSymbolKind.INTERFACE) ? qualified : null; + || matches.get(0).symbol().kind() == VasSymbolKind.INTERFACE + || allowNamespace && matches.get(0).symbol().kind() == VasSymbolKind.ENUM) ? qualified : null; } } return null; @@ -136,7 +137,8 @@ private static String resolveContainer( private static List> inContainer(List> visible, String name, String container) { return visible.stream().filter(candidate -> candidate.symbol().name().equals(name) - && candidate.symbol().container().equals(container)).toList(); + && (candidate.symbol().container().equals(container) + || candidate.symbol().kind() == VasSymbolKind.ENUM_MEMBER && candidate.symbol().declaredType().equals(container))).toList(); } private static List enclosingContainers(String container) { diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasUsageSearch.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasUsageSearch.java new file mode 100644 index 000000000..a79cd2cb3 --- /dev/null +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/index/VasUsageSearch.java @@ -0,0 +1,35 @@ +package com.verseangelscript.rider.index; + +import com.intellij.openapi.progress.ProgressManager; +import com.intellij.psi.PsiElement; +import com.intellij.psi.search.PsiSearchHelper; +import com.intellij.psi.search.SearchScope; +import com.intellij.psi.search.UsageSearchContext; +import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.util.Processor; +import com.verseangelscript.rider.lang.VasIdentifierPsiElement; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** Read-only source usages. Rename continues to use its complete-coverage references. */ +public final class VasUsageSearch { + private VasUsageSearch() { } + + public static boolean process(PsiElement target, SearchScope scope, Processor processor) { + if (!(target instanceof VasIdentifierPsiElement) || VasSymbolResolver.findSymbol(target).isEmpty()) return true; + Set seen = new HashSet<>(); + return PsiSearchHelper.getInstance(target.getProject()).processElementsWithWord((element, offset) -> { + ProgressManager.checkCanceled(); + PsiElement leaf = element.getContainingFile().findElementAt(element.getTextOffset() + offset); + VasIdentifierPsiElement usage = PsiTreeUtil.getParentOfType(leaf, VasIdentifierPsiElement.class, false); + if (usage == null || !usage.getText().equals(target.getText()) || usage.isEquivalentTo(target) + || VasSymbolResolver.findSymbol(usage).isPresent() || !seen.add(usage)) return true; + List candidates = VasSymbolResolver.findNavigationDeclarations(usage); + // Retain lexical/receiver/arity filtering; never select an ambiguous same-name symbol. + return candidates.size() != 1 || !target.getManager().areElementsEquivalent(candidates.getFirst(), target) + || processor.process(usage); + }, scope, target.getText(), UsageSearchContext.IN_CODE, true); + } +} diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasBackspaceHandler.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasBackspaceHandler.java new file mode 100644 index 000000000..8ab20dd48 --- /dev/null +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasBackspaceHandler.java @@ -0,0 +1,25 @@ +package com.verseangelscript.rider.lang; + +import com.intellij.codeInsight.editorActions.BackspaceHandlerDelegate; +import com.intellij.openapi.editor.Editor; +import com.intellij.psi.PsiFile; +import com.verseangelscript.rider.VasFileType; + +public final class VasBackspaceHandler extends BackspaceHandlerDelegate { + private boolean paired; + @Override public void beforeCharDeleted(char c, PsiFile file, Editor editor) { + int offset = editor.getCaretModel().getOffset(); var text = editor.getDocument().getCharsSequence(); + paired = file.getFileType() == VasFileType.INSTANCE && offset > 0 && offset < text.length() + && VasTypedHandler.closing(c) != 0 && text.charAt(offset) == VasTypedHandler.closing(c) + && VasTypedHandler.inCode(text, offset - 1); + } + @Override public boolean charDeleted(char c, PsiFile file, Editor editor) { + if (!paired) return false; + paired = false; + int offset = editor.getCaretModel().getOffset(); var document = editor.getDocument(); + if (offset < document.getTextLength() && document.getCharsSequence().charAt(offset) == VasTypedHandler.closing(c)) { + document.deleteString(offset, offset + 1); return true; + } + return false; + } +} diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasCallNavigation.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasCallNavigation.java index 97d33804b..a7c20c4d0 100644 --- a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasCallNavigation.java +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasCallNavigation.java @@ -62,7 +62,7 @@ static PsiElement resolveCallable(PsiElement source) { .orElse(false)) { return source; } - List candidates = VasSymbolResolver.findDeclarations(source).stream() + List candidates = VasSymbolResolver.findNavigationDeclarations(source).stream() .filter(candidate -> VasSymbolResolver.findSymbol(candidate) .map(symbol -> symbol.kind() == VasSymbolKind.FUNCTION) .orElse(false)) diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasCallSupport.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasCallSupport.java new file mode 100644 index 000000000..027df4924 --- /dev/null +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasCallSupport.java @@ -0,0 +1,95 @@ +package com.verseangelscript.rider.lang; + +import com.intellij.psi.PsiFile; +import com.verseangelscript.rider.index.*; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; + +public final class VasCallSupport { + public record Call(String name, int nameOffset, int open, int parameter) { } + public record Signature(String label, List parameters) { } + private record Word(String text, int start) { } + private VasCallSupport() { } + + public static Call callAt(CharSequence text, int offset) { + VasLexer lexer = new VasLexer(); lexer.start(text); + var stack = new ArrayDeque(); String previous = ""; int previousOffset = 0; + while (lexer.getTokenType() != null && lexer.getTokenStart() < offset) { + var type = lexer.getTokenType(); + if (type == VasTypes.STRING || type == VasTypes.COMMENT || type == VasTypes.PREPROCESSOR + || type == com.intellij.psi.TokenType.WHITE_SPACE) { lexer.advance(); continue; } + String word = text.subSequence(lexer.getTokenStart(), lexer.getTokenEnd()).toString(); + if (word.equals("(") || word.equals("[") || word.equals("{")) + stack.push(new Call(word.equals("(") ? previous : "", previousOffset, lexer.getTokenStart(), 0)); + else if (word.equals(")") || word.equals("]") || word.equals("}")) { if (!stack.isEmpty()) stack.pop(); } + else if (word.equals(",") && !stack.isEmpty()) { + Call call = stack.pop(); stack.push(new Call(call.name(), call.nameOffset(), call.open(), call.parameter() + 1)); + } + previous = word; previousOffset = lexer.getTokenStart(); lexer.advance(); + } + for (Call call : stack) if (!call.name().isEmpty() && Character.isJavaIdentifierStart(call.name().charAt(0)) + && !List.of("if", "while", "for", "switch", "catch").contains(call.name())) return call; + return null; + } + + public static Signature signature(String text, VasSymbol symbol) { + int open = text.indexOf('(', symbol.offset()); + if (open < 0) return new Signature(symbol.name() + "()", List.of()); + String suffix = text.substring(open, Math.min(text.length(), open + 8192)); + VasLexer lexer = new VasLexer(); lexer.start(suffix); + int depth = 0, end = open; + while (lexer.getTokenType() != null) { + if (lexer.getTokenType() == VasTypes.LPAREN) depth++; + if (lexer.getTokenType() == VasTypes.RPAREN && --depth == 0) { end = open + lexer.getTokenEnd(); break; } + lexer.advance(); + } + if (end <= open) return new Signature(symbol.name() + "(...)", List.of()); + String label = symbol.qualifiedName() + text.substring(open, end).replaceAll("\\s+", " "); + return signature(label); + } + + public static Signature signature(String label) { + List ranges = new ArrayList<>(); int open = label.indexOf('('), begin = open + 1, nesting = 0; + if (open < 0) return new Signature(label, ranges); + boolean quoted = false; char quote = 0; + for (int i = begin; i < label.length(); i++) { + char c = label.charAt(i); + if (quoted) { if (c == '\\') i++; else if (c == quote) quoted = false; continue; } + if (c == '"' || c == '\'') { quoted = true; quote = c; continue; } + if (c == '(' || c == '[' || c == '<' || c == '{') nesting++; + else if (c == ')' && nesting == 0 || c == ',' && nesting == 0) { + int start = begin, end = i; + while (start < end && Character.isWhitespace(label.charAt(start))) start++; + while (end > start && Character.isWhitespace(label.charAt(end - 1))) end--; + if (end > start) ranges.add(new int[] {start, end}); + begin = i + 1; if (c == ')') break; + } else if (c == ')' || c == ']' || c == '>' || c == '}') nesting--; + } + return new Signature(label, List.copyOf(ranges)); + } + + public static List signatures(PsiFile file, Call call) { + List result = new ArrayList<>(); + if (call == null) return result; + var local = VasSymbolScanner.scan(file.getText()); var others = new ArrayList(); + var sourceTexts = new java.util.HashMap(); + for (var symbol : local) sourceTexts.put(symbol, file.getText()); + var files = VasSymbolResolver.navigationFiles(file); + for (PsiFile dependency : files) if (!dependency.equals(file)) { + String text = dependency.getText(); var symbols = VasSymbolScanner.scan(text); others.addAll(symbols); + for (var symbol : symbols) sourceTexts.putIfAbsent(symbol, text); + } + var usage = VasSymbolScanner.usageContext(file.getText(), call.nameOffset()); + for (VasSymbol symbol : VasCompletionSelection.select(local, others, call.nameOffset(), usage)) { + if (symbol.kind() != VasSymbolKind.FUNCTION || !symbol.name().equals(call.name())) continue; + Signature signature = signature(sourceTexts.get(symbol), symbol); + if (result.stream().noneMatch(s -> s.label().equals(signature.label()))) result.add(signature); + } + if (result.isEmpty() && usage.access() == VasUsageContext.Access.UNQUALIFIED) { + String runtime = VasRuntimeSymbols.ALL.get(call.name()); + if (runtime != null && runtime.contains("(")) result.add(signature(runtime)); + } + return result; + } +} diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasColorSettingsPage.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasColorSettingsPage.java index ae590ec76..b28932a6c 100644 --- a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasColorSettingsPage.java +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasColorSettingsPage.java @@ -16,6 +16,11 @@ public final class VasColorSettingsPage implements ColorSettingsPage { private static final AttributesDescriptor[] DESCRIPTORS = { new AttributesDescriptor("Keyword", VasSyntaxHighlighter.KEYWORD), new AttributesDescriptor("Identifier", VasSyntaxHighlighter.IDENTIFIER), + new AttributesDescriptor("Type", VasSemanticAnnotator.TYPE), + new AttributesDescriptor("Function", VasSemanticAnnotator.FUNCTION), + new AttributesDescriptor("Namespace", VasSemanticAnnotator.NAMESPACE), + new AttributesDescriptor("Variable declaration", VasSemanticAnnotator.VARIABLE), + new AttributesDescriptor("Macro", VasSemanticAnnotator.MACRO), new AttributesDescriptor("Number", VasSyntaxHighlighter.NUMBER), new AttributesDescriptor("String", VasSyntaxHighlighter.STRING), new AttributesDescriptor("Comment", VasSyntaxHighlighter.COMMENT), diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasCompletionContributor.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasCompletionContributor.java index 240979c72..ed9d26b54 100644 --- a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasCompletionContributor.java +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasCompletionContributor.java @@ -10,6 +10,11 @@ import com.intellij.patterns.PlatformPatterns; import com.intellij.util.ProcessingContext; import com.verseangelscript.rider.index.VasSymbol; +import com.verseangelscript.rider.index.VasSymbolKind; +import com.verseangelscript.rider.index.VasUsageContext; +import com.verseangelscript.rider.index.VasCompletionSelection; +import java.util.ArrayList; +import com.verseangelscript.rider.index.VasMacroScanner; import com.verseangelscript.rider.index.VasSymbolResolver; import com.verseangelscript.rider.index.VasSymbolScanner; import org.jetbrains.annotations.NotNull; @@ -37,33 +42,58 @@ protected void addCompletions( @NotNull CompletionResultSet result ) { Set added = new HashSet<>(); - for (String keyword : VasKeywords.ALL) { - result.addElement( - LookupElementBuilder.create(keyword) - .bold() - .withTypeText("VAS keyword", true) - ); - added.add(keyword); + var original = parameters.getOriginalFile(); + String text = original.getText(); + int offset = Math.min(parameters.getOffset(), text.length()); + int wordStart = offset; + while (wordStart > 0 && Character.isJavaIdentifierPart(text.charAt(wordStart - 1))) wordStart--; + var usage = VasSymbolScanner.usageContext(text.substring(0, wordStart) + "__VasCompletion__;", wordStart); + boolean plain = usage.access() == VasUsageContext.Access.UNQUALIFIED; + var local = VasSymbolScanner.scan(text); + var dependencies = new ArrayList(); + var sourceTexts = new java.util.HashMap(); + for (var symbol : local) sourceTexts.put(symbol, text); + var files = VasSymbolResolver.navigationFiles(original); + for (var file : files) if (!file.equals(original)) { + String sourceText = file.getText(); var symbols = VasSymbolScanner.scan(sourceText); + dependencies.addAll(symbols); + for (var symbol : symbols) sourceTexts.putIfAbsent(symbol, sourceText); } - - for (VasSymbol symbol : VasSymbolScanner.scan(parameters.getOriginalFile().getText())) { - if (added.add(symbol.name())) { - result.addElement(symbolLookup(symbol.name(), symbol.kind().displayName(), true)); + for (var symbol : VasCompletionSelection.select(local, dependencies, wordStart, usage)) { + String identity = symbol.kind() == VasSymbolKind.FUNCTION ? symbol.signature() : symbol.name(); + if (added.add(identity)) { + var item = symbolLookup(symbol.name(), symbol.kind().displayName(), local.contains(symbol)); + if (symbol.kind() == VasSymbolKind.FUNCTION) { + String label = VasCallSupport.signature(sourceTexts.get(symbol), symbol).label(); + item = item.withTailText(" " + label, true).withInsertHandler((insertion, selected) -> insertCall(insertion, symbol.requiredParameterCount() > 0)); + } else item = item.withTailText(" " + symbol.qualifiedName(), true); + result.addElement(item); + } + } + if (plain) { + for (String keyword : VasKeywords.ALL) if (added.add(keyword)) result.addElement(LookupElementBuilder.create(keyword).bold().withTypeText("VAS keyword", true)); + for (var file : files) for (var macro : VasMacroScanner.scan(file.getText())) { + if (added.add(macro.name())) result.addElement(LookupElementBuilder.create(macro.name()) + .withTypeText("VAS macro · " + file.getName(), true).withTailText(" " + macro.declaration(), true)); } } - for (var runtimeSymbol : VasRuntimeSymbols.ALL.entrySet()) { + for (var runtimeSymbol : (plain ? VasRuntimeSymbols.ALL : java.util.Map.of()).entrySet()) { if (added.add(runtimeSymbol.getKey())) { result.addElement( LookupElementBuilder.create(runtimeSymbol.getKey()) .withIcon(com.verseangelscript.rider.VasIcons.FILE) .withTailText(" " + runtimeSymbol.getValue(), true) .withTypeText("VAS runtime", true) + .withInsertHandler((insertion, selected) -> { + if (runtimeSymbol.getValue().contains("(")) insertCall(insertion, + !runtimeSymbol.getValue().contains("()")); + }) ); } } - if (!DumbService.isDumb(parameters.getPosition().getProject())) { + if (plain && parameters.getInvocationCount() > 1 && !DumbService.isDumb(parameters.getPosition().getProject())) { for (String name : VasSymbolResolver.allProjectNames( parameters.getPosition().getProject() )) { @@ -74,6 +104,17 @@ protected void addCompletions( } } + private static void insertCall(com.intellij.codeInsight.completion.InsertionContext context, boolean arguments) { + var document = context.getDocument(); int tail = context.getTailOffset(), next = tail; + while (next < document.getTextLength() && Character.isWhitespace(document.getCharsSequence().charAt(next))) next++; + if (next >= document.getTextLength() || document.getCharsSequence().charAt(next) != '(') { + document.insertString(tail, "()"); context.setTailOffset(tail + 2); + context.getEditor().getCaretModel().moveToOffset(tail + (arguments ? 1 : 2)); + } else context.getEditor().getCaretModel().moveToOffset(next + 1); + if (context.getCompletionChar() == '(') context.setAddCompletionChar(false); + com.intellij.codeInsight.AutoPopupController.getInstance(context.getProject()).autoPopupParameterInfo(context.getEditor(), null); + } + private static LookupElementBuilder symbolLookup( String name, String kind, diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasDirectNavigationProvider.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasDirectNavigationProvider.java index 22018e65e..896b8bd57 100644 --- a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasDirectNavigationProvider.java +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasDirectNavigationProvider.java @@ -30,7 +30,7 @@ public final class VasDirectNavigationProvider implements DirectNavigationProvid if (element.getNode().getElementType() != VasTypes.IDENTIFIER) { return null; } - List declarations = VasSymbolResolver.findDeclarations(element); + List declarations = VasSymbolResolver.findNavigationDeclarations(element); return declarations.size() == 1 ? declarations.get(0) : null; } } diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasEnterHandler.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasEnterHandler.java new file mode 100644 index 000000000..910b5c69b --- /dev/null +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasEnterHandler.java @@ -0,0 +1,31 @@ +package com.verseangelscript.rider.lang; + +import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegate; +import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.actionSystem.EditorActionHandler; +import com.intellij.openapi.util.Ref; +import com.intellij.psi.PsiFile; +import com.verseangelscript.rider.VasFileType; + +public final class VasEnterHandler implements EnterHandlerDelegate { + @Override public Result preprocessEnter(PsiFile file, Editor editor, Ref caretOffset, + Ref caretAdvance, DataContext data, EditorActionHandler original) { + if (file.getFileType() != VasFileType.INSTANCE || editor.getSelectionModel().hasSelection()) return Result.Continue; + var document = editor.getDocument(); var text = document.getCharsSequence(); + int offset = editor.getCaretModel().getOffset(); + if (!VasTypedHandler.inCode(text, offset)) return Result.Continue; + int start = document.getLineStartOffset(document.getLineNumber(offset)), end = start; + while (end < offset && (text.charAt(end) == ' ' || text.charAt(end) == '\t')) end++; + String indent = text.subSequence(start, end).toString(); + int previous = offset - 1; + while (previous >= start && Character.isWhitespace(text.charAt(previous))) previous--; + boolean block = previous >= start && text.charAt(previous) == '{'; + String inner = indent + (block ? "\t" : ""); + String insert = "\n" + inner; + if (block && offset < text.length() && text.charAt(offset) == '}') insert += "\n" + indent; + document.insertString(offset, insert); + editor.getCaretModel().moveToOffset(offset + 1 + inner.length()); + return Result.Stop; + } +} diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasFindUsagesHandlerFactory.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasFindUsagesHandlerFactory.java new file mode 100644 index 000000000..df9cdcbd4 --- /dev/null +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasFindUsagesHandlerFactory.java @@ -0,0 +1,34 @@ +package com.verseangelscript.rider.lang; + +import com.intellij.find.findUsages.FindUsagesHandler; +import com.intellij.find.findUsages.FindUsagesHandlerFactory; +import com.intellij.find.findUsages.FindUsagesOptions; +import com.intellij.psi.PsiElement; +import com.intellij.usageView.UsageInfo; +import com.intellij.util.Processor; +import com.verseangelscript.rider.index.VasSymbolResolver; +import com.verseangelscript.rider.index.VasUsageSearch; +import org.jetbrains.annotations.NotNull; + +public final class VasFindUsagesHandlerFactory extends FindUsagesHandlerFactory { + static PsiElement target(PsiElement element) { + if (!(element instanceof VasIdentifierPsiElement)) return null; + if (VasSymbolResolver.findSymbol(element).isPresent()) return element; + var candidates = VasSymbolResolver.findNavigationDeclarations(element); + return candidates.size() == 1 && VasSymbolResolver.findSymbol(candidates.getFirst()).isPresent() ? candidates.getFirst() : null; + } + @Override public boolean canFindUsages(@NotNull PsiElement element) { + return target(element) != null; + } + @Override public FindUsagesHandler createFindUsagesHandler(@NotNull PsiElement element, boolean forHighlightUsages) { + PsiElement target = target(element); + return target != null ? new Handler(target) : null; + } + static final class Handler extends FindUsagesHandler { + Handler(PsiElement element) { super(element); } + @Override public boolean processElementUsages(@NotNull PsiElement element, + @NotNull Processor processor, @NotNull FindUsagesOptions options) { + return VasUsageSearch.process(element, options.searchScope, usage -> processor.process(new UsageInfo(usage))); + } + } +} diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasFindUsagesProvider.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasFindUsagesProvider.java index c4a81fa03..ef1a722e7 100644 --- a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasFindUsagesProvider.java +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasFindUsagesProvider.java @@ -24,7 +24,7 @@ public final class VasFindUsagesProvider implements FindUsagesProvider { @Override public boolean canFindUsagesFor(@NotNull PsiElement element) { return element.getLanguage().isKindOf(VasLanguage.INSTANCE) - && VasSymbolResolver.findSymbol(element).isPresent(); + && VasFindUsagesHandlerFactory.target(element) != null; } @Override diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasGotoDeclarationHandler.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasGotoDeclarationHandler.java index 6d856d533..6ccff68b4 100644 --- a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasGotoDeclarationHandler.java +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasGotoDeclarationHandler.java @@ -48,10 +48,17 @@ public final class VasGotoDeclarationHandler implements GotoDeclarationHandler { PsiElement includeTarget = VasIncludeReference.resolveTarget(navigationElement); if (includeTarget != null) { targets.add(includeTarget); + } else { + String text = navigationElement.getText(); + int start = Math.max(0, Math.min(text.length(), offset - navigationElement.getTextOffset())), end = start; + while (start > 0 && Character.isJavaIdentifierPart(text.charAt(start - 1))) start--; + while (end < text.length() && Character.isJavaIdentifierPart(text.charAt(end))) end++; + if (end > start) targets.addAll(VasSymbolResolver.findMacroDeclarations( + navigationElement.getContainingFile(), text.substring(start, end))); } } if (targets.isEmpty() && elementType == VasTypes.IDENTIFIER) { - targets.addAll(VasSymbolResolver.findDeclarations(navigationElement)); + targets.addAll(VasSymbolResolver.findNavigationDeclarations(navigationElement)); } return targets.isEmpty() ? null : targets.toArray(PsiElement.EMPTY_ARRAY); } diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasGotoSymbolContributor.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasGotoSymbolContributor.java new file mode 100644 index 000000000..872ce78a6 --- /dev/null +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasGotoSymbolContributor.java @@ -0,0 +1,53 @@ +package com.verseangelscript.rider.lang; + +import com.intellij.navigation.ChooseByNameContributor; +import com.intellij.navigation.ItemPresentation; +import com.intellij.navigation.NavigationItem; +import com.intellij.openapi.fileEditor.OpenFileDescriptor; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiElement; +import com.verseangelscript.rider.VasIcons; +import com.verseangelscript.rider.index.VasMacroScanner; +import com.verseangelscript.rider.index.VasSymbolResolver; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import javax.swing.Icon; + +/** Exposes the VAS file index to Rider's native Search Everywhere / Go to Symbol UI. */ +public final class VasGotoSymbolContributor implements ChooseByNameContributor { + @Override + public String @NotNull [] getNames(Project project, boolean includeNonProjectItems) { + return VasSymbolResolver.allProjectNames(project).toArray(String[]::new); + } + + @Override + public NavigationItem @NotNull [] getItemsByName(String name, String pattern, Project project, boolean includeNonProjectItems) { + return VasSymbolResolver.findProjectDeclarations(project, name).stream() + .map(element -> new Declaration(name, element)).toArray(NavigationItem[]::new); + } + + private record Declaration(String name, PsiElement element) implements NavigationItem { + @Override public @Nullable String getName() { return name; } + @Override public @Nullable ItemPresentation getPresentation() { + return new ItemPresentation() { + @Override public @Nullable String getPresentableText() { + return VasSymbolResolver.findSymbol(element).map(symbol -> symbol.qualifiedName()).orElse(name); + } + @Override public @Nullable String getLocationString() { return element.getContainingFile().getVirtualFile().getPresentableUrl(); } + @Override public @Nullable Icon getIcon(boolean unused) { return VasIcons.FILE; } + }; + } + @Override public boolean canNavigate() { return element.isValid() && element.getContainingFile().getVirtualFile() != null; } + @Override public boolean canNavigateToSource() { return canNavigate(); } + @Override public void navigate(boolean requestFocus) { + if (!canNavigate()) return; + int offset = element.getTextOffset(); + if (element.getNode().getElementType() == VasTypes.PREPROCESSOR) { + offset = VasMacroScanner.scan(element.getContainingFile().getText()).stream().filter(macro -> macro.name().equals(name)) + .findFirst().map(VasMacroScanner.Macro::offset).orElse(offset); + } + new OpenFileDescriptor(element.getProject(), element.getContainingFile().getVirtualFile(), offset).navigate(requestFocus); + } + } +} diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasIncludeReference.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasIncludeReference.java index 2adf3afa0..de0d5db88 100644 --- a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasIncludeReference.java +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasIncludeReference.java @@ -7,19 +7,23 @@ import com.intellij.psi.PsiManager; import com.intellij.psi.PsiReferenceBase; import com.verseangelscript.rider.index.VasIncludeScanner; +import com.verseangelscript.rider.index.VasDependencyPaths; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class VasIncludeReference extends PsiReferenceBase { private final String includePath; + private final VasIncludeScanner.Kind kind; private VasIncludeReference( @NotNull PsiElement element, @NotNull TextRange range, - @NotNull String includePath + @NotNull String includePath, + @NotNull VasIncludeScanner.Kind kind ) { super(element, range, true); this.includePath = includePath; + this.kind = kind; } public static @Nullable VasIncludeReference create(@NotNull PsiElement element) { @@ -30,7 +34,7 @@ private VasIncludeReference( return new VasIncludeReference( element, new TextRange(include.pathStart(), include.pathEnd()), - include.path() + include.path(), include.kind() ); } @@ -67,7 +71,7 @@ private VasIncludeReference( || java.io.File.separatorChar != '\\' && includePath.indexOf('\\') >= 0) { return null; } - VirtualFile target = directory.findFileByRelativePath(includePath.replace('\\', '/')); + VirtualFile target = VasDependencyPaths.resolve(sourceFile, directory, includePath, kind); return target == null ? null : PsiManager.getInstance(myElement.getProject()).findFile(target); } } diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasLexer.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasLexer.java index c5db6826a..7bfb6b4f8 100644 --- a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasLexer.java +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasLexer.java @@ -118,6 +118,13 @@ private void locateToken() { return; } + Integer dependencyEnd = includeEnds.get(tokenStart); + if (current != '#' && dependencyEnd != null) { + tokenEnd = dependencyEnd; + tokenType = VasTypes.PREPROCESSOR; + return; + } + if (current == '#') { Integer includeEnd = includeEnds.get(tokenStart); if (includeEnd != null) { diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasParameterInfoHandler.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasParameterInfoHandler.java new file mode 100644 index 000000000..25ff09f35 --- /dev/null +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasParameterInfoHandler.java @@ -0,0 +1,31 @@ +package com.verseangelscript.rider.lang; + +import com.intellij.lang.parameterInfo.*; +import com.intellij.psi.PsiFile; + +public final class VasParameterInfoHandler implements ParameterInfoHandler { + @Override public PsiFile findElementForParameterInfo(CreateParameterInfoContext context) { + var call = VasCallSupport.callAt(context.getFile().getText(), context.getOffset()); + var signatures = VasCallSupport.signatures(context.getFile(), call); + if (signatures.isEmpty()) return null; + context.setItemsToShow(signatures.toArray()); + return context.getFile(); + } + @Override public void showParameterInfo(PsiFile file, CreateParameterInfoContext context) { + var call = VasCallSupport.callAt(file.getText(), context.getOffset()); + if (call != null) context.showHint(file, call.open(), this); + } + @Override public PsiFile findElementForUpdatingParameterInfo(UpdateParameterInfoContext context) { + return VasCallSupport.callAt(context.getFile().getText(), context.getOffset()) == null ? null : context.getFile(); + } + @Override public void updateParameterInfo(PsiFile file, UpdateParameterInfoContext context) { + var call = VasCallSupport.callAt(file.getText(), context.getOffset()); + if (call == null || call.open() != context.getParameterListStart()) { context.removeHint(); return; } + context.setParameterOwner(file); context.setCurrentParameter(call.parameter()); + } + @Override public void updateUI(VasCallSupport.Signature signature, ParameterInfoUIContext context) { + int index = context.getCurrentParameterIndex(); + int[] range = index >= 0 && index < signature.parameters().size() ? signature.parameters().get(index) : new int[] {-1, -1}; + context.setupUIComponentPresentation(signature.label(), range[0], range[1], false, false, false, context.getDefaultParameterColor()); + } +} diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasReferencesCodeVisionProvider.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasReferencesCodeVisionProvider.java index a37eeb7dc..38f4781fa 100644 --- a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasReferencesCodeVisionProvider.java +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasReferencesCodeVisionProvider.java @@ -4,9 +4,10 @@ import com.intellij.codeInsight.codeVision.CodeVisionRelativeOrdering; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; -import com.intellij.psi.search.searches.ReferencesSearch; +import com.intellij.psi.search.PsiSearchHelper; import com.verseangelscript.rider.VasLanguage; import com.verseangelscript.rider.index.VasSymbolResolver; +import com.verseangelscript.rider.index.VasUsageSearch; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -24,8 +25,9 @@ public boolean acceptsElement(@NotNull PsiElement element) { @Override public String getHint(@NotNull PsiElement element, @NotNull PsiFile file) { - int count = ReferencesSearch.search(element).findAll().size(); - return count + (count == 1 ? " usage" : " usages"); + int[] count = {0}; + VasUsageSearch.process(element, PsiSearchHelper.getInstance(element.getProject()).getUseScope(element), usage -> { count[0]++; return true; }); + return count[0] + (count[0] == 1 ? " usage" : " usages"); } @Override diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasRuntimeSymbols.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasRuntimeSymbols.java index a467592f8..a88960da7 100644 --- a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasRuntimeSymbols.java +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasRuntimeSymbols.java @@ -4,7 +4,8 @@ public final class VasRuntimeSymbols { public static final Map ALL = Map.ofEntries( - Map.entry("print", "void print(const string &in)"), + Map.entry("print", "void print(const string &in format, const ?&in ...) (+ primitive overloads; no newline)"), + Map.entry("println", "void println(const string &in format, const ?&in ...) (+ empty and primitive overloads)"), Map.entry("getInput", "string getInput()"), Map.entry("getCommandLineArgs", "array@ getCommandLineArgs()"), Map.entry("exec", "int exec(const string &in)"), diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasSemanticAnnotator.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasSemanticAnnotator.java new file mode 100644 index 000000000..4691fbcb3 --- /dev/null +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasSemanticAnnotator.java @@ -0,0 +1,94 @@ +package com.verseangelscript.rider.lang; + +import com.intellij.lang.annotation.AnnotationHolder; +import com.intellij.lang.annotation.Annotator; +import com.intellij.lang.annotation.HighlightSeverity; +import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; +import com.intellij.openapi.editor.colors.TextAttributesKey; +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; +import com.verseangelscript.rider.index.*; +import org.jetbrains.annotations.NotNull; + +import java.util.HashMap; +import java.util.Map; + +/** One pass per file, rather than rebuilding the dependency closure for every identifier. */ +public final class VasSemanticAnnotator implements Annotator { + public static final TextAttributesKey TYPE = key("VAS_TYPE", DefaultLanguageHighlighterColors.CLASS_NAME); + public static final TextAttributesKey FUNCTION = key("VAS_FUNCTION", DefaultLanguageHighlighterColors.FUNCTION_DECLARATION); + public static final TextAttributesKey NAMESPACE = key("VAS_NAMESPACE", DefaultLanguageHighlighterColors.METADATA); + public static final TextAttributesKey VARIABLE = key("VAS_VARIABLE", DefaultLanguageHighlighterColors.LOCAL_VARIABLE); + public static final TextAttributesKey MACRO = key("VAS_MACRO", DefaultLanguageHighlighterColors.CONSTANT); + + private static TextAttributesKey key(String name, TextAttributesKey fallback) { + return TextAttributesKey.createTextAttributesKey(name, fallback); + } + + @Override + public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) { + if (!(element instanceof PsiFile file)) return; + String text = file.getText(); + Map declarations = new HashMap<>(); + Map names = new HashMap<>(); + for (PsiFile dependency : VasSymbolResolver.navigationFiles(file)) { + for (VasSymbol symbol : VasSymbolScanner.scan(dependency.getText())) { + TextAttributesKey attributes = switch (symbol.kind()) { + case CLASS, INTERFACE, ENUM, TYPE_ALIAS -> TYPE; + case FUNCTION -> FUNCTION; + case NAMESPACE -> NAMESPACE; + case VARIABLE -> VARIABLE; + case ENUM_MEMBER -> MACRO; + }; + if (dependency.equals(file)) declarations.put(symbol.offset(), attributes); + if (symbol.isProjectVisible() && symbol.kind() != VasSymbolKind.VARIABLE) names.put(symbol.name(), attributes); + } + for (var macro : VasMacroScanner.scan(dependency.getText())) { + names.put(macro.name(), MACRO); + if (dependency.equals(file)) shade(holder, macro.offset(), macro.offset() + macro.name().length(), MACRO); + } + } + VasRuntimeSymbols.ALL.keySet().forEach(name -> names.putIfAbsent(name, FUNCTION)); + VasLexer lexer = new VasLexer(); + lexer.start(text); + while (lexer.getTokenType() != null) { + if (lexer.getTokenType() == VasTypes.IDENTIFIER) { + int start = lexer.getTokenStart(), end = lexer.getTokenEnd(); + TextAttributesKey attributes = declarations.get(start); + if (attributes == null) { + attributes = names.get(text.substring(start, end)); + // Function names in source declarations are certain; calls need a following '('. + if (attributes == FUNCTION) { + int next = end; + while (next < text.length() && Character.isWhitespace(text.charAt(next))) next++; + if (next == text.length() || text.charAt(next) != '(') attributes = null; + } + } + if (attributes != null) shade(holder, start, end, attributes); + } else if (lexer.getTokenType() == VasTypes.PREPROCESSOR && text.startsWith("import", lexer.getTokenStart())) { + String directive = text.substring(lexer.getTokenStart(), lexer.getTokenEnd()); + var imports = VasIncludeScanner.scan(directive).includes(); + if (imports.size() == 1 && imports.getFirst().kind() == VasIncludeScanner.Kind.MODULE) { + shade(holder, lexer.getTokenStart(), lexer.getTokenStart() + 6, VasSyntaxHighlighter.KEYWORD); + shade(holder, lexer.getTokenStart() + imports.getFirst().pathStart(), lexer.getTokenStart() + imports.getFirst().pathEnd(), NAMESPACE); + } + } else if (lexer.getTokenType() == VasTypes.PREPROCESSOR && text.charAt(lexer.getTokenStart()) == '#') { + int base = lexer.getTokenStart() + 1; + String directive = text.substring(base, lexer.getTokenEnd()); + VasLexer words = new VasLexer(); + words.start(directive); + while (words.getTokenType() != null) { + if (words.getTokenType() == VasTypes.IDENTIFIER && names.get(directive.substring(words.getTokenStart(), words.getTokenEnd())) == MACRO) + shade(holder, base + words.getTokenStart(), base + words.getTokenEnd(), MACRO); + words.advance(); + } + } + lexer.advance(); + } + } + + private static void shade(AnnotationHolder holder, int start, int end, TextAttributesKey key) { + holder.newSilentAnnotation(HighlightSeverity.INFORMATION).range(new TextRange(start, end)).textAttributes(key).create(); + } +} diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasSyntaxAnnotator.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasSyntaxAnnotator.java new file mode 100644 index 000000000..2a658a75f --- /dev/null +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasSyntaxAnnotator.java @@ -0,0 +1,59 @@ +package com.verseangelscript.rider.lang; + +import com.intellij.lang.annotation.Annotator; +import com.intellij.lang.annotation.AnnotationHolder; +import com.intellij.lang.annotation.HighlightSeverity; +import com.intellij.openapi.util.TextRange; +import com.intellij.psi.PsiElement; +import com.intellij.psi.PsiFile; +import com.intellij.psi.TokenType; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import org.jetbrains.annotations.NotNull; + +/** Immediate structural errors do not require a compiler process or project trust. */ +public final class VasSyntaxAnnotator implements Annotator { + public record Problem(int start, int end, String message) { } + public static List inspect(CharSequence text) { + var problems = new ArrayList(); var stack = new ArrayDeque(); + VasLexer lexer = new VasLexer(); lexer.start(text); + while (lexer.getTokenType() != null) { + var type = lexer.getTokenType(); int start = lexer.getTokenStart(), end = lexer.getTokenEnd(); + String value = text.subSequence(start, end).toString(); + if (type == VasTypes.COMMENT && value.startsWith("/*") && !value.endsWith("*/")) + problems.add(new Problem(start, Math.min(end, start + 2), "Unterminated block comment")); + else if (type == VasTypes.STRING) { + int delimiter = value.startsWith("\"\"\"") ? 3 : 1; + String opening = value.substring(0, delimiter); + if (value.length() < 2 * delimiter || !value.endsWith(opening) || delimiter == 1 && escapedEnding(value)) + problems.add(new Problem(start, Math.min(end, start + delimiter), "Unterminated string literal")); + } else if (type == TokenType.BAD_CHARACTER) problems.add(new Problem(start, end, "Invalid character")); + else if (type == VasTypes.LPAREN || type == VasTypes.LBRACKET || type == VasTypes.LBRACE) + stack.push(new Problem(start, end, value)); + else if (type == VasTypes.RPAREN || type == VasTypes.RBRACKET || type == VasTypes.RBRACE) { + char expected = value.charAt(0); + if (stack.isEmpty() || VasTypedHandler.closing(stack.peek().message().charAt(0)) != expected) + problems.add(new Problem(start, end, "Unexpected '" + expected + "'")); + else stack.pop(); + } + lexer.advance(); + } + // Inactive macro branches may deliberately contain unmatched code. Their + // actual structural diagnostics belong to the preprocessed compiler input. + boolean conditional = java.util.regex.Pattern.compile("(?m)^\\s*#(?:if|ifdef|ifndef)\\b").matcher(text).find(); + if (conditional) problems.removeIf(p -> p.message().startsWith("Unexpected")); + else for (Problem open : stack) problems.add(new Problem(open.start(), open.end(), "Expected '" + VasTypedHandler.closing(open.message().charAt(0)) + "'")); + return List.copyOf(problems); + } + private static boolean escapedEnding(String value) { + int slashes = 0; + for (int i = value.length() - 2; i >= 0 && value.charAt(i) == '\\'; i--) slashes++; + return slashes % 2 != 0; + } + @Override public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) { + if (!(element instanceof PsiFile file)) return; + for (Problem problem : inspect(file.getText())) holder.newAnnotation(HighlightSeverity.ERROR, problem.message()) + .range(new TextRange(problem.start(), problem.end())).create(); + } +} diff --git a/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasTypedHandler.java b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasTypedHandler.java new file mode 100644 index 000000000..682586d68 --- /dev/null +++ b/tools/rider-plugin/src/main/java/com/verseangelscript/rider/lang/VasTypedHandler.java @@ -0,0 +1,115 @@ +package com.verseangelscript.rider.lang; + +import com.intellij.codeInsight.AutoPopupController; +import com.intellij.codeInsight.CodeInsightSettings; +import com.intellij.codeInsight.editorActions.TypedHandlerDelegate; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.fileTypes.FileType; +import com.intellij.openapi.project.Project; +import com.intellij.psi.PsiFile; +import com.verseangelscript.rider.VasFileType; +import org.jetbrains.annotations.NotNull; + +/** Native typed-action hook: pairing participates in the editor's typing/undo command. */ +public final class VasTypedHandler extends TypedHandlerDelegate { + static char closing(char c) { + return switch (c) { case '{' -> '}'; case '(' -> ')'; case '[' -> ']'; case '"', '\'' -> c; default -> 0; }; + } + + static boolean inCode(CharSequence text, int offset) { + VasLexer lexer = new VasLexer(); + lexer.start(text); + while (lexer.getTokenType() != null) { + if (lexer.getTokenStart() <= offset && offset < lexer.getTokenEnd() + || offset == text.length() && lexer.getTokenEnd() == offset) { + if (lexer.getTokenType() == VasTypes.STRING) { + int start = lexer.getTokenStart(), end = lexer.getTokenEnd(); + return offset == start || offset == end && end > start + 1 + && text.charAt(end - 1) == text.charAt(start); + } + if (lexer.getTokenType() == VasTypes.COMMENT && offset == lexer.getTokenEnd() + && offset >= 2 && text.charAt(offset - 2) == '*' && text.charAt(offset - 1) == '/') return true; + return lexer.getTokenType() != VasTypes.COMMENT && lexer.getTokenType() != VasTypes.PREPROCESSOR; + } + lexer.advance(); + } + return true; + } + + static boolean isQuoteEnd(CharSequence text, int offset, char quote) { + if (offset >= text.length() || text.charAt(offset) != quote) return false; + int slashes = 0; + for (int i = offset - 1; i >= 0 && text.charAt(i) == '\\'; i--) slashes++; + if (slashes % 2 != 0) return false; + VasLexer lexer = new VasLexer(); lexer.start(text); + while (lexer.getTokenType() != null) { + if (lexer.getTokenType() == VasTypes.STRING && lexer.getTokenStart() < offset + && lexer.getTokenEnd() == offset + 1 && text.charAt(lexer.getTokenStart()) == quote) return true; + lexer.advance(); + } + return false; + } + private static boolean afterNumber(CharSequence text, int offset) { + VasLexer lexer = new VasLexer(); lexer.start(text); + while (lexer.getTokenType() != null) { + if (lexer.getTokenEnd() == offset) return lexer.getTokenType() == VasTypes.NUMBER; + if (lexer.getTokenStart() >= offset) break; + lexer.advance(); + } + return false; + } + @Override public @NotNull Result beforeSelectionRemoved(char c, @NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { + var selection = editor.getSelectionModel(); char close = closing(c); + if (file.getFileType() != VasFileType.INSTANCE || close == 0 || !selection.hasSelection() + || !inCode(editor.getDocument().getCharsSequence(), selection.getSelectionStart())) return Result.CONTINUE; + var settings = CodeInsightSettings.getInstance(); + if (c == '"' || c == '\'' ? !settings.AUTOINSERT_PAIR_QUOTE : !settings.AUTOINSERT_PAIR_BRACKET) return Result.CONTINUE; + int start = selection.getSelectionStart(), end = selection.getSelectionEnd(); String selected = selection.getSelectedText(); + editor.getDocument().replaceString(start, end, "" + c + selected + close); + selection.setSelection(start + 1, end + 1); editor.getCaretModel().moveToOffset(end + 1); + return Result.STOP; + } + + @Override + public @NotNull Result beforeCharTyped(char c, @NotNull Project project, @NotNull Editor editor, + @NotNull PsiFile file, @NotNull FileType fileType) { + if (fileType != VasFileType.INSTANCE || editor.getSelectionModel().hasSelection()) return Result.CONTINUE; + var document = editor.getDocument(); var text = document.getCharsSequence(); + int offset = editor.getCaretModel().getOffset(); + boolean quote = c == '"' || c == '\''; + var settings = CodeInsightSettings.getInstance(); + if (quote ? !settings.AUTOINSERT_PAIR_QUOTE : !settings.AUTOINSERT_PAIR_BRACKET) return Result.CONTINUE; + if (offset < text.length() && text.charAt(offset) == c + && (quote ? isQuoteEnd(text, offset, c) : ")]}".indexOf(c) >= 0 && inCode(text, offset))) { + editor.getCaretModel().moveToOffset(offset + 1); + return Result.STOP; + } + char close = closing(c); + if (close == 0 || !inCode(text, offset) || c == '\'' && afterNumber(text, offset)) return Result.CONTINUE; + if (offset < text.length() && !Character.isWhitespace(text.charAt(offset)) && ")]};,:".indexOf(text.charAt(offset)) < 0) return Result.CONTINUE; + document.insertString(offset, "" + c + close); + editor.getCaretModel().moveToOffset(offset + 1); + if (c == '(') AutoPopupController.getInstance(project).autoPopupParameterInfo(editor, null); + return Result.STOP; + } + + @Override public @NotNull Result charTyped(char c, @NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { + if (file.getFileType() == VasFileType.INSTANCE && (c == '(' || c == ',') + && inCode(editor.getDocument().getCharsSequence(), Math.max(0, editor.getCaretModel().getOffset() - 1))) + AutoPopupController.getInstance(project).autoPopupParameterInfo(editor, null); + return Result.CONTINUE; + } + + @Override + public @NotNull Result checkAutoPopup(char c, @NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { + if (file.getFileType() != VasFileType.INSTANCE) return Result.CONTINUE; + int offset = editor.getCaretModel().getOffset(); + if (inCode(editor.getDocument().getCharsSequence(), Math.max(0, offset - 1)) + && (Character.isJavaIdentifierPart(c) || c == '.' || c == ':' && offset >= 2 + && editor.getDocument().getCharsSequence().charAt(offset - 2) == ':')) { + AutoPopupController.getInstance(project).scheduleAutoPopup(editor); + return Result.STOP; + } + return Result.CONTINUE; + } +} diff --git a/tools/rider-plugin/src/main/resources/META-INF/plugin.xml b/tools/rider-plugin/src/main/resources/META-INF/plugin.xml index 1ae9e3bd1..676b864f2 100644 --- a/tools/rider-plugin/src/main/resources/META-INF/plugin.xml +++ b/tools/rider-plugin/src/main/resources/META-INF/plugin.xml @@ -43,6 +43,12 @@ + + + + + + + + " "int findByRef(uint, const T&in) const" objmthd "array" "bool opEquals(const array&in) const" objmthd "array" "bool isEmpty() const" objmthd "array" "void sort(array::less&in, uint = 0, uint = uint ( - 1 ))" -objmthd "array" "uint get_length() const" -objmthd "array" "void set_length(uint)" // Type members objbeh "string" 2 "void string()" @@ -96,8 +94,6 @@ objmthd "string" "int opCmp(const string&in) const" objmthd "string" "string opAdd(const string&in) const" objmthd "string" "uint length() const" objmthd "string" "void resize(uint)" -objmthd "string" "uint get_length() const" -objmthd "string" "void set_length(uint)" objmthd "string" "bool isEmpty() const" objmthd "string" "uint8& opIndex(uint)" objmthd "string" "const uint8& opIndex(uint) const" @@ -214,7 +210,31 @@ func "int64 parseInt(const string&in, uint = 10, uint&out = 0)" func "uint64 parseUInt(const string&in, uint = 10, uint&out = 0)" func "double parseFloat(const string&in, uint&out = 0)" func "string join(const array&in, const string&in)" -func "void print(const string&in)" +formatfunc "void print(const string&in format, const ?&in ...)" +func "void print(int8)" +func "void print(uint8)" +func "void print(int16)" +func "void print(uint16)" +func "void print(int)" +func "void print(uint)" +func "void print(int64)" +func "void print(uint64)" +func "void print(float)" +func "void print(double)" +func "void print(bool)" +formatfunc "void println(const string&in format, const ?&in ...)" +func "void println()" +func "void println(int8)" +func "void println(uint8)" +func "void println(int16)" +func "void println(uint16)" +func "void println(int)" +func "void println(uint)" +func "void println(int64)" +func "void println(uint64)" +func "void println(float)" +func "void println(double)" +func "void println(bool)" func "string getInput()" func "array@ getCommandLineArgs()" func "int exec(const string&in)" diff --git a/tools/rider-plugin/src/main/resources/runtime/windows-x64/vasbuild.exe b/tools/rider-plugin/src/main/resources/runtime/windows-x64/vasbuild.exe index e65ecad42..192fbfeb8 100644 Binary files a/tools/rider-plugin/src/main/resources/runtime/windows-x64/vasbuild.exe and b/tools/rider-plugin/src/main/resources/runtime/windows-x64/vasbuild.exe differ diff --git a/tools/rider-plugin/src/main/resources/runtime/windows-x64/vasrun.exe b/tools/rider-plugin/src/main/resources/runtime/windows-x64/vasrun.exe index 236c619f9..38c3e6097 100644 Binary files a/tools/rider-plugin/src/main/resources/runtime/windows-x64/vasrun.exe and b/tools/rider-plugin/src/main/resources/runtime/windows-x64/vasrun.exe differ diff --git a/tools/rider-plugin/src/test/java/com/verseangelscript/rider/diagnostics/VasRiderTrustIntegrationTest.java b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/diagnostics/VasRiderTrustIntegrationTest.java index 6257435fe..e3a5afe6b 100644 --- a/tools/rider-plugin/src/test/java/com/verseangelscript/rider/diagnostics/VasRiderTrustIntegrationTest.java +++ b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/diagnostics/VasRiderTrustIntegrationTest.java @@ -37,6 +37,7 @@ import com.jetbrains.rider.test.junit5.base.PerTestSolutionTestBase; import com.verseangelscript.rider.VasLanguage; import com.verseangelscript.rider.build.VasSettingsState; +import com.verseangelscript.rider.build.VasToolchainSettings; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -64,6 +65,59 @@ public void modifyOpenSolutionParams(OpenSolutionParams parameters) { parameters.setRestoreNuGetPackages(false); } + @Test + @Tag("season/vas") + void usesApplicationCompilerWithUnsavedModuleAndIncludeSnapshots() throws Exception { + String compiler = System.getenv("VAS_TEST_COMPILER"), config = System.getenv("VAS_TEST_CONFIG"); + org.junit.jupiter.api.Assumptions.assumeTrue(compiler != null && config != null, "Set native compiler/config to verify real background compilation"); + Project project = getSolutionApiFacade().getProject(); + Path root = getSolutionApiFacade().getActiveSolutionDirectory(); + VirtualFile main = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(root.resolve("src/arena/main.vas")); + VirtualFile demo = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(root.resolve("src/arena/Arena/Demo.vas")); + assertNotNull(main); assertNotNull(demo); + PsiFile mainPsi = ReadAction.computeBlocking(() -> PsiManager.getInstance(project).findFile(main)); + PsiFile demoPsi = ReadAction.computeBlocking(() -> PsiManager.getInstance(project).findFile(demo)); + var documents = com.intellij.openapi.fileEditor.FileDocumentManager.getInstance(); + Document mainDocument = ReadAction.computeBlocking(() -> documents.getDocument(main)); + Document demoDocument = ReadAction.computeBlocking(() -> documents.getDocument(demo)); + String beforeMain = mainDocument.getText(), beforeDemo = demoDocument.getText(); + byte[] beforeMainBytes = Files.readAllBytes(Path.of(main.getPath())); + var settings = VasSettingsState.getInstance(project); var app = VasToolchainSettings.getInstance(); + String previousBuilder = settings.builderPath, previousConfig = settings.configPath, previousCompiler = app.compilerPath; + Disposable lifetime = Disposer.newDisposable("Native VAS editing snapshots"); + try { + EdtTestUtil.runInEdtAndWait(() -> { + TrustedPaths isolatedTrust = new TrustedPaths(); isolatedTrust.loadState(TrustedPaths.getInstance().getState()); + ServiceContainerUtil.replaceService(ApplicationManager.getApplication(), TrustedPaths.class, isolatedTrust, lifetime); + setTrust(project, true); settings.builderPath = ""; settings.configPath = config; app.compilerPath = compiler; + replaceText(project, mainDocument, beforeMain.replace("return 2;", "return MissingEditorName;")); + }); + var annotator = registeredAnnotator(); + var request = ReadAction.computeBlocking(() -> annotator.collectInformation(mainPsi)); + var result = annotator.doAnnotate(request); + assertNotNull(result); + assertTrue(result.diagnostics().stream().anyMatch(d -> d.message().contains("MissingEditorName")), result.diagnostics().toString()); + EdtTestUtil.runInEdtAndWait(() -> { + replaceText(project, mainDocument, beforeMain); + replaceText(project, demoDocument, beforeDemo + "\nvoid BrokenForEditor() { UnknownEditorCall(); }\n"); + }); + var moduleRequest = ReadAction.computeBlocking(() -> annotator.collectInformation(demoPsi)); + var moduleResult = annotator.doAnnotate(moduleRequest); + assertNotNull(moduleResult); + assertTrue(moduleResult.diagnostics().stream().anyMatch(d -> d.message().contains("UnknownEditorCall")), moduleResult.diagnostics().toString()); + EdtTestUtil.runInEdtAndWait(() -> replaceText(project, demoDocument, beforeDemo)); + var fixed = annotator.doAnnotate(ReadAction.computeBlocking(() -> annotator.collectInformation(mainPsi))); + assertNotNull(fixed); assertTrue(fixed.diagnostics().isEmpty(), fixed.diagnostics().toString()); + assertArrayEquals(beforeMainBytes, Files.readAllBytes(Path.of(main.getPath())), "native snapshot must not save the editor document"); + } finally { + EdtTestUtil.runInEdtAndWait(() -> { + replaceText(project, mainDocument, beforeMain); replaceText(project, demoDocument, beforeDemo); + settings.builderPath = previousBuilder; settings.configPath = previousConfig; app.compilerPath = previousCompiler; + Disposer.dispose(lifetime); + }); + } + } + @Test @Tag("season/vas") void guardsRegisteredBackgroundDiagnosticsAcrossTrustChanges() throws Exception { diff --git a/tools/rider-plugin/src/test/java/com/verseangelscript/rider/index/VasCompletionSelectionTest.java b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/index/VasCompletionSelectionTest.java new file mode 100644 index 000000000..a2e09472e --- /dev/null +++ b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/index/VasCompletionSelectionTest.java @@ -0,0 +1,42 @@ +package com.verseangelscript.rider.index; + +import org.junit.Test; +import java.util.List; +import static org.junit.Assert.*; + +public final class VasCompletionSelectionTest { + @Test + public void enumValuesResolveThroughNamespaceAndEnumQualification() { + String source = "namespace Arena { enum ERole { Warrior = Host(1, 2), Medic } void Main() { print(Warrior); print(ERole::Warrior); } }"; + var symbols = VasSymbolScanner.scan(source); + assertEquals(2, symbols.stream().filter(symbol -> symbol.kind() == VasSymbolKind.ENUM_MEMBER).count()); + int plain = source.indexOf("Warrior);"); + var local = symbols.stream().map(symbol -> new VasSymbolSelection.Candidate<>(symbol, symbol)).toList(); + var target = VasSymbolSelection.select(local, List.of(), "Warrior", plain, VasSymbolScanner.usageContext(source, plain)); + assertEquals(1, target.size()); + assertEquals(VasSymbolKind.ENUM_MEMBER, target.getFirst().kind()); + int qualified = source.lastIndexOf("Warrior);"); + assertEquals(1, VasSymbolSelection.select(local, List.of(), "Warrior", qualified, VasSymbolScanner.usageContext(source, qualified)).size()); + assertTrue(VasCompletionSelection.select(symbols, List.of(), qualified, VasSymbolScanner.usageContext(source, qualified)) + .stream().anyMatch(symbol -> symbol.name().equals("Medic"))); + } + + @Test + public void filtersNamespacesTypedMembersAndLocalsByVisibility() { + String library = "namespace Arena { class FHero { int Health; void Heal(int Amount) {} } int RunDemo() { return 1; } }"; + String source = "void Main() { Arena::FHero Hero; { int Hidden; } Hero.Heal(); Arena::RunDemo(); }"; + var local = VasSymbolScanner.scan(source); + var imported = VasSymbolScanner.scan(library); + int member = source.indexOf("Heal()"); + List members = VasCompletionSelection.select(local, imported, member, VasSymbolScanner.usageContext(source, member)); + assertTrue(members.stream().anyMatch(symbol -> symbol.name().equals("Heal"))); + assertTrue(members.stream().anyMatch(symbol -> symbol.name().equals("Health"))); + assertFalse(members.stream().anyMatch(symbol -> symbol.name().equals("RunDemo"))); + int namespace = source.indexOf("RunDemo()"); + var qualified = VasCompletionSelection.select(local, imported, namespace, VasSymbolScanner.usageContext(source, namespace)); + assertTrue(qualified.stream().anyMatch(symbol -> symbol.name().equals("RunDemo"))); + assertFalse(qualified.stream().anyMatch(symbol -> symbol.name().equals("Health"))); + var plain = VasCompletionSelection.select(local, imported, member, VasUsageContext.PLAIN); + assertFalse(plain.stream().anyMatch(symbol -> symbol.name().equals("Hidden"))); + } +} diff --git a/tools/rider-plugin/src/test/java/com/verseangelscript/rider/index/VasIncludeScannerTest.java b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/index/VasIncludeScannerTest.java index effdedffa..debd1579a 100644 --- a/tools/rider-plugin/src/test/java/com/verseangelscript/rider/index/VasIncludeScannerTest.java +++ b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/index/VasIncludeScannerTest.java @@ -63,7 +63,7 @@ public void numericSeparatorsDoNotHideFollowingIncludes() { @Test public void directivesMustHaveExactNamesAndQuotedNonemptyPaths() { - for (String source : List.of("#include", "#include", "#include api.vas", + for (String source : List.of("#include", "#include api.vas", "#include ''", "#include \"\"", "#include_more 'api.vas'", "# include 'api.vas'")) { VasIncludeScanner.Result result = VasIncludeScanner.scan(source); assertFalse(source, result.complete()); @@ -145,6 +145,21 @@ public void nativeUnicodeIdentifierAndWhitespaceBoundariesStayExact() { assertTrue(VasIncludeScanner.scan("int 😀value;\n#include 'api.vas'").complete()); } + @Test + public void moduleImportsAndAngleIncludesShareDependencyExtraction() { + String source = "import math;\nimport pkg /*comment*/ . tool;\n#include \n"; + VasIncludeScanner.Result result = VasIncludeScanner.scan(source); + assertTrue(result.complete()); + assertEquals(List.of("math.vas", "pkg/tool.vas", "api.vas"), paths(result)); + assertEquals(VasIncludeScanner.Kind.MODULE, result.includes().getFirst().kind()); + assertEquals(VasIncludeScanner.Kind.SYSTEM, result.includes().getLast().kind()); + assertEquals("math", source.substring(result.includes().getFirst().pathStart(), result.includes().getFirst().pathEnd())); + assertTrue(VasIncludeScanner.scan("import pkg.; import 2bad; import pkg.int;").includes().isEmpty()); + assertTrue(VasIncludeScanner.scan("import int host(int) from \"other\";").includes().isEmpty()); + assertFalse(VasIncludeScanner.scan("void main(){ import math; }").complete()); + assertTrue(VasIncludeScanner.scan("string s = \"import hidden;\"; // import hidden;\n").includes().isEmpty()); + } + private static List paths(VasIncludeScanner.Result result) { return result.includes().stream().map(VasIncludeScanner.Include::path).toList(); } diff --git a/tools/rider-plugin/src/test/java/com/verseangelscript/rider/index/VasIndexPerformanceTest.java b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/index/VasIndexPerformanceTest.java new file mode 100644 index 000000000..def9150ec --- /dev/null +++ b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/index/VasIndexPerformanceTest.java @@ -0,0 +1,45 @@ +package com.verseangelscript.rider.index; + +import org.junit.Test; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.List; +import static org.junit.Assert.assertEquals; + +/** Informational measurements, with symbol-count correctness as the stable assertion. */ +public final class VasIndexPerformanceTest { + @Test + public void measuresArenaAndLargeDeclarationIndexing() throws Exception { + Path arena = Path.of("../../examples/arena"); + List files; + try (var paths = Files.walk(arena)) { + files = paths.filter(path -> path.toString().endsWith(".vas")).sorted().map(path -> { + try { return Files.readString(path); } catch (Exception error) { throw new RuntimeException(error); } + }).toList(); + } + assertEquals(9, files.size()); + StringBuilder synthetic = new StringBuilder("namespace Perf {\n"); + for (int index = 0; index < 1500; index++) synthetic.append("int32 Function").append(index).append("(int32 Value) { int32 Result = Value + 1; return Result; }\n"); + synthetic.append('}'); + String large = synthetic.toString(); + long[] arenaTimes = new long[11], largeTimes = new long[5]; + int arenaSymbols = 0; + for (int repeat = 0; repeat < arenaTimes.length; repeat++) { + long start = System.nanoTime(); + arenaSymbols = files.stream().mapToInt(file -> VasSymbolScanner.scan(file).size()).sum(); + arenaTimes[repeat] = System.nanoTime() - start; + } + for (int repeat = 0; repeat < largeTimes.length; repeat++) { + long start = System.nanoTime(); + assertEquals(4501, VasSymbolScanner.scan(large).size()); + largeTimes[repeat] = System.nanoTime() - start; + } + Arrays.sort(arenaTimes); Arrays.sort(largeTimes); + String result = "{\"arenaFiles\":9,\"arenaSymbols\":" + arenaSymbols + ",\"arenaMedianMs\":" + arenaTimes[5] / 1e6 + + ",\"syntheticFunctions\":1500,\"syntheticSymbols\":4501,\"syntheticMedianMs\":" + largeTimes[2] / 1e6 + "}"; + Path evidence = Path.of("../../out/verification/ide/rider-index-" + System.getProperty("vas.performance.phase", "current") + ".json"); + Files.createDirectories(evidence.getParent()); Files.writeString(evidence, result); + System.out.println("VAS index performance " + result); + } +} diff --git a/tools/rider-plugin/src/test/java/com/verseangelscript/rider/index/VasSymbolScannerTest.java b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/index/VasSymbolScannerTest.java index 2900ea3a9..c09345d77 100644 --- a/tools/rider-plugin/src/test/java/com/verseangelscript/rider/index/VasSymbolScannerTest.java +++ b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/index/VasSymbolScannerTest.java @@ -9,6 +9,15 @@ import static org.junit.Assert.assertTrue; public final class VasSymbolScannerTest { + @Test + public void retainsLegacyFunctionImportsAlongsideModuleImportsAndMacros() { + var symbols = VasSymbolScanner.scan("import Arena.Math;\n#define VALUE 3\nimport int Host(int Value) from \"Native\";\nint Main() { return Host(1); }"); + assertSymbol(symbols, "Host", VasSymbolKind.FUNCTION); + assertFalse(symbols.stream().filter(symbol -> symbol.name().equals("Host")).findFirst().orElseThrow().definition()); + assertFalse(symbols.stream().anyMatch(symbol -> symbol.name().equals("Arena"))); + assertEquals("VALUE", VasMacroScanner.scan("\"#define FALSE 1\"; // #define BAD 2\n#define VALUE 3\n").getFirst().name()); + } + @Test public void discoversTypesFunctionsFieldsAndLocals() { String source = """ diff --git a/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasAstFactoryTest.java b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasAstFactoryTest.java index 6996d4602..020a8e3fc 100644 --- a/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasAstFactoryTest.java +++ b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasAstFactoryTest.java @@ -22,11 +22,13 @@ public void createsCustomPsiOnlyForIdentifiers() { } @Test - public void extractsOnlyQuotedIncludePaths() { + public void extractsQuotedAngleAndModulePaths() { assertEquals("shared/math.vas", VasIncludeReference.extractIncludePath( " #include \"shared/math.vas\"" )); - assertNull(VasIncludeReference.extractIncludePath("#include ")); + assertEquals("shared/math.vas", VasIncludeReference.extractIncludePath("#include ")); + assertEquals("Arena/Demo.vas", VasIncludeReference.extractIncludePath("import Arena.Demo;")); + assertNull(VasIncludeReference.extractIncludePath("import int Fn() from \"module\";")); assertNull(VasIncludeReference.extractIncludePath("#define path \"math.vas\"")); assertEquals("shared/math.vas", VasIncludeReference.extractIncludePath("#include'shared/math.vas'")); assertEquals("shared/math.vas", VasIncludeReference.extractIncludePath("#include\"shared/math.vas\"")); diff --git a/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasEditingSupportTest.java b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasEditingSupportTest.java new file mode 100644 index 000000000..5f3c3f8ca --- /dev/null +++ b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasEditingSupportTest.java @@ -0,0 +1,39 @@ +package com.verseangelscript.rider.lang; + +import org.junit.Test; +import static org.junit.Assert.*; + +public final class VasEditingSupportTest { + @Test public void reportsStructuralErrorsButProtectsStringsCommentsAndHeredocs() { + assertTrue(VasSyntaxAnnotator.inspect("void Main() { string Text = \"} )\"; /* ] */ }").isEmpty()); + assertTrue(VasSyntaxAnnotator.inspect("string Text = \"\"\"} ] (\n\"\"\";").isEmpty()); + assertTrue(VasSyntaxAnnotator.inspect("void Main(] {}").stream().anyMatch(p -> p.message().contains("Unexpected"))); + assertTrue(VasSyntaxAnnotator.inspect("void Main() {").stream().anyMatch(p -> p.message().equals("Expected '}'"))); + assertTrue(VasSyntaxAnnotator.inspect("string Text = \"oops").stream().anyMatch(p -> p.message().contains("string"))); + assertTrue(VasSyntaxAnnotator.inspect("/* oops").stream().anyMatch(p -> p.message().contains("comment"))); + assertTrue(VasSyntaxAnnotator.inspect("string Text = \"escaped\\\"").stream().anyMatch(p -> p.message().contains("string"))); + } + @Test public void avoidsPairingInsideProtectedTokensAndDigitSeparators() { + assertFalse(VasTypedHandler.inCode("// typing {", 10)); + assertFalse(VasTypedHandler.inCode("\"typing {\"", 8)); + assertFalse(VasTypedHandler.inCode("/* typing { */", 10)); + assertTrue(VasTypedHandler.inCode("/* done */", 10)); + assertTrue(VasTypedHandler.inCode("\"done\"", 6)); + assertFalse(VasTypedHandler.isQuoteEnd("\"escaped\\\"", 9, '"')); + assertTrue(VasTypedHandler.isQuoteEnd("\"done\"", 5, '"')); + } + @Test public void selectsInnermostCallAndCountsOnlyItsArguments() { + String text = "Outer(Inner(1, 2), {3, 4}, \"comma,\", "; + var call = VasCallSupport.callAt(text, text.length()); + assertEquals("Outer", call.name()); assertEquals(3, call.parameter()); + var nested = VasCallSupport.callAt("Outer(Inner(1, ", 15); + assertEquals("Inner", nested.name()); assertEquals(1, nested.parameter()); + assertNull(VasCallSupport.callAt("if (true)", 9)); + } + @Test public void signatureRangesProtectGenericAndDefaultArgumentCommas() { + var signature = VasCallSupport.signature("Add(array@ Values, int Count = Other(1, 2), string Text = \"a,b\")"); + assertEquals(3, signature.parameters().size()); + int[] last = signature.parameters().get(2); + assertEquals("string Text = \"a,b\"", signature.label().substring(last[0], last[1])); + } +} diff --git a/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasLexerTest.java b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasLexerTest.java index ac1fb9b05..2203b531c 100644 --- a/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasLexerTest.java +++ b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasLexerTest.java @@ -37,6 +37,23 @@ public void recognizesCoreVasTokens() { assertToken(tokens, VasTypes.COMMENT, "// ready"); } + @Test + public void moduleImportsAreOpaqueButNativeFunctionImportsRemainTokens() { + String source = "import pkg.tool;\n#include \nimport int host(int) from \"other\";\nint value = 42;"; + VasLexer lexer = new VasLexer(); + lexer.start(source); + List tokens = new ArrayList<>(); + while (lexer.getTokenType() != null) { + tokens.add(new Token(lexer.getTokenType(), source.substring(lexer.getTokenStart(), lexer.getTokenEnd()))); + lexer.advance(); + } + assertToken(tokens, VasTypes.PREPROCESSOR, "import pkg.tool;"); + assertToken(tokens, VasTypes.PREPROCESSOR, "#include "); + assertToken(tokens, VasTypes.KEYWORD, "import"); + assertToken(tokens, VasTypes.IDENTIFIER, "host"); + assertToken(tokens, VasTypes.IDENTIFIER, "value"); + } + @Test public void keepsEscapedQuotesInsideStrings() { String source = "string value = \"VAS \\\"script\\\"\";"; diff --git a/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasRiderEditingIntegrationTest.java b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasRiderEditingIntegrationTest.java new file mode 100644 index 000000000..d763af7b0 --- /dev/null +++ b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasRiderEditingIntegrationTest.java @@ -0,0 +1,106 @@ +package com.verseangelscript.rider.lang; + +import com.intellij.codeInsight.CodeInsightSettings; +import com.intellij.codeInsight.completion.*; +import com.intellij.codeInsight.lookup.LookupManager; +import com.intellij.openapi.actionSystem.*; +import com.intellij.openapi.actionSystem.impl.SimpleDataContext; +import com.intellij.openapi.command.WriteCommandAction; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.editor.actionSystem.*; +import com.intellij.openapi.fileEditor.FileEditorManager; +import com.intellij.openapi.fileEditor.OpenFileDescriptor; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.LocalFileSystem; +import com.intellij.psi.*; +import com.intellij.testFramework.EdtTestUtil; +import com.jetbrains.rider.test.OpenSolutionParams; +import com.jetbrains.rider.test.annotations.*; +import com.jetbrains.rider.test.enums.*; +import com.jetbrains.rider.test.enums.sdk.SdkVersion; +import com.jetbrains.rider.test.junit5.base.PerTestSolutionTestBase; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Tag; +import java.util.function.Consumer; +import static org.junit.jupiter.api.Assertions.*; + +@Solution(name = "vas-navigation", slnName = "VasNavigation.sln") +@TestSettings(buildTool = BuildTool.AUTODETECT, mono = Mono.NONE, sdkVersion = SdkVersion.NONE) +public final class VasRiderEditingIntegrationTest extends PerTestSolutionTestBase { + @Override public void modifyOpenSolutionParams(OpenSolutionParams params) { + super.modifyOpenSolutionParams(params); params.setWaitForCaches(true); params.setWaitForSolutionBuilder(true); params.setRestoreNuGetPackages(false); + } + @Test @Tag("season/vas") void nativeTypingPairsSkipsDeletesAndIndents() { + withEditor(editor -> { + Project project = editor.getProject(); + var settings = CodeInsightSettings.getInstance(); boolean brackets = settings.AUTOINSERT_PAIR_BRACKET, quotes = settings.AUTOINSERT_PAIR_QUOTE; + settings.AUTOINSERT_PAIR_BRACKET = true; settings.AUTOINSERT_PAIR_QUOTE = true; + try { + for (char c : new char[] {'{', '(', '[', '"', '\''}) { + setText(editor, "", 0); type(editor, c); + assertEquals("" + c + VasTypedHandler.closing(c), editor.getDocument().getText(), "native pair " + c); + assertEquals(1, editor.getCaretModel().getOffset()); + action(editor, IdeActions.ACTION_EDITOR_BACKSPACE); + assertEquals("", editor.getDocument().getText(), "paired backspace " + c); + type(editor, c); type(editor, VasTypedHandler.closing(c)); + assertEquals(2, editor.getDocument().getTextLength(), "closing must not duplicate " + c); + assertEquals(2, editor.getCaretModel().getOffset()); + } + setText(editor, "void Main() ", 12); type(editor, '{'); action(editor, IdeActions.ACTION_EDITOR_ENTER); + assertEquals("void Main() {\n\t\n}", editor.getDocument().getText()); + assertEquals("void Main() {\n\t".length(), editor.getCaretModel().getOffset()); + setText(editor, "// comment ", 11); type(editor, '{'); assertEquals("// comment {", editor.getDocument().getText()); + setText(editor, "\"inside\"", 7); type(editor, '('); assertEquals("\"inside(\"", editor.getDocument().getText()); + setText(editor, "int Value = 1", 13); type(editor, '\''); assertEquals("int Value = 1'", editor.getDocument().getText()); + setText(editor, "int Value = 0xAF", 16); type(editor, '\''); assertEquals("int Value = 0xAF'", editor.getDocument().getText()); + setText(editor, "Value", 5); editor.getSelectionModel().setSelection(0, 5); type(editor, '('); + assertEquals("(Value)", editor.getDocument().getText()); editor.getSelectionModel().removeSelection(); + settings.AUTOINSERT_PAIR_BRACKET = false; setText(editor, "", 0); type(editor, '{'); assertEquals("{", editor.getDocument().getText()); + } finally { settings.AUTOINSERT_PAIR_BRACKET = brackets; settings.AUTOINSERT_PAIR_QUOTE = quotes; } + }); + } + @Test @Tag("season/vas") void nativeCompletionInsertsCallAndProvidesOverloadSignatures() { + withEditor(editor -> { + String source = "int Add(int Left, int Right) { return Left + Right; }\nvoid Main() { Ad }"; + setText(editor, source, source.lastIndexOf("Ad") + 2); + new CodeCompletionHandlerBase(CompletionType.BASIC).invokeCompletion(editor.getProject(), editor); + var lookup = LookupManager.getActiveLookup(editor); + if (lookup != null) { + var item = lookup.getItems().stream().filter(i -> i.getLookupString().equals("Add")).findFirst().orElseThrow(); + lookup.setCurrentItem(item); ((com.intellij.codeInsight.lookup.impl.LookupImpl) lookup).finishLookup('\t'); + } + assertTrue(editor.getDocument().getText().contains("Main() { Add() }"), editor.getDocument().getText()); + assertEquals(')', editor.getDocument().getCharsSequence().charAt(editor.getCaretModel().getOffset())); + PsiDocumentManager.getInstance(editor.getProject()).commitAllDocuments(); + PsiFile file = PsiDocumentManager.getInstance(editor.getProject()).getPsiFile(editor.getDocument()); + var call = VasCallSupport.callAt(file.getText(), editor.getCaretModel().getOffset()); + assertEquals("Add", call.name()); + assertEquals("Add(int Left, int Right)", VasCallSupport.signatures(file, call).getFirst().label()); + }); + } + private void withEditor(Consumer body) { + Project project = getSolutionApiFacade().getProject(); + var file = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(getSolutionApiFacade().getActiveSolutionDirectory().resolve("src/main.vas")); + assertNotNull(file); + EdtTestUtil.runInEdtAndWait(() -> { + Editor editor = FileEditorManager.getInstance(project).openTextEditor(new OpenFileDescriptor(project, file), true); + assertNotNull(editor); String before = editor.getDocument().getText(); + try { body.accept(editor); } finally { LookupManager.hideActiveLookup(project); setText(editor, before, 0); FileEditorManager.getInstance(project).closeFile(file); } + }); + } + private static void setText(Editor editor, String text, int caret) { + LookupManager.hideActiveLookup(editor.getProject()); + WriteCommandAction.runWriteCommandAction(editor.getProject(), () -> editor.getDocument().setText(text)); + editor.getCaretModel().moveToOffset(caret); + PsiDocumentManager.getInstance(editor.getProject()).commitAllDocuments(); + } + private static DataContext context(Editor editor) { + return SimpleDataContext.builder().add(CommonDataKeys.PROJECT, editor.getProject()).add(CommonDataKeys.EDITOR, editor) + .add(CommonDataKeys.PSI_FILE, PsiDocumentManager.getInstance(editor.getProject()).getPsiFile(editor.getDocument())).build(); + } + private static void type(Editor editor, char c) { TypedAction.getInstance().actionPerformed(editor, c, context(editor)); } + private static void action(Editor editor, String name) { + WriteCommandAction.runWriteCommandAction(editor.getProject(), () -> EditorActionManager.getInstance().getActionHandler(name) + .execute(editor, editor.getCaretModel().getCurrentCaret(), context(editor))); + } +} diff --git a/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasRiderSolutionIntegrationTest.java b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasRiderSolutionIntegrationTest.java index c62f5688c..178989bd4 100644 --- a/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasRiderSolutionIntegrationTest.java +++ b/tools/rider-plugin/src/test/java/com/verseangelscript/rider/lang/VasRiderSolutionIntegrationTest.java @@ -69,6 +69,61 @@ public void modifyOpenSolutionParams(OpenSolutionParams params) { params.setRestoreNuGetPackages(false); } + @Test + @Tag("season/vas") + void navigatesAndIndexesArenaModulesWithExportedMacros() { + Project project = getSolutionApiFacade().getProject(); + Path sourceDirectory = getSolutionApiFacade().getActiveSolutionDirectory().resolve("src/arena"); + ApplicationManager.getApplication().runReadAction(() -> { + PsiFile main = fixture(project, sourceDirectory, "main.vas"); + PsiFile demo = fixture(project, sourceDirectory, "Arena/Demo.vas"); + PsiFile config = fixture(project, sourceDirectory, "Arena/Config.vas"); + assertProjectIndexedFile(project, demo, "RunDemo"); + assertProjectIndexedFile(project, config, "VAS_ARENA_MAX_ROUNDS"); + var symbols = new VasGotoSymbolContributor(); + assertTrue(List.of(symbols.getNames(project, false)).contains("RunDemo")); + assertTrue(symbols.getItemsByName("RunDemo", "RunDemo", project, false).length > 0); + assertTrue(symbols.getItemsByName("VAS_ARENA_MAX_ROUNDS", "VAS_ARENA_MAX_ROUNDS", project, false).length > 0); + assertEquals(8, VasSymbolResolver.inspectDependencyClosure(main).includedFiles().size()); + PsiElement imported = main.findElementAt(main.getText().indexOf("import Arena.Demo")); + assertEquals(demo, new VasDirectNavigationProvider().getNavigationElement(imported)); + PsiElement runDemo = main.findElementAt(main.getText().indexOf("RunDemo(")); + PsiElement target = new VasDirectNavigationProvider().getNavigationElement(runDemo); + assertNotNull(target, "macro/conditional directives must not erase known navigation candidates"); + assertEquals(demo, target.getContainingFile()); + assertEquals("RunDemo", target.getText()); + assertTrue(VasSymbolResolver.findDeclarations(runDemo).isEmpty(), "rename coverage remains conservative"); + PsiElement runBatch = demo.findElementAt(demo.getText().indexOf("RunBatch(")); + var manager = ((com.intellij.find.impl.FindManagerImpl)com.intellij.find.FindManager.getInstance(project)).getFindUsagesManager(); + var handler = manager.getFindUsagesHandler(runBatch, false); + assertNotNull(handler, "native Find Usages must have a VAS handler"); + assertTrue(handler instanceof VasFindUsagesHandlerFactory.Handler, "the registered native handler must serve VAS"); + var options = handler.getFindUsagesOptions(); options.searchScope = GlobalSearchScope.projectScope(project); + var usages = new java.util.ArrayList(); + assertTrue(handler.processElementUsages(runBatch, info -> { usages.add(info); return true; }, options)); + assertEquals(1, usages.size(), "RunBatch has one source usage even when imported modules contain macros"); + assertEquals(main, usages.getFirst().getFile()); + assertEquals(main.getText().indexOf("RunBatch("), usages.getFirst().getNavigationOffset()); + assertEquals("1 usage", new VasReferencesCodeVisionProvider().getHint(runBatch, demo)); + assertEquals(List.of("main"), VasSymbolResolver.findCallers(runBatch).stream().map(PsiElement::getText).toList()); + PsiElement call = main.findElementAt(main.getText().indexOf("RunBatch(")); + assertTrue(new VasFindUsagesProvider().canFindUsagesFor(call)); + var callHandler = manager.getFindUsagesHandler(call, false); + assertNotNull(callHandler, "Find Usages must also work from a call, not only its declaration"); + assertEquals(runBatch, callHandler.getPsiElement()); + PsiFile combatant = fixture(project, sourceDirectory, "Arena/Combatant.vas"); + assertTrue(VasSymbolResolver.navigationFiles(combatant).stream().anyMatch(file -> file.equals(config))); + assertTrue(VasSymbolResolver.navigationFiles(main).stream().anyMatch(file -> file.equals(combatant))); + assertProjectIndexedFile(project, combatant, "FCombatant"); + assertProjectIndexedFile(project, combatant, "Warrior"); + var role = combatant.findElementAt(combatant.getText().indexOf("Warrior, 90")); + var roleTarget = new VasDirectNavigationProvider().getNavigationElement(role); + assertNotNull(roleTarget); + assertEquals("Warrior", roleTarget.getText()); + assertTrue(roleTarget.getTextOffset() < role.getTextOffset()); + }); + } + @Test @Tag("season/vas") void resolvesNestedIncludeAndDeclarationInOpenedRiderSolution() { @@ -234,6 +289,10 @@ void registersReferencesAndPerformsAtomicRenameAndUndoInTheRiderHost() { PsiElement ambiguous = markedIdentifier(api, "rename-ambiguous-declaration"); assertTrue(ReferencesSearch.search(ambiguous).findAll().isEmpty(), "an ambiguous call must not be claimed as a usage of either overload"); + var ambiguousUsages = new java.util.ArrayList(); + com.verseangelscript.rider.index.VasUsageSearch.process(ambiguous, GlobalSearchScope.projectScope(project), + usage -> { ambiguousUsages.add(usage); return true; }); + assertTrue(ambiguousUsages.isEmpty(), "read-only usage lookup must also retain overload ambiguity"); String sourceBefore = source.getText(); String apiBefore = api.getText(); RuntimeException rejection = assertThrows(RuntimeException.class, diff --git a/tools/rider-plugin/testData/solutions/vas-navigation/VasNavigation.vcxproj b/tools/rider-plugin/testData/solutions/vas-navigation/VasNavigation.vcxproj index c9eacec7d..771a41826 100644 --- a/tools/rider-plugin/testData/solutions/vas-navigation/VasNavigation.vcxproj +++ b/tools/rider-plugin/testData/solutions/vas-navigation/VasNavigation.vcxproj @@ -59,6 +59,15 @@ + + + + + + + + + diff --git a/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Battle.vas b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Battle.vas new file mode 100644 index 000000000..55d9de981 --- /dev/null +++ b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Battle.vas @@ -0,0 +1,92 @@ +import Combatant; +import Skills; // Shared Combatant dependency is processed only once. + +namespace Arena +{ + class FBattleResult + { + string LeftName; + string RightName; + int32 LeftHealth; + int32 RightHealth; + int32 LeftDamageDealt; + int32 RightDamageDealt; + int32 LeftHealingDone; + int32 RightHealingDone; + int32 RoundCount = 0; + int32 WinnerIndex = -1; // -1: draw, 0: left wins, 1: right wins. + } + + void TakeTurn(FCombatant@ Actor, FCombatant@ Target, ICombatSkill@ Attack, ICombatSkill@ Heal, + FDeterministicRandom@ Random, bool bVerbose) + { + if (!Actor.IsAlive() || !Target.IsAlive()) + { + return; + } + ICombatSkill@ Selected = Attack; + if (Actor.Role == Medic && Actor.Health <= Actor.MaxHealth / 2) + { + @Selected = Heal; + } + int32 Amount = Selected.Execute(Actor, Target, Random); +#if VAS_ARENA_VERBOSE + if (bVerbose) + { + println(" {} {}:{},双方 HP = {} / {}", Actor.Name, Selected.GetLabel(), Amount, Actor.Health, Target.Health); + } +#endif + } + + FBattleResult@ SimulateBattle(FCombatant@ Left, FCombatant@ Right, uint32 Seed, bool bVerbose) + { + FDeterministicRandom Random(Seed); + // Create skills once per battle and reuse them inside the round loop. + FAttackSkill Attack; + FHealSkill Heal; + FBattleResult@ Result = FBattleResult(); + for (int32 Round = 1; Round <= VAS_ARENA_MAX_ROUNDS && Left.IsAlive() && Right.IsAlive(); ++Round) + { + Result.RoundCount = Round; +#if VAS_ARENA_VERBOSE + if (bVerbose) + { + println("第 {:02d} 回合", Round); + } +#endif + // Alternate initiative each round and check both combatants before every action. + if (Round % 2 == 1) + { + TakeTurn(Left, Right, Attack, Heal, Random, bVerbose); + TakeTurn(Right, Left, Attack, Heal, Random, bVerbose); + } + else + { + TakeTurn(Right, Left, Attack, Heal, Random, bVerbose); + TakeTurn(Left, Right, Attack, Heal, Random, bVerbose); + } + } + Result.LeftName = Left.Name; + Result.RightName = Right.Name; + Result.LeftHealth = Left.Health; + Result.RightHealth = Right.Health; + Result.LeftDamageDealt = Left.DamageDealt; + Result.RightDamageDealt = Right.DamageDealt; + Result.LeftHealingDone = Left.HealingDone; + Result.RightHealingDone = Right.HealingDone; + if (Left.IsAlive() && !Right.IsAlive()) + { + Result.WinnerIndex = 0; + } + if (Right.IsAlive() && !Left.IsAlive()) + { + Result.WinnerIndex = 1; + } + return Result; + } + + string GetWinnerLabel(FBattleResult@ Result) + { + return Result.WinnerIndex == 0 ? Result.LeftName : Result.WinnerIndex == 1 ? Result.RightName : "平局"; + } +} diff --git a/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Checks.vas b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Checks.vas new file mode 100644 index 000000000..5086e9701 --- /dev/null +++ b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Checks.vas @@ -0,0 +1,93 @@ +import Report; + +namespace Arena +{ + class FSelfTestChecks + { + int32 Count = 0; + int32 Failures = 0; + + void Expect(bool bCondition, const string&in Description) + { + ++Count; + if (!bCondition) + { + ++Failures; + println("[FAIL] {}", Description); + } + } + } + + bool AreSelfTestsPassing() + { + FSelfTestChecks Checks; + Checks.Expect(Clamp(-5, 0, 10) == 0, "clamp 下界"); + Checks.Expect(Clamp(15, 0, 10) == 10, "clamp 上界"); + Checks.Expect(Clamp(7, 0, 10) == 7, "clamp 区间内"); + Checks.Expect(CreateCombatant(99) is null, "非法角色索引返回 null"); + FCombatant@ Combatant = CreateCombatant(0); + Checks.Expect(Combatant.ApplyDamage(-10) == 0 && Combatant.Health == 90, "负伤害不回血"); + Checks.Expect(Combatant.ApplyDamage(7) == 7 && Combatant.Health == 83, "实际伤害"); + Checks.Expect(Combatant.RestoreHealth(1000) == 7 && Combatant.Health == 90, "治疗封顶"); + Checks.Expect(Combatant.RestoreHealth(-10) == 0 && Combatant.Health == 90, "负治疗不扣血"); + Checks.Expect(Combatant.ApplyDamage(1000) == 90 && !Combatant.IsAlive(), "致命伤害封底"); + Checks.Expect(Combatant.RestoreHealth(18) == 0 && Combatant.Health == 0, "治疗不复活"); + + FDeterministicRandom FirstRandom(42); + FDeterministicRandom ReplayRandom(42); + FDeterministicRandom DifferentRandom(43); + bool bEqualSequence = true; + for (uint32 Index = 0; Index < 20; ++Index) + { + bEqualSequence = (FirstRandom.Next() == ReplayRandom.Next()) && bEqualSequence; + } + Checks.Expect(bEqualSequence, "相同种子生成相同序列"); + FDeterministicRandom InitialRandom(42); + Checks.Expect(InitialRandom.Next() != DifferentRandom.Next(), "不同种子改变序列"); + Checks.Expect(FirstRandom.NextBelow(0) == 0, "零范围随机数避免除零"); + + ICombatSkill@ Attack = FAttackSkill(); + ICombatSkill@ Heal = FHealSkill(); + FDeterministicRandom CriticalRandom(0); + FDeterministicRandom NormalRandom(1); + FCombatant@ Actor = CreateCombatant(0); + FCombatant@ Target = CreateCombatant(1); + Checks.Expect(Attack.Execute(Actor, Target, NormalRandom) == 12, "普通攻击扣除护甲"); + @Target = CreateCombatant(1); + Checks.Expect(Attack.Execute(Actor, Target, CriticalRandom) == 30, "暴击宏与接口调用"); + Actor.ApplyDamage(20); + Checks.Expect(Heal.Execute(Actor, Target, NormalRandom) == 18 && Actor.Health == 88, "治疗技能多态"); + Checks.Expect(Attack.Execute(null, Target, NormalRandom) == 0, "空句柄保护"); + Checks.Expect(Attack.Execute(Combatant, Target, NormalRandom) == 0, "倒下角色不能行动"); + + FBattleResult@ FirstResult = SimulateBattle(CreateCombatant(0), CreateCombatant(1), 42, false); + FBattleResult@ SecondResult = SimulateBattle(CreateCombatant(0), CreateCombatant(1), 42, false); + Checks.Expect( + FirstResult.WinnerIndex == SecondResult.WinnerIndex && + FirstResult.LeftHealth == SecondResult.LeftHealth && + FirstResult.RightHealth == SecondResult.RightHealth && + FirstResult.RoundCount == SecondResult.RoundCount && + FirstResult.LeftDamageDealt == SecondResult.LeftDamageDealt && + FirstResult.RightDamageDealt == SecondResult.RightDamageDealt, + "整场战斗可重放"); + Checks.Expect( + FirstResult.RoundCount > 0 && FirstResult.RoundCount <= VAS_ARENA_MAX_ROUNDS && + FirstResult.LeftHealth >= 0 && FirstResult.RightHealth >= 0, + "回合上限和 HP 范围"); + + FStanding Left("左"), Right("右"); + FBattleResult Result; + Result.WinnerIndex = 0; + Result.LeftDamageDealt = 17; + RecordResult(Left, Right, Result); + Checks.Expect(Left.GetPoints() == 3 && Left.Wins == 1 && Right.Losses == 1 && Left.DamageDealt == 17, + "胜负积分和伤害归档"); + Result.WinnerIndex = -1; + RecordResult(Left, Right, Result); + Checks.Expect(Left.GetPoints() == 4 && Right.GetPoints() == 1 && Left.Draws == 1 && Right.Draws == 1, + "平局积分归档"); + Checks.Expect(ShouldRankBefore(Left, Right), "排行榜积分优先"); + println("SELF_TEST passed={} failed={}", Checks.Count - Checks.Failures, Checks.Failures); + return Checks.Failures == 0; + } +} diff --git a/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Combatant.vas b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Combatant.vas new file mode 100644 index 000000000..0abb767e8 --- /dev/null +++ b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Combatant.vas @@ -0,0 +1,70 @@ +import Config; +import Math; + +namespace Arena +{ + enum ECombatRole + { + Warrior, + Guardian, + Medic + } + + class FCombatant + { + string Name; + ECombatRole Role; + int32 MaxHealth; + int32 Health; + int32 Attack; + int32 Armor; + int32 DamageDealt = 0; + int32 HealingDone = 0; + + FCombatant(const string&in Label, ECombatRole Kind, int32 InitialHealth, int32 Power, int32 Defense) + { + Name = Label; + Role = Kind; + MaxHealth = InitialHealth; + Health = InitialHealth; + Attack = Power; + Armor = Defense; + } + + bool IsAlive() const + { + return Health > 0; + } + + // Return the actual change so excess damage and healing do not inflate statistics. + int32 ApplyDamage(int32 Amount) + { + int32 Actual = Clamp(Amount, 0, Health); + Health -= Actual; + return Actual; + } + + int32 RestoreHealth(int32 Amount) + { + if (!IsAlive()) + { + return 0; // Healing does not revive defeated combatants. + } + int32 Actual = Clamp(Amount, 0, MaxHealth - Health); + Health += Actual; + HealingDone += Actual; + return Actual; + } + } + + FCombatant@ CreateCombatant(uint32 Index) + { + switch (Index) + { + case 0: return FCombatant("剑士", Warrior, 90, 18, 2); + case 1: return FCombatant("守卫", Guardian, 110, 14, 6); + case 2: return FCombatant("医师", Medic, 82, 12, 3); + } + return null; + } +} diff --git a/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Config.vas b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Config.vas new file mode 100644 index 000000000..78efad766 --- /dev/null +++ b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Config.vas @@ -0,0 +1,16 @@ +// Defaults are shared by the compilation unit and may be overridden by the entry point. +#ifndef VAS_ARENA_VERBOSE +#define VAS_ARENA_VERBOSE 1 +#endif +#ifndef VAS_ARENA_MAX_ROUNDS +#define VAS_ARENA_MAX_ROUNDS 12 +#endif +#define VAS_ARENA_VERSION "1.0" +#define VAS_ARENA_CRIT_PERCENT 25 +#define VAS_ARENA_CRITICAL_DAMAGE(Amount) ((Amount) * 2) +#if VAS_ARENA_MAX_ROUNDS < 1 || VAS_ARENA_MAX_ROUNDS > 100 +#error VAS_ARENA_MAX_ROUNDS 必须在 1..100 范围内 +#endif +#if VAS_ARENA_VERBOSE != 0 && VAS_ARENA_VERBOSE != 1 +#error VAS_ARENA_VERBOSE 只能是 0 或 1 +#endif diff --git a/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Demo.vas b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Demo.vas new file mode 100644 index 000000000..da0e73488 --- /dev/null +++ b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Demo.vas @@ -0,0 +1,70 @@ +import Report; +import Checks; + +namespace Arena +{ + int32 RunDemo(bool bVerbose) + { + println("=== VAS 模块化竞技场 v{} ===", VAS_ARENA_VERSION); + println("配置:最多 {} 回合,暴击率 {}%,日志宏 = {}", VAS_ARENA_MAX_ROUNDS, VAS_ARENA_CRIT_PERCENT, VAS_ARENA_VERBOSE); + // Configuration macros are exported transitively; print accepts primitives and concatenation. + print("预览:暴击伤害 = "); + print(VAS_ARENA_CRITICAL_DAMAGE(18)); + println(" | " + "固定种子保证战斗可重放"); + if (!AreSelfTestsPassing()) + { + return 1; + } + + array Standings; + Standings.reserve(3); + for (uint32 Index = 0; Index < 3; ++Index) + { + Standings.insertLast(FStanding(CreateCombatant(Index).Name)); + } + uint32 MatchCount = 0; + for (uint32 Left = 0; Left < 3; ++Left) + { + for (uint32 Right = Left + 1; Right < 3; ++Right) + { + ++MatchCount; + println(); + println("[比赛 {}] {} vs {}", MatchCount, Standings[Left].Name, Standings[Right].Name); + FBattleResult@ Result = SimulateBattle(CreateCombatant(Left), CreateCombatant(Right), 42 + MatchCount, bVerbose); + RecordResult(Standings[Left], Standings[Right], Result); + println("战报:{},{} 回合,剩余 HP = {} / {}", + GetWinnerLabel(Result), Result.RoundCount, Result.LeftHealth, Result.RightHealth); + } + } + PrintStandings(Standings); + println("TOURNAMENT matches={} leader={} points={}", MatchCount, Standings[0].Name, Standings[0].GetPoints()); + return 0; + } + + void RunBatch(uint32 Count) + { + // Suppress round logs; create fresh combatants and change the seed for every battle. + uint32 Wins = 0; + uint32 Losses = 0; + uint32 Draws = 0; + uint64 Checksum = 0; + for (uint32 Index = 0; Index < Count; ++Index) + { + FBattleResult@ Result = SimulateBattle(CreateCombatant(0), CreateCombatant(1), 42 + Index, false); + if (Result.WinnerIndex == 0) + { + ++Wins; + } + else if (Result.WinnerIndex == 1) + { + ++Losses; + } + else + { + ++Draws; + } + Checksum += uint64(Result.LeftHealth * 1000 + Result.RightHealth + Result.RoundCount); + } + println("BATCH count={} wins={} losses={} draws={} checksum={}", Count, Wins, Losses, Draws, Checksum); + } +} diff --git a/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Math.vas b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Math.vas new file mode 100644 index 000000000..e7dfe6425 --- /dev/null +++ b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Math.vas @@ -0,0 +1,29 @@ +namespace Arena +{ + int32 Clamp(int32 Value, int32 Lower, int32 Upper) + { + return Value < Lower ? Lower : Value > Upper ? Upper : Value; + } + + // A seeded generator for reproducible simulation, not cryptography. + class FDeterministicRandom + { + FDeterministicRandom(uint32 Seed) + { + State = Seed; + } + + uint32 Next() + { + State = State * uint32(1664525) + uint32(1013904223); + return State; + } + + uint32 NextBelow(uint32 Upper) + { + return Upper == 0 ? 0 : Next() % Upper; + } + + private uint32 State; + } +} diff --git a/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Report.vas b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Report.vas new file mode 100644 index 000000000..bef894cb9 --- /dev/null +++ b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Report.vas @@ -0,0 +1,84 @@ +import Battle; + +namespace Arena +{ + class FStanding + { + string Name; + int32 Wins = 0; + int32 Draws = 0; + int32 Losses = 0; + int32 DamageDealt = 0; + int32 HealingDone = 0; + + FStanding(const string&in Label) + { + Name = Label; + } + int32 GetPoints() const + { + return Wins * 3 + Draws; + } + } + + void RecordResult(FStanding@ Left, FStanding@ Right, FBattleResult@ Result) + { + Left.DamageDealt += Result.LeftDamageDealt; + Right.DamageDealt += Result.RightDamageDealt; + Left.HealingDone += Result.LeftHealingDone; + Right.HealingDone += Result.RightHealingDone; + if (Result.WinnerIndex == 0) + { + ++Left.Wins; + ++Right.Losses; + } + else if (Result.WinnerIndex == 1) + { + ++Right.Wins; + ++Left.Losses; + } + else + { + ++Left.Draws; + ++Right.Draws; + } + } + + bool ShouldRankBefore(FStanding@ Left, FStanding@ Right) + { + if (Left.GetPoints() != Right.GetPoints()) + { + return Left.GetPoints() > Right.GetPoints(); + } + if (Left.DamageDealt != Right.DamageDealt) + { + return Left.DamageDealt > Right.DamageDealt; + } + return Left.Name < Right.Name; // Keep tied rankings deterministic. + } + + void PrintStandings(array&inout Standings) + { + // Insertion sort suits this small table; move handles instead of copying statistics. + for (uint32 Index = 1; Index < Standings.length(); ++Index) + { + FStanding@ Current = Standings[Index]; + uint32 InsertionIndex = Index; + while (InsertionIndex > 0 && ShouldRankBefore(Current, Standings[InsertionIndex - 1])) + { + @Standings[InsertionIndex] = Standings[InsertionIndex - 1]; + --InsertionIndex; + } + @Standings[InsertionIndex] = Current; + } + println(); + println("[排行榜:胜 3 分 / 平 1 分 / 负 0 分]"); + println("{:<8} {:>4} {:>4} {:>4} {:>4} {:>6} {:>6}", "角色", "积分", "胜", "平", "负", "伤害", "治疗"); + for (uint32 Index = 0; Index < Standings.length(); ++Index) + { + FStanding@ Row = Standings[Index]; + println("{:<8} {:>4d} {:>4d} {:>4d} {:>4d} {:>6d} {:>6d}", + Row.Name, Row.GetPoints(), Row.Wins, Row.Draws, Row.Losses, Row.DamageDealt, Row.HealingDone); + } + } +} diff --git a/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Skills.vas b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Skills.vas new file mode 100644 index 000000000..ab1031c58 --- /dev/null +++ b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/Arena/Skills.vas @@ -0,0 +1,52 @@ +import Combatant; + +namespace Arena +{ + interface ICombatSkill + { + string GetLabel() const; + int32 Execute(FCombatant@ Actor, FCombatant@ Target, FDeterministicRandom@ Random); + } + + // Invoke implementations through ICombatSkill@ to demonstrate dynamic dispatch. + class FAttackSkill : ICombatSkill + { + string GetLabel() const + { + return "攻击"; + } + + int32 Execute(FCombatant@ Actor, FCombatant@ Target, FDeterministicRandom@ Random) + { + if (Actor is null || Target is null || Random is null) + { + return 0; + } + if (!Actor.IsAlive() || !Target.IsAlive()) + { + return 0; + } + int32 Amount = Actor.Attack; + if (Random.NextBelow(100) < VAS_ARENA_CRIT_PERCENT) + { + Amount = VAS_ARENA_CRITICAL_DAMAGE(Amount); + } + int32 Actual = Target.ApplyDamage(Clamp(Amount - Target.Armor, 0, Target.Health)); + Actor.DamageDealt += Actual; + return Actual; + } + } + + class FHealSkill : ICombatSkill + { + string GetLabel() const + { + return "治疗"; + } + + int32 Execute(FCombatant@ Actor, FCombatant@ Target, FDeterministicRandom@ Random) + { + return Actor is null ? 0 : Actor.RestoreHealth(18); + } + } +} diff --git a/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/main.vas b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/main.vas new file mode 100644 index 000000000..3e3e9a3db --- /dev/null +++ b/tools/rider-plugin/testData/solutions/vas-navigation/src/arena/main.vas @@ -0,0 +1,36 @@ +// Configure macros before import; dependencies share this environment. +#ifndef VAS_ARENA_VERBOSE +#define VAS_ARENA_VERBOSE 1 +#endif +import Arena.Demo; +#include "Arena/Demo.vas" +#include + +int32 main() +{ + array@ Args = getCommandLineArgs(); + if (Args.length() == 0) + { + return Arena::RunDemo(true); + } + if (Args.length() == 1 && Args[0] == "--quiet") + { + return Arena::RunDemo(false); + } + if (Args.length() == 1 && Args[0] == "--self-test") + { + return Arena::AreSelfTestsPassing() ? 0 : 1; + } + if (Args.length() == 2 && Args[0] == "--batch") + { + uint32 ParsedCharacters = 0; + uint64 Count = parseUInt(Args[1], 10, ParsedCharacters); + if (ParsedCharacters == Args[1].length() && Count >= 1 && Count <= 100000) + { + Arena::RunBatch(uint32(Count)); + return 0; + } + } + println("用法:vasrun main.vas [--quiet | --self-test | --batch 1..100000]"); + return 2; +} diff --git a/tools/visualstudio-extension/Build/NativeProcess.cs b/tools/visualstudio-extension/Build/NativeProcess.cs index 6d8f2dcb0..4ae8d5ff0 100644 --- a/tools/visualstudio-extension/Build/NativeProcess.cs +++ b/tools/visualstudio-extension/Build/NativeProcess.cs @@ -83,16 +83,18 @@ public static string QuoteArgument(string value) /// The guard and line sink run on background threads; both must return promptly. public static Task RunAsync(string executable, IReadOnlyList args, string cwd, - TimeSpan timeout, long stdoutLimit, CancellationToken cancellationToken, Action guard = null, Action lineSink = null) + TimeSpan timeout, long stdoutLimit, CancellationToken cancellationToken, Action guard = null, Action lineSink = null, + IReadOnlyDictionary environment = null) { if (args == null) throw new ArgumentNullException(nameof(args)); // Copy mutable callers' arrays before queuing work. string[] copy = args.ToArray(); - return Task.Run(() => Run(executable, copy, cwd, timeout, stdoutLimit, cancellationToken, guard, lineSink), cancellationToken); + var env = environment?.ToDictionary(p => p.Key, p => p.Value); + return Task.Run(() => Run(executable, copy, cwd, timeout, stdoutLimit, cancellationToken, guard, lineSink, env), cancellationToken); } private static ProcessResult Run(string executable, IReadOnlyList args, string cwd, - TimeSpan timeout, long stdoutLimit, CancellationToken token, Action guard, Action sink) + TimeSpan timeout, long stdoutLimit, CancellationToken token, Action guard, Action sink, IReadOnlyDictionary environment) { if (!FullyQualifiedPath(executable) || !FullyQualifiedPath(cwd)) throw new IOException("Compiler and working-directory paths must be absolute."); if (timeout <= TimeSpan.Zero || stdoutLimit < 0 || stdoutLimit > int.MaxValue) throw new ArgumentOutOfRangeException(nameof(timeout)); @@ -108,6 +110,7 @@ private static ProcessResult Run(string executable, IReadOnlyList args, Exception primary = null; try { + if (environment != null) foreach (var entry in environment) process.StartInfo.EnvironmentVariables[entry.Key] = entry.Value; token.ThrowIfCancellationRequested(); launched = process.Start(); if (!launched) throw new IOException("The native VAS compiler could not be started."); diff --git a/tools/visualstudio-extension/Editor/CallHelp.cs b/tools/visualstudio-extension/Editor/CallHelp.cs new file mode 100644 index 000000000..73648d879 --- /dev/null +++ b/tools/visualstudio-extension/Editor/CallHelp.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel.Composition; +using System.Linq; +using Microsoft.VisualStudio.Language.Intellisense; +using Microsoft.VisualStudio.Text; +using Microsoft.VisualStudio.Utilities; + +namespace VerseAngelScript.VisualStudio.Editor +{ + internal sealed class CallSite { internal string Name; internal int NameOffset, Open, Parameter; } + internal static class CallHelp + { + internal static CallSite Find(string text, int offset) { + var source = LanguageModel.Parse(text, ""); var stack = new Stack(); Token previous = null; + foreach (var token in source.Tokens) { + if (token.Start >= offset) break; + if (new[] { "(", "[", "{" }.Contains(token.Text)) stack.Push(new CallSite { Name = token.Text == "(" && previous?.Kind == "id" ? previous.Text : "", NameOffset = previous?.Start ?? 0, Open = token.Start }); + else if (new[] { ")", "]", "}" }.Contains(token.Text)) { if (stack.Count > 0) stack.Pop(); } + else if (token.Text == "," && stack.Count > 0) stack.Peek().Parameter++; + previous = token; + } + return stack.FirstOrDefault(c => c.Name.Length > 0 && !new[] { "if", "for", "while", "switch", "catch" }.Contains(c.Name)); + } + internal static List Parameters(string label) { + var tokens = LanguageModel.Parse(label, "").Tokens; var ranges = new List(); + int open = tokens.FindIndex(t => t.Text == "("), depth = 0; + if (open < 0) return ranges; + int begin = tokens[open].End; + foreach (var token in tokens.Skip(open + 1)) { + if (new[] { "(", "[", "{", "<" }.Contains(token.Text)) depth++; + else if (token.Text == ")" && depth == 0 || token.Text == "," && depth == 0) { + int start = begin, end = token.Start; + while (start < end && char.IsWhiteSpace(label[start])) start++; + while (end > start && char.IsWhiteSpace(label[end - 1])) end--; + if (end > start) ranges.Add(new Span(start, end - start)); + begin = token.End; if (token.Text == ")") break; + } else if (new[] { ")", "]", "}", ">" }.Contains(token.Text)) depth--; + } + return ranges; + } + } + [Export(typeof(ISignatureHelpSourceProvider)), Name("VAS parameters"), ContentType("text")] + internal sealed class SignatureProvider : ISignatureHelpSourceProvider { + [Import] internal EditorWorkspace Workspace = null; + public ISignatureHelpSource TryCreateSignatureHelpSource(ITextBuffer buffer) { var state = Workspace.Get(buffer); return state == null ? null : new SignatureSource(state); } + } + internal sealed class SignatureSource : ISignatureHelpSource { + private readonly DocumentState state; + internal SignatureSource(DocumentState state) { this.state = state; } + public void AugmentSignatureHelpSession(ISignatureHelpSession session, IList signatures) { + var snapshot = state.Buffer.CurrentSnapshot; var point = session.GetTriggerPoint(snapshot); if (point == null || snapshot != state.AnalyzedSnapshot) return; + var call = CallHelp.Find(snapshot.GetText(), point.Value.Position); if (call == null) return; + var declarations = LanguageModel.Resolve(state.Graph, state.Current, call.NameOffset).Where(s => s.Kind == "function" || s.Kind == "method").Select(s => s.Detail).Distinct().ToList(); + if (declarations.Count == 0 && (call.Name == "print" || call.Name == "println")) declarations.Add(call.Name + "(const string &in Format, const ?&in Arguments...)"); + var ours = declarations.Select(label => new Signature(state.Buffer, label, snapshot.CreateTrackingSpan(call.Open + 1, point.Value.Position - call.Open - 1, SpanTrackingMode.EdgeInclusive), call.Parameter)).ToList(); + foreach (var signature in ours) signatures.Add(signature); + EventHandler dismissed = null; + dismissed = (sender, args) => { foreach (var signature in ours) signature.Dispose(); session.Dismissed -= dismissed; }; + session.Dismissed += dismissed; + } + public ISignature GetBestMatch(ISignatureHelpSession session) { + var call = CallHelp.Find(state.Buffer.CurrentSnapshot.GetText(), session.TextView.Caret.Position.BufferPosition.Position); + return session.Signatures.FirstOrDefault(s => s.Parameters.Count > (call?.Parameter ?? 0)) ?? session.Signatures.FirstOrDefault(); + } + public void Dispose() { } + } + internal sealed class Signature : ISignature, IDisposable { + private readonly ITextBuffer buffer; + public string Content { get; } + public string PrettyPrintedContent => Content; + public string Documentation => "VAS function parameters"; + public ITrackingSpan ApplicableToSpan { get; } + public ReadOnlyCollection Parameters { get; } + public IParameter CurrentParameter { get; private set; } + public event EventHandler CurrentParameterChanged; + internal Signature(ITextBuffer buffer, string label, ITrackingSpan span, int index) { + this.buffer = buffer; Content = label; ApplicableToSpan = span; + Parameters = CallHelp.Parameters(label).Select(p => (IParameter)new Parameter(this, label.Substring(p.Start, p.Length), p)).ToList().AsReadOnly(); + CurrentParameter = index < Parameters.Count ? Parameters[index] : null; + buffer.Changed += Changed; + } + private void Changed(object sender, TextContentChangedEventArgs args) { + int offset = ApplicableToSpan.GetEndPoint(args.After).Position; + var call = CallHelp.Find(args.After.GetText(), offset); int index = call?.Parameter ?? -1; + var next = index >= 0 && index < Parameters.Count ? Parameters[index] : null; + if (next != CurrentParameter) { var before = CurrentParameter; CurrentParameter = next; CurrentParameterChanged?.Invoke(this, new CurrentParameterChangedEventArgs(before, next)); } + if (call == null) buffer.Changed -= Changed; + } + public void Dispose() { buffer.Changed -= Changed; } + } + internal sealed class Parameter : IParameter { + public ISignature Signature { get; } + public string Name { get; } + public string Documentation => Name; + public Span Locus { get; } + public Span PrettyPrintedLocus => Locus; + internal Parameter(ISignature signature, string name, Span span) { Signature = signature; Name = name; Locus = span; } + } +} diff --git a/tools/visualstudio-extension/Editor/LanguageModel.cs b/tools/visualstudio-extension/Editor/LanguageModel.cs new file mode 100644 index 000000000..a7dbf9b17 --- /dev/null +++ b/tools/visualstudio-extension/Editor/LanguageModel.cs @@ -0,0 +1,252 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +using Newtonsoft.Json.Linq; + +namespace VerseAngelScript.VisualStudio.Editor +{ + // Read-only editor declarations. Conditional activation/expansion and overload + // validation remain compiler-owned; uncertain definitions are returned as candidates. + internal sealed class Token + { + internal string Text, Kind; + internal int Start, End; + } + internal sealed class Symbol + { + internal string Name, Kind, File, Container, Type, Detail; + internal int Start, End, ScopeStart, ScopeEnd; + internal bool Exported; + internal string QualifiedName => string.IsNullOrEmpty(Container) ? Name : Container + "::" + Name; + } + internal sealed class Include + { + internal string Path, Kind; + internal int Start, End; + } + internal sealed class Source + { + internal string Text, File; + internal readonly List Tokens = new List(); + internal readonly List DirectiveWords = new List(); + internal readonly List Symbols = new List(); + internal readonly List Includes = new List(); + internal readonly List Problems = new List(); + } + internal sealed class SyntaxIssue { internal int Start, End; internal string Message; } + internal static class LanguageModel + { + internal static readonly HashSet Keywords = new HashSet(("abstract auto bool break case cast class const continue default do double else enum explicit external false final float for foreach from funcdef get if import in inout int int8 int16 int32 int64 interface is mixin namespace null out override private protected property public return set shared string super switch this true try typedef uint uint8 uint16 uint32 uint64 void while").Split(' ')); + internal static readonly string[] Runtime = { "print", "println", "getCommandLineArgs", "getSystemTime", "assert", "formatInt", "formatUInt", "formatFloat", "parseInt", "parseUInt", "parseFloat" }; + private static readonly HashSet Modifiers = new HashSet(new[] { "const", "private", "protected", "public", "shared", "external", "explicit", "import" }); + private static readonly HashSet NonTypes = new HashSet(new[] { "return", "new", "throw", "case", "else", "break", "continue", "namespace", "class", "interface", "enum" }); + private static readonly Regex Lexer = new Regex("\\s+|//[^\\r\\n]*|/\\*[\\s\\S]*?(?:\\*/|$)|\"\"\"[\\s\\S]*?(?:\"\"\"|$)|\"(?:\\\\[\\s\\S]|[^\"\\\\])*(?:\"|$)|'(?:\\\\[\\s\\S]|[^'\\\\])*(?:'|$)|0[xX][\\da-fA-F](?:[\\da-fA-F]|'(?=[\\da-fA-F]))*|0[bB][01](?:[01]|'(?=[01]))*|0[oO][0-7](?:[0-7]|'(?=[0-7]))*|0[dD]\\d(?:\\d|'(?=\\d))*|(?:\\d(?:\\d|'(?=\\d))*(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?[fF]?|[\\p{L}_][\\p{L}\\p{N}_]*|::|==|!=|<=|>=|&&|\\|\\||[\\s\\S]", RegexOptions.Compiled, TimeSpan.FromSeconds(1)); + private sealed class Scope + { + internal string Kind, Name; + internal int Start, End; + } + internal static bool IsCode(string text, int offset) { + foreach (Match match in Lexer.Matches(text)) { + if (match.Index > offset) break; + if (match.Index <= offset && offset < match.Index + match.Length) return !(match.Value.StartsWith("//") || match.Value.StartsWith("/*") || match.Value[0] == '"' || match.Value[0] == '\''); + if (offset == text.Length && match.Index + match.Length == offset) { + if (match.Value.StartsWith("//") || match.Value.StartsWith("/*") && !match.Value.EndsWith("*/")) return false; + if (match.Value[0] == '"' || match.Value[0] == '\'') return match.Value.Length > 1 && match.Value[match.Value.Length - 1] == match.Value[0]; + } + } + return true; + } + internal static Source Parse(string text, string file) + { + var model = new Source { Text = text, File = file }; + if (text.Length > 4 * 1024 * 1024) return model; + for (var match = Lexer.Match(text); match.Success; match = match.NextMatch()) + { + string value = match.Value; + if (value.StartsWith("/*") && !value.EndsWith("*/")) model.Problems.Add(new SyntaxIssue { Start = match.Index, End = match.Index + 2, Message = "Unterminated block comment" }); + if (value[0] == '"' || value[0] == '\'') { + string delimiter = value.StartsWith("\"\"\"") ? "\"\"\"" : value.Substring(0, 1); int slashes = 0; + if (delimiter.Length == 1) for (int i = value.Length - 2; i >= 0 && value[i] == '\\'; i--) slashes++; + if (value.Length < delimiter.Length * 2 || !value.EndsWith(delimiter) || slashes % 2 != 0) + model.Problems.Add(new SyntaxIssue { Start = match.Index, End = match.Index + delimiter.Length, Message = "Unterminated string literal" }); + } + if (char.IsWhiteSpace(value[0]) || value.StartsWith("//") || value.StartsWith("/*")) continue; + if (value == "#") + { + int stop = text.IndexOf('\n', match.Index); if (stop < 0) stop = text.Length; + string directive = text.Substring(match.Index, stop - match.Index).TrimEnd('\r'); + foreach (Match word in Lexer.Matches(directive)) { + var token = ToToken(word); + if (token.Kind == "id") { token.Start += match.Index; token.End += match.Index; model.DirectiveWords.Add(token); } + } + var include = Regex.Match(directive, "^#include\\s*(?:\"([^\"\\r\\n]+)\"|'([^'\\r\\n]+)'|<([^>\\r\\n]+)>)"); + if (include.Success) model.Includes.Add(new Include { Path = include.Groups[1].Success ? include.Groups[1].Value : include.Groups[2].Success ? include.Groups[2].Value : include.Groups[3].Value, Kind = include.Groups[3].Success ? "system" : "quoted", Start = match.Index, End = match.Index + include.Length }); + var macro = Regex.Match(directive, "^#define[ \\t]+([A-Za-z_]\\w*)(.*)"); + if (macro.Success) model.Symbols.Add(new Symbol { Name = macro.Groups[1].Value, Kind = "macro", File = file, Start = match.Index + macro.Groups[1].Index, End = match.Index + macro.Groups[1].Index + macro.Groups[1].Length, Container = "", ScopeEnd = text.Length, Exported = true, Detail = directive }); + match = Lexer.Match(text, stop); if (!match.Success) break; + // The next match starts at the end of this directive (usually a newline). + if (!char.IsWhiteSpace(match.Value[0])) model.Tokens.Add(ToToken(match)); + continue; + } + model.Tokens.Add(ToToken(match)); + } + var t = model.Tokens; var pairs = new Dictionary(); var brackets = new Stack(); + for (int i = 0; i < t.Count; i++) + { + if (new[] { "(", "[", "{" }.Contains(t[i].Text)) brackets.Push(i); + else if (new[] { ")", "]", "}" }.Contains(t[i].Text)) { + if (brackets.Count == 0 || "([{".IndexOf(t[brackets.Peek()].Text) != ")]}".IndexOf(t[i].Text)) + model.Problems.Add(new SyntaxIssue { Start = t[i].Start, End = t[i].End, Message = "Unexpected '" + t[i].Text + "'" }); + else pairs[brackets.Pop()] = i; + } + } + if (Regex.IsMatch(text, "(?m)^\\s*#(?:if|ifdef|ifndef)\\b")) model.Problems.RemoveAll(p => p.Message.StartsWith("Unexpected")); + else foreach (int left in brackets) model.Problems.Add(new SyntaxIssue { Start = t[left].Start, End = t[left].End, Message = "Expected '" + ")]}"["([{".IndexOf(t[left].Text)] + "'" }); + var scopes = new List(); var bodies = new Dictionary(); var declarations = new HashSet(); + Func container = () => string.Join("::", scopes.Where(s => new[] { "namespace", "class", "interface", "enum" }.Contains(s.Kind)).Select(s => s.Name)); + Func inFunction = () => scopes.Any(s => s.Kind == "function"); + Func at = i => i >= 0 && i < t.Count ? t[i].Text : ""; + Func add = (i, kind) => + { + declarations.Add(i); var scope = scopes.LastOrDefault(); + var symbol = new Symbol { Name = t[i].Text, Kind = kind, File = file, Start = t[i].Start, End = t[i].End, Container = container(), ScopeStart = scope?.Start ?? 0, ScopeEnd = scope?.End ?? text.Length, Exported = !inFunction(), Detail = "" }; + model.Symbols.Add(symbol); return symbol; + }; + Func typeBefore = i => + { + int j = i - 1; + while (new[] { "@", "&", "const", "in", "out", "inout" }.Contains(at(j))) j--; + if (at(j) == ">") { int depth = 1; while (--j >= 0 && depth > 0) { if (at(j) == ">") depth++; if (at(j) == "<") depth--; } } + if (j < 0 || t[j].Kind != "id" || NonTypes.Contains(at(j))) return null; + int end = j; while (j >= 2 && at(j - 1) == "::" && t[j - 2].Kind == "id") j -= 2; + string name = string.Concat(t.Skip(j).Take(end - j + 1).Select(x => x.Text)); + int head = j - 1; while (head >= 0 && Modifiers.Contains(at(head))) head--; + return head >= 0 && !new[] { ";", "{", "}", "(", "," }.Contains(at(head)) ? null : name; + }; + for (int i = 0; i < t.Count; i++) + { + var token = t[i]; string next = at(i + 1); + if (token.Text == "{") { scopes.Add(bodies.TryGetValue(i, out var body) ? body : new Scope { Kind = "block", Name = "", Start = token.Start, End = pairs.TryGetValue(i, out int end) ? t[end].End : text.Length }); continue; } + if (token.Text == "}") { if (scopes.Count > 0) scopes.RemoveAt(scopes.Count - 1); continue; } + if (token.Text == "import" && scopes.Count == 0) + { + int j = i + 1; var parts = new List(); + while (j < t.Count && t[j].Kind == "id" && !Keywords.Contains(at(j))) { parts.Add(at(j++)); if (at(j) != ".") break; j++; } + if (parts.Count > 0 && at(j) == ";") { model.Includes.Add(new Include { Path = string.Join("/", parts) + ".vas", Kind = "module", Start = token.Start, End = t[j].End }); i = j; continue; } + } + if (new[] { "namespace", "class", "interface", "enum" }.Contains(token.Text) && i + 1 < t.Count && t[i + 1].Kind == "id") + { + int j = i + 2; while (j < t.Count && at(j) != "{" && at(j) != ";") j++; + var type = add(i + 1, token.Text); + if (at(j) == "{") bodies[j] = new Scope { Kind = token.Text, Name = type.Name, Start = t[j].Start, End = pairs.TryGetValue(j, out int end) ? t[end].End : text.Length }; + continue; + } + if (token.Kind != "id" || Keywords.Contains(token.Text) || declarations.Contains(i)) continue; + if (next == "(" && pairs.TryGetValue(i + 1, out int close) && !inFunction()) + { + int tail = close + 1; while (new[] { "const", "override", "final", "property" }.Contains(at(tail))) tail++; + string type = typeBefore(i); var owner = scopes.LastOrDefault(); + bool ctor = owner?.Name == token.Text && new[] { "class", "interface" }.Contains(owner.Kind); + if ((type != null || ctor) && (new[] { "{", ";" }.Contains(at(tail)) || at(tail) == "from" && tail + 1 < t.Count && t[tail + 1].Kind == "string" && at(tail + 2) == ";")) + { + int start = at(tail) == "{" ? t[tail].Start : text.Length, end = pairs.TryGetValue(tail, out int bodyEnd) ? t[bodyEnd].End : start; + int partStart = i + 2, depth = 0; var parameters = new List(); + for (int j = partStart; j <= close; j++) + { + if (new[] { "(", "[", "<" }.Contains(at(j))) depth++; + if (new[] { ")", "]", ">" }.Contains(at(j)) && j != close) depth--; + if (j == close || at(j) == "," && depth == 0) + { + var part = t.Skip(partStart).Take(j - partStart).ToList(); + if (part.Count > 0) parameters.Add(text.Substring(part[0].Start, part.Last().End - part[0].Start)); + var before = part.TakeWhile(x => x.Text != "=").ToList(); var name = before.LastOrDefault(x => x.Kind == "id" && !Keywords.Contains(x.Text)); + if (name != null && before.IndexOf(name) > 0) { int atName = t.IndexOf(name); var parameter = add(atName, "parameter"); parameter.Type = typeBefore(atName); parameter.ScopeStart = start; parameter.ScopeEnd = end; parameter.Exported = false; } + partStart = j + 1; + } + } + var fn = add(i, scopes.Any(s => s.Kind == "class" || s.Kind == "interface") ? "method" : "function"); fn.Type = type; fn.Detail = (type ?? "") + " " + token.Text + "(" + string.Join(", ", parameters) + ")"; + if (at(tail) == "{") bodies[tail] = new Scope { Kind = "function", Name = fn.Name, Start = start, End = end }; + i = close; continue; + } + } + string variableType = typeBefore(i); + if (variableType != null && new[] { "=", ";", ",", "[" }.Contains(next)) { var variable = add(i, !inFunction() && scopes.Any(s => s.Kind == "class" || s.Kind == "interface") ? "property" : "variable"); variable.Type = variableType; } + else if (scopes.LastOrDefault()?.Kind == "enum" && new[] { "=", ",", "}" }.Contains(next)) { var value = add(i, "enumMember"); value.Type = container(); value.Container = string.Join("::", scopes.Where(s => new[] { "namespace", "class", "interface" }.Contains(s.Kind)).Select(s => s.Name)); } + } + return model; + } + private static Token ToToken(Match match) => new Token { Text = match.Value, Start = match.Index, End = match.Index + match.Length, Kind = match.Value[0] == '"' || match.Value[0] == '\'' ? "string" : char.IsLetter(match.Value[0]) || match.Value[0] == '_' ? "id" : char.IsDigit(match.Value[0]) ? "number" : "punctuation" }; + + internal static List Resolve(IReadOnlyList graph, Source model, int offset) + { + var word = model.Tokens.FirstOrDefault(t => t.Kind == "id" && t.Start <= offset && offset <= t.End); + if (word == null) return new List(); + var own = model.Symbols.FirstOrDefault(s => s.Start == word.Start); if (own != null) return new List { own }; + var all = graph.SelectMany(m => m.Symbols.Where(s => m == model || s.Exported)).ToList(); + var locals = model.Symbols.Where(s => s.Name == word.Text && !s.Exported && s.Start <= offset && s.ScopeStart <= offset && offset <= s.ScopeEnd).OrderBy(s => s.ScopeEnd - s.ScopeStart).ThenByDescending(s => s.Start).ToList(); + if (locals.Count > 0) return locals.Take(1).ToList(); + var t = model.Tokens; int index = t.IndexOf(word); + if (index >= 2 && t[index - 1].Text == ".") + { + var receiver = Resolve(graph, model, t[index - 2].Start); + if (receiver.Count != 1 || string.IsNullOrEmpty(receiver[0].Type)) return new List(); + string type = receiver[0].Type, qualified = receiver[0].Container + "::" + type; + return all.Where(s => s.Name == word.Text && (s.Container == type || s.Container == qualified)).ToList(); + } + string qualifier = ""; int j = index; + while (j >= 2 && t[j - 1].Text == "::" && t[j - 2].Kind == "id") { qualifier = t[j - 2].Text + (qualifier.Length == 0 ? "" : "::" + qualifier); j -= 2; } + if (qualifier.Length > 0) { + string lexical = model.Symbols.Where(s => s.Start <= offset && s.ScopeStart <= offset && offset <= s.ScopeEnd).OrderByDescending(s => s.Container?.Length ?? 0).FirstOrDefault()?.Container ?? ""; + var owners = new List { qualifier }; + for (;;) { if (lexical.Length > 0) owners.Add(lexical + "::" + qualifier); int last = lexical.LastIndexOf("::", StringComparison.Ordinal); if (last < 0) break; lexical = lexical.Substring(0, last); } + foreach (string scope in owners) { var matches = all.Where(s => s.Name == word.Text && (s.Container == scope || s.Kind == "enumMember" && s.Type == scope)).ToList(); if (matches.Count > 0) return matches; } + return new List(); + } + var candidates = all.Where(s => s.Name == word.Text && s.Exported).ToList(); + string owner = model.Symbols.Where(s => s.Start <= offset && s.ScopeStart <= offset && offset <= s.ScopeEnd).OrderByDescending(s => s.Container?.Length ?? 0).FirstOrDefault()?.Container ?? ""; + for (;;) { var selected = candidates.Where(s => s.Container == owner).ToList(); if (selected.Count > 0) return selected; if (owner.Length == 0) break; int last = owner.LastIndexOf("::", StringComparison.Ordinal); owner = last < 0 ? "" : owner.Substring(0, last); } + return new List(); + } + + internal static List SearchRoots(string file) + { + var roots = new List(); string original = Path.GetDirectoryName(file), directory = original; + for (int depth = 0; directory != null && depth < 16; depth++, directory = Path.GetDirectoryName(directory)) + { + roots.Add(directory); + string manifest = Path.Combine(directory, "vas-project.json"); + if (System.IO.File.Exists(manifest)) + { + try { if (new FileInfo(manifest).Length < 1024 * 1024) foreach (var unit in JObject.Parse(System.IO.File.ReadAllText(manifest))["compilationUnits"] ?? new JArray()) if (unit["entry"]?.Type == JTokenType.String) roots.Add(Path.GetDirectoryName(Path.GetFullPath(Path.Combine(directory, (string)unit["entry"])))); } catch (Exception e) when (e is IOException || e is Newtonsoft.Json.JsonException || e is ArgumentException) { } + break; + } + if (Directory.Exists(Path.Combine(directory, ".git")) || System.IO.File.Exists(Path.Combine(directory, ".git"))) break; + } + foreach (string root in (Environment.GetEnvironmentVariable("VAS_INCLUDE_PATH") ?? "").Split(Path.PathSeparator).Where(x => x.Length > 0)) roots.Add(Path.GetFullPath(Path.Combine(original, root))); + return roots.Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + } + internal static Source Dependency(string file, Include include, IReadOnlyList roots, Func read) + { + if (Path.IsPathRooted(include.Path) || include.Path.Contains(":")) return null; + string relative = include.Path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar); + if (include.Kind != "system") { var local = read(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(file), relative))); if (local != null) return local; } + var matches = roots.Select(root => Path.GetFullPath(Path.Combine(root, relative))).Distinct(StringComparer.OrdinalIgnoreCase).Select(read).Where(m => m != null).ToList(); + return matches.Count == 1 ? matches[0] : null; + } + internal static List Graph(Source source, Func read, CancellationToken cancellation) + { + var roots = SearchRoots(source.File); var graph = new List(); var queue = new Queue(); queue.Enqueue(source); var visited = new HashSet(StringComparer.OrdinalIgnoreCase); int bytes = 0; + while (queue.Count > 0 && graph.Count < 256) + { + cancellation.ThrowIfCancellationRequested(); var model = queue.Dequeue(); + if (!visited.Add(model.File)) continue; bytes += model.Text.Length; if (bytes > 16 * 1024 * 1024) break; graph.Add(model); + foreach (var include in model.Includes) { var dependency = Dependency(model.File, include, roots, read); if (dependency != null) queue.Enqueue(dependency); } + } + return graph; + } + } +} diff --git a/tools/visualstudio-extension/Editor/LanguageServices.cs b/tools/visualstudio-extension/Editor/LanguageServices.cs new file mode 100644 index 000000000..e6f3336de --- /dev/null +++ b/tools/visualstudio-extension/Editor/LanguageServices.cs @@ -0,0 +1,332 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.ComponentModel.Composition; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.VisualStudio; +using Microsoft.VisualStudio.Editor; +using Microsoft.VisualStudio.Language.Intellisense; +using Microsoft.VisualStudio.OLE.Interop; +using Microsoft.VisualStudio.Shell; +using Microsoft.VisualStudio.Text; +using Microsoft.VisualStudio.Text.Classification; +using Microsoft.VisualStudio.Text.Editor; +using Microsoft.VisualStudio.TextManager.Interop; +using Microsoft.VisualStudio.Utilities; +using Microsoft.VisualStudio.Threading; + +namespace VerseAngelScript.VisualStudio.Editor +{ + [Export(typeof(EditorWorkspace))] + internal sealed class EditorWorkspace + { + [Import] internal ITextDocumentFactoryService Documents = null; + private readonly ConcurrentDictionary states = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + internal DocumentState Get(ITextBuffer buffer) + { + if (!Documents.TryGetTextDocument(buffer, out var document) || !document.FilePath.EndsWith(".vas", StringComparison.OrdinalIgnoreCase)) return null; + return states.GetOrAdd(document.FilePath, file => new DocumentState(buffer, file, this)); + } + internal Dictionary OpenSources() => states.ToDictionary(p => p.Key, p => p.Value.Buffer.CurrentSnapshot.GetText(), StringComparer.OrdinalIgnoreCase); + internal void Changed() { foreach (var state in states.Values) state.Refresh(); } + internal void Remove(DocumentState state) => states.TryRemove(state.File, out _); + } + + internal sealed class DocumentState + { + internal readonly ITextBuffer Buffer; + internal readonly string File; + internal IReadOnlyList Graph = new List(); + internal event EventHandler Updated; + private readonly EditorWorkspace workspace; + private CancellationTokenSource pending; + private JoinableTask ready; + private JoinableTask diagnosticTask; + private int generation; + internal ITextSnapshot AnalyzedSnapshot; + internal IReadOnlyList CompilerProblems = Array.Empty(); + private DateTime requested; + + internal DocumentState(ITextBuffer buffer, string file, EditorWorkspace workspace) + { + Buffer = buffer; File = file; this.workspace = workspace; + buffer.Changed += OnChanged; + if (workspace.Documents.TryGetTextDocument(buffer, out var document)) workspace.Documents.TextDocumentDisposed += OnDisposed; + Refresh(); + } + private void OnDisposed(object sender, TextDocumentEventArgs args) + { + if (args.TextDocument.TextBuffer != Buffer) return; + Buffer.Changed -= OnChanged; pending?.Cancel(); pending?.Dispose(); workspace.Remove(this); + workspace.Documents.TextDocumentDisposed -= OnDisposed; + workspace.Changed(); + } + private void OnChanged(object sender, TextContentChangedEventArgs args) { workspace.Changed(); } + internal void EnsureFresh() { if (DateTime.UtcNow - requested > TimeSpan.FromMilliseconds(500)) Refresh(); } + internal async Task WaitAsync() { if (ready != null) await ready.JoinAsync(); } + internal void Refresh() + { + pending?.Cancel(); pending?.Dispose(); var cancellation = new CancellationTokenSource(); pending = cancellation; + var token = cancellation.Token; + int revision = ++generation; var snapshot = Buffer.CurrentSnapshot; string text = snapshot.GetText(); + var open = workspace.OpenSources(); open[File] = text; requested = DateTime.UtcNow; + ready = ThreadHelper.JoinableTaskFactory.RunAsync(async () => + { + try + { + await TaskScheduler.Default; + await Task.Delay(75, token); + var loaded = new Dictionary(StringComparer.OrdinalIgnoreCase); + Func read = file => + { + token.ThrowIfCancellationRequested(); + if (loaded.TryGetValue(file, out var prior)) return prior; + Source source = null; + if (open.TryGetValue(file, out string unsaved)) source = LanguageModel.Parse(unsaved, file); + else if (System.IO.File.Exists(file) && new FileInfo(file).Length <= 4 * 1024 * 1024) source = LanguageModel.Parse(System.IO.File.ReadAllText(file), file); + loaded[file] = source; return source; + }; + var graph = LanguageModel.Graph(LanguageModel.Parse(text, File), read, token); + await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(token); + if (revision != generation || snapshot != Buffer.CurrentSnapshot) return; + Graph = graph; CompilerProblems = Array.Empty(); AnalyzedSnapshot = snapshot; Updated?.Invoke(this, EventArgs.Empty); + string compiler = LiveCompiler.ConfiguredCompiler(); + if (!string.IsNullOrWhiteSpace(compiler)) diagnosticTask = ThreadHelper.JoinableTaskFactory.RunAsync(async () => { + try { + await TaskScheduler.Default; await Task.Delay(400, token); + var problems = await LiveCompiler.InspectAsync(compiler, graph, token); + await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(token); + if (revision != generation || snapshot != Buffer.CurrentSnapshot) return; + CompilerProblems = problems.ToArray(); Updated?.Invoke(this, EventArgs.Empty); + } catch (OperationCanceledException) { } + }); + } + catch (OperationCanceledException) { } + catch (Exception e) when (e is IOException || e is UnauthorizedAccessException || e is ArgumentException || e is System.Text.RegularExpressions.RegexMatchTimeoutException) { } + }); + } + internal Source Current => Graph.FirstOrDefault(); + internal List Definitions(int offset) + { + if (Current == null || AnalyzedSnapshot != Buffer.CurrentSnapshot) return new List(); + var symbols = LanguageModel.Resolve(Graph, Current, offset); + if (symbols.Count > 0) return symbols; + // PREPROCESSOR leaves also permit macro definition navigation. + string text = Current.Text; int left = Math.Min(offset, text.Length), right = left; + while (left > 0 && (char.IsLetterOrDigit(text[left - 1]) || text[left - 1] == '_')) left--; + while (right < text.Length && (char.IsLetterOrDigit(text[right]) || text[right] == '_')) right++; + string name = text.Substring(left, right - left); + return Graph.SelectMany(m => m.Symbols).Where(s => s.Kind == "macro" && s.Name == name).ToList(); + } + internal List Completions(int offset) + { + if (Current == null || AnalyzedSnapshot != Buffer.CurrentSnapshot) return new List(); + var symbols = Graph.SelectMany(m => m.Symbols.Where(s => m != Current ? s.Exported : s.Exported || s.Start <= offset && s.ScopeStart <= offset && offset <= s.ScopeEnd)).ToList(); + var match = System.Text.RegularExpressions.Regex.Match(Current.Text.Substring(0, Math.Min(offset, Current.Text.Length)), "([\\p{L}_][\\p{L}\\p{N}_]*(?:::[\\p{L}_][\\p{L}\\p{N}_]*)*)(::|\\.)[\\p{L}\\p{N}_]*$"); + if (!match.Success) return symbols; + string owner = match.Groups[1].Value; + if (match.Groups[2].Value == ".") + { + var receiver = LanguageModel.Resolve(Graph, Current, match.Index); + if (receiver.Count != 1 || string.IsNullOrEmpty(receiver[0].Type)) return new List(); + string type = receiver[0].Type, qualified = receiver[0].Container + "::" + type; + owner = symbols.FirstOrDefault(s => (s.Kind == "class" || s.Kind == "interface") && (s.QualifiedName == type || s.QualifiedName == qualified))?.QualifiedName ?? type; + } + if (match.Groups[2].Value == "::" && !owner.Contains("::")) { + var identities = LanguageModel.Resolve(Graph, Current, match.Index).Where(s => new[] { "class", "interface", "enum", "namespace" }.Contains(s.Kind)).Select(s => s.QualifiedName).Distinct().ToList(); + if (identities.Count == 1) owner = identities[0]; + } + return symbols.Where(s => (s.Container == owner || s.Kind == "enumMember" && s.Type == owner) && s.Exported).ToList(); + } + } + + [Export(typeof(ICompletionSourceProvider)), Name("VAS completions"), ContentType("text")] + internal sealed class CompletionProvider : ICompletionSourceProvider + { + [Import] internal EditorWorkspace Workspace = null; + [Import] internal ISignatureHelpBroker Signatures = null; + public ICompletionSource TryCreateCompletionSource(ITextBuffer buffer) + { + var state = Workspace.Get(buffer); return state == null ? null : new CompletionSource(state, Signatures); + } + } + internal sealed class CompletionSource : ICompletionSource + { + private readonly DocumentState state; + private readonly ISignatureHelpBroker signatures; + internal CompletionSource(DocumentState state, ISignatureHelpBroker signatures) { this.state = state; this.signatures = signatures; } + public void AugmentCompletionSession(ICompletionSession session, IList sets) + { + ThreadHelper.ThrowIfNotOnUIThread(); + state.EnsureFresh(); var snapshot = state.Buffer.CurrentSnapshot; var point = session.GetTriggerPoint(snapshot); if (point == null) return; + int offset = point.Value.Position, start = offset; string text = snapshot.GetText(); + if (!LanguageModel.IsCode(text, offset)) return; + while (start > 0 && (char.IsLetterOrDigit(text[start - 1]) || text[start - 1] == '_')) start--; + int following = offset; while (following < text.Length && char.IsWhiteSpace(text[following])) following++; + bool addCall = following == text.Length || text[following] != '('; + var symbols = state.Completions(offset); var completions = symbols.GroupBy(s => s.Name).Select(g => new Completion(g.Key, + g.Key + (addCall && g.Any(s => s.Kind == "function" || s.Kind == "method") ? "()" : ""), + string.Join("\n", g.Select(s => (string.IsNullOrEmpty(s.Detail) ? s.Kind + " " + s.QualifiedName : s.Detail) + " — " + Path.GetFileName(s.File))), null, null)).ToList(); + if (start == 0 || text[start - 1] != '.' && text[start - 1] != ':') foreach (string name in LanguageModel.Keywords.Concat(LanguageModel.Runtime)) if (!completions.Any(c => c.DisplayText == name)) + completions.Add(new Completion(name, name + (addCall && LanguageModel.Runtime.Contains(name) ? "()" : ""), null, null, null)); + sets.Add(new CompletionSet("VAS", "VAS", snapshot.CreateTrackingSpan(start, offset - start, SpanTrackingMode.EdgeInclusive), completions.OrderBy(c => c.DisplayText), null)); + // Native IntelliSense may consume Tab before the view command filter. + // Put call syntax in InsertionText so every native commit route agrees. + if (!session.Properties.ContainsProperty(typeof(CompletionSource))) { + session.Properties.AddProperty(typeof(CompletionSource), true); + session.Committed += (sender, args) => { + var set = session.SelectedCompletionSet; var selected = set?.SelectionStatus.Completion; + if (set?.Moniker != "VAS" || selected == null || !selected.InsertionText.EndsWith("()", StringComparison.Ordinal)) return; + var functions = symbols.Where(s => s.Name == selected.DisplayText && (s.Kind == "function" || s.Kind == "method")).ToList(); + bool arguments = functions.Count == 0 || functions.Any(s => CallHelp.Parameters(s.Detail).Count > 0); + if (arguments) { + int end = set.ApplicableTo.GetEndPoint(state.Buffer.CurrentSnapshot).Position; + session.TextView.Caret.MoveTo(new SnapshotPoint(state.Buffer.CurrentSnapshot, Math.Max(0, end - 1))); + var committed = state.Buffer.CurrentSnapshot; + ThreadHelper.JoinableTaskFactory.RunAsync(async () => { + await state.WaitAsync(); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); + if (!session.TextView.IsClosed && committed == state.Buffer.CurrentSnapshot) signatures.TriggerSignatureHelp(session.TextView); + }).FileAndForget("VAS/CompletionParameters"); + } + }; + } + } + public void Dispose() { } + } + + [Export(typeof(IAsyncQuickInfoSourceProvider)), Name("VAS quick info"), ContentType("text")] + internal sealed class QuickInfoProvider : IAsyncQuickInfoSourceProvider + { + [Import] internal EditorWorkspace Workspace = null; + public IAsyncQuickInfoSource TryCreateQuickInfoSource(ITextBuffer buffer) + { var state = Workspace.Get(buffer); return state == null ? null : new QuickInfoSource(state); } + } + internal sealed class QuickInfoSource : IAsyncQuickInfoSource + { + private readonly DocumentState state; + internal QuickInfoSource(DocumentState state) { this.state = state; } + public async Task GetQuickInfoItemAsync(IAsyncQuickInfoSession session, CancellationToken cancellation) + { + await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(cancellation); + state.EnsureFresh(); await state.WaitAsync(); + cancellation.ThrowIfCancellationRequested(); + var point = session.GetTriggerPoint(state.Buffer.CurrentSnapshot); if (point == null) return null; + var word = state.Current?.Tokens.Concat(state.Current.DirectiveWords).FirstOrDefault(t => t.Start <= point.Value.Position && point.Value.Position <= t.End && t.Kind == "id"); + if (word == null || state.AnalyzedSnapshot != state.Buffer.CurrentSnapshot) return null; + var symbols = state.Definitions(point.Value.Position); if (symbols.Count == 0) return null; + var applicable = state.Buffer.CurrentSnapshot.CreateTrackingSpan(word.Start, word.End - word.Start, SpanTrackingMode.EdgeInclusive); + return new QuickInfoItem(applicable, string.Join("\n", symbols.Select(s => (string.IsNullOrEmpty(s.Detail) ? (s.Type ?? s.Kind) + " " + s.QualifiedName : s.Detail) + " — " + Path.GetFileName(s.File)))); + } + public void Dispose() { } + } + + [Export(typeof(IVsTextViewCreationListener)), Name("VAS commands"), ContentType("text"), TextViewRole(PredefinedTextViewRoles.Editable)] + internal sealed class ViewListener : IVsTextViewCreationListener + { + [Import] internal IVsEditorAdaptersFactoryService Adapters = null; + [Import] internal ICompletionBroker Completion = null; + [Import] internal ISignatureHelpBroker Signatures = null; + [Import] internal EditorWorkspace Workspace = null; + public void VsTextViewCreated(IVsTextView adapter) + { + ThreadHelper.ThrowIfNotOnUIThread(); + var view = Adapters.GetWpfTextView(adapter); if (view == null) return; + var state = Workspace.Get(view.TextBuffer); if (state != null) new Commands(adapter, view, state, Completion, Signatures); + } + } + internal sealed class Commands : IOleCommandTarget + { + private readonly IVsTextView adapter; private readonly IWpfTextView view; private readonly DocumentState state; private readonly ICompletionBroker broker; + private readonly ISignatureHelpBroker signatures; + private IOleCommandTarget next; private ICompletionSession session; + private readonly EventHandler analyzed; + internal Commands(IVsTextView adapter, IWpfTextView view, DocumentState state, ICompletionBroker broker, ISignatureHelpBroker signatures) + { + ThreadHelper.ThrowIfNotOnUIThread(); + this.adapter = adapter; this.view = view; this.state = state; this.broker = broker; + this.signatures = signatures; + analyzed = (sender, args) => { if (!view.IsClosed && session != null && !session.IsDismissed) session.Recalculate(); }; + state.Updated += analyzed; + ErrorHandler.ThrowOnFailure(adapter.AddCommandFilter(this, out next)); + view.Closed += (sender, args) => { state.Updated -= analyzed; session?.Dismiss(); adapter.RemoveCommandFilter(this); }; + } + public int QueryStatus(ref Guid group, uint count, OLECMD[] commands, IntPtr text) + { + ThreadHelper.ThrowIfNotOnUIThread(); + int result = next.QueryStatus(ref group, count, commands, text); + for (int i = 0; i < count; i++) if (group == VSConstants.GUID_VSStandardCommandSet97 && commands[i].cmdID == (uint)VSConstants.VSStd97CmdID.GotoDefn || group == VSConstants.VSStd2K && new[] { (uint)VSConstants.VSStd2KCmdID.AUTOCOMPLETE, (uint)VSConstants.VSStd2KCmdID.COMPLETEWORD, (uint)VSConstants.VSStd2KCmdID.SHOWMEMBERLIST, (uint)VSConstants.VSStd2KCmdID.PARAMINFO }.Contains(commands[i].cmdID)) + commands[i].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED | OLECMDF.OLECMDF_ENABLED); + return commands.Take((int)count).Any(c => (c.cmdf & (uint)OLECMDF.OLECMDF_SUPPORTED) != 0) ? VSConstants.S_OK : result; + } + public int Exec(ref Guid group, uint id, uint options, IntPtr input, IntPtr output) + { + ThreadHelper.ThrowIfNotOnUIThread(); + if (group == VSConstants.GUID_VSStandardCommandSet97 && id == (uint)VSConstants.VSStd97CmdID.GotoDefn) + { + int offset = view.Caret.Position.BufferPosition.Position; + ThreadHelper.JoinableTaskFactory.RunAsync(async () => + { + state.EnsureFresh(); await state.WaitAsync(); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); + var include = state.Current?.Includes.FirstOrDefault(i => i.Start <= offset && offset < i.End); + Symbol target; + if (include != null) + { + // Resolve only files already in the analyzed closure: never perform disk IO on the UI thread. + var candidates = state.Graph.Where(s => s.File.Replace('\\', '/').EndsWith("/" + include.Path.Replace('\\', '/'), StringComparison.OrdinalIgnoreCase)).ToList(); + if (candidates.Count != 1) return; target = new Symbol { File = candidates[0].File, Start = 0 }; + } + else { var targets = state.Definitions(offset); if (targets.Count != 1) return; target = targets[0]; } + VsShellUtilities.OpenDocument(ServiceProvider.GlobalProvider, target.File, VSConstants.LOGVIEWID_Code, out _, out _, out var frame); + var targetView = VsShellUtilities.GetTextView(frame); + if (targetView != null) + { + var source = state.Graph.FirstOrDefault(s => s.File == target.File); string preceding = source?.Text.Substring(0, Math.Min(target.Start, source.Text.Length)) ?? ""; + int line = preceding.Count(c => c == '\n'), last = preceding.LastIndexOf('\n'); targetView.SetCaretPos(line, preceding.Length - last - 1); targetView.CenterLines(line, 1); + } + }).FileAndForget("VAS/GoToDefinition"); + return VSConstants.S_OK; + } + if (group == VSConstants.VSStd2K) + { + if (new[] { (uint)VSConstants.VSStd2KCmdID.AUTOCOMPLETE, (uint)VSConstants.VSStd2KCmdID.COMPLETEWORD, (uint)VSConstants.VSStd2KCmdID.SHOWMEMBERLIST }.Contains(id)) { StartCompletion(); return VSConstants.S_OK; } + if (id == (uint)VSConstants.VSStd2KCmdID.PARAMINFO) { StartSignature(); return VSConstants.S_OK; } + if (session != null && !session.IsDismissed && (id == (uint)VSConstants.VSStd2KCmdID.TAB || id == (uint)VSConstants.VSStd2KCmdID.RETURN) && session.SelectedCompletionSet?.SelectionStatus.IsSelected == true) { + session.Commit(); + StartSignature(); + return VSConstants.S_OK; + } + } + int result = next.Exec(ref group, id, options, input, output); + if (group == VSConstants.VSStd2K && id == (uint)VSConstants.VSStd2KCmdID.TYPECHAR) + { + int caret = view.Caret.Position.BufferPosition.Position; string text = view.TextBuffer.CurrentSnapshot.GetText(); + if (caret > 0 && (text[caret - 1] == '(' || text[caret - 1] == ',')) StartSignature(); + else if (caret > 0 && (char.IsLetter(text[caret - 1]) || text[caret - 1] == '_' || text[caret - 1] == '.' || text[caret - 1] == ':')) StartCompletion(); + else if (session != null && !session.IsDismissed) session.Filter(); + } + return result; + } + private void StartCompletion() + { + if (!LanguageModel.IsCode(view.TextBuffer.CurrentSnapshot.GetText(), view.Caret.Position.BufferPosition.Position)) return; + if (state.AnalyzedSnapshot == state.Buffer.CurrentSnapshot) { Complete(); return; } + var snapshot = state.Buffer.CurrentSnapshot; int offset = view.Caret.Position.BufferPosition.Position; + ThreadHelper.JoinableTaskFactory.RunAsync(async () => + { + await state.WaitAsync(); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); + if (!view.IsClosed && state.Buffer.CurrentSnapshot == snapshot && view.Caret.Position.BufferPosition.Position == offset) Complete(); + }).FileAndForget("VAS/Completion"); + } + private void StartSignature() { + var snapshot = view.TextBuffer.CurrentSnapshot; int offset = view.Caret.Position.BufferPosition.Position; + ThreadHelper.JoinableTaskFactory.RunAsync(async () => { + await state.WaitAsync(); await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); + if (!view.IsClosed && state.Buffer.CurrentSnapshot == snapshot && view.Caret.Position.BufferPosition.Position == offset) signatures.TriggerSignatureHelp(view); + }).FileAndForget("VAS/Parameters"); + } + private void Complete() { if (session == null || session.IsDismissed) session = broker.TriggerCompletion(view); else session.Filter(); } + } +} diff --git a/tools/visualstudio-extension/Editor/LiveCompiler.cs b/tools/visualstudio-extension/Editor/LiveCompiler.cs new file mode 100644 index 000000000..e3ebb547f --- /dev/null +++ b/tools/visualstudio-extension/Editor/LiveCompiler.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.VisualStudio.Settings; +using Microsoft.VisualStudio.Shell; +using Microsoft.VisualStudio.Shell.Settings; +using VerseAngelScript.VisualStudio.Build; + +namespace VerseAngelScript.VisualStudio.Editor +{ + internal static class LiveCompiler + { + private static readonly SemaphoreSlim Gate = new SemaphoreSlim(1); + internal static string ConfiguredCompiler() { + ThreadHelper.ThrowIfNotOnUIThread(); + var store = new ShellSettingsManager(ServiceProvider.GlobalProvider).GetReadOnlySettingsStore(SettingsScope.UserSettings); + return store.CollectionExists(BuildOptions.Collection) && store.PropertyExists(BuildOptions.Collection, "LiveDiagnostics") && store.GetBoolean(BuildOptions.Collection, "LiveDiagnostics") + && store.PropertyExists(BuildOptions.Collection, "CompilerPath") ? store.GetString(BuildOptions.Collection, "CompilerPath") : ""; + } + internal static async Task> InspectAsync(string compiler, IReadOnlyList graph, CancellationToken cancellation) { + var issues = new List(); if (string.IsNullOrWhiteSpace(compiler) || graph.Count == 0) return issues; + await Gate.WaitAsync(cancellation); string temporary = null; + try { + compiler = NativeProcess.ValidateCompiler(compiler); var source = graph[0]; + string root = Path.GetDirectoryName(source.File), config = null; + for (int depth = 0; root != null && depth < 16; depth++, root = Path.GetDirectoryName(root)) { + config = Path.Combine(root, ".vas", "vasbuild.config.txt"); if (File.Exists(config)) break; + } + if (root == null || config == null || !File.Exists(config) || graph.Any(s => !s.File.StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))) return issues; + temporary = Path.Combine(Path.GetTempPath(), "vas-vs-diagnostics-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(temporary); + foreach (var model in graph) { + cancellation.ThrowIfCancellationRequested(); string target = Path.Combine(temporary, model.File.Substring(root.Length + 1)); + Directory.CreateDirectory(Path.GetDirectoryName(target)); File.WriteAllText(target, model.Text, new UTF8Encoding(false)); + } + string entry = Path.Combine(temporary, source.File.Substring(root.Length + 1)); var roots = new List(); + for (string parent = Path.GetDirectoryName(entry); parent != null && parent.StartsWith(temporary, StringComparison.OrdinalIgnoreCase); parent = Path.GetDirectoryName(parent)) roots.Add(parent); + var environment = new Dictionary { ["VAS_INCLUDE_PATH"] = string.Join(Path.PathSeparator.ToString(), roots) }; + var result = await NativeProcess.RunAsync(compiler, new[] { config, entry, Path.Combine(temporary, "diagnostics.vasbc") }, temporary, + TimeSpan.FromSeconds(10), 2 * 1024 * 1024, cancellation, environment: environment); + string output = Encoding.UTF8.GetString(result.Stdout) + result.Stderr; + foreach (string line in output.Split('\n')) { + var match = Regex.Match(line.TrimEnd('\r'), "^(.*) \\((\\d+),\\s*(\\d+)\\)\\s*:\\s*ERR\\s*:\\s*(.+)$"); + if (!match.Success || !string.Equals(Path.GetFullPath(match.Groups[1].Value), entry, StringComparison.OrdinalIgnoreCase) + || !int.TryParse(match.Groups[2].Value, out int row) || !int.TryParse(match.Groups[3].Value, out int column)) continue; + int start = Offset(source.Text, row, column); if (start < 0) continue; + int end = start; while (end < source.Text.Length && (char.IsLetterOrDigit(source.Text[end]) || source.Text[end] == '_')) end++; + if (end == start && end < source.Text.Length) end += char.IsHighSurrogate(source.Text[end]) && end + 1 < source.Text.Length ? 2 : 1; + issues.Add(new SyntaxIssue { Start = start, End = end, Message = match.Groups[4].Value }); + } + return issues; + } catch (Exception e) when (e is IOException || e is UnauthorizedAccessException || e is ArgumentException || e is InvalidOperationException || e is TimeoutException) { return issues; } + finally { + if (temporary != null && string.Equals(Path.GetDirectoryName(Path.GetFullPath(temporary)), Path.GetFullPath(Path.GetTempPath()).TrimEnd(Path.DirectorySeparatorChar), StringComparison.OrdinalIgnoreCase) + && Path.GetFileName(temporary).StartsWith("vas-vs-diagnostics-", StringComparison.Ordinal)) { + try { Directory.Delete(temporary, true); } catch (IOException) { } catch (UnauthorizedAccessException) { } + } + Gate.Release(); + } + } + private static int Offset(string text, int row, int column) { + if (row < 1 || column < 1) return -1; int start = 0; + for (int line = 1; line < row; line++) { int newline = text.IndexOf('\n', start); if (newline < 0) return -1; start = newline + 1; } + int offset = start, bytes = 0; + while (offset < text.Length && text[offset] != '\n' && bytes < column - 1) { + int width = char.IsHighSurrogate(text[offset]) && offset + 1 < text.Length && char.IsLowSurrogate(text[offset + 1]) ? 2 : 1; + int count = Encoding.UTF8.GetByteCount(text.Substring(offset, width)); if (bytes + count > column - 1) break; + bytes += count; offset += width; + } + return offset; + } + } +} diff --git a/tools/visualstudio-extension/Editor/SemanticColors.cs b/tools/visualstudio-extension/Editor/SemanticColors.cs new file mode 100644 index 000000000..c62412cd9 --- /dev/null +++ b/tools/visualstudio-extension/Editor/SemanticColors.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.Composition; +using System.Linq; +using System.Windows.Media; +using Microsoft.VisualStudio.Text; +using Microsoft.VisualStudio.Text.Classification; +using Microsoft.VisualStudio.Utilities; + +namespace VerseAngelScript.VisualStudio.Editor +{ + internal static class ColorNames + { + internal const string Type = "VAS type", Function = "VAS function", Macro = "VAS macro"; + [Export(typeof(ClassificationTypeDefinition)), Name(Type), BaseDefinition("identifier")] + internal static ClassificationTypeDefinition TypeDefinition = null; + [Export(typeof(ClassificationTypeDefinition)), Name(Function), BaseDefinition("identifier")] + internal static ClassificationTypeDefinition FunctionDefinition = null; + [Export(typeof(ClassificationTypeDefinition)), Name(Macro), BaseDefinition("preprocessor keyword")] + internal static ClassificationTypeDefinition MacroDefinition = null; + } + [Export(typeof(EditorFormatDefinition)), ClassificationType(ClassificationTypeNames = ColorNames.Type), Name(ColorNames.Type), UserVisible(true), Order(After = Priority.Default)] + internal sealed class TypeFormat : ClassificationFormatDefinition + { public TypeFormat() { DisplayName = ColorNames.Type; ForegroundColor = Color.FromRgb(78, 201, 176); } } + [Export(typeof(EditorFormatDefinition)), ClassificationType(ClassificationTypeNames = ColorNames.Function), Name(ColorNames.Function), UserVisible(true), Order(After = Priority.Default)] + internal sealed class FunctionFormat : ClassificationFormatDefinition + { public FunctionFormat() { DisplayName = ColorNames.Function; ForegroundColor = Color.FromRgb(176, 144, 40); } } + [Export(typeof(EditorFormatDefinition)), ClassificationType(ClassificationTypeNames = ColorNames.Macro), Name(ColorNames.Macro), UserVisible(true), Order(After = Priority.Default)] + internal sealed class MacroFormat : ClassificationFormatDefinition + { public MacroFormat() { DisplayName = ColorNames.Macro; ForegroundColor = Color.FromRgb(177, 112, 193); } } + + [Export(typeof(IClassifierProvider)), Name("VAS semantic colors"), ContentType("text")] + internal sealed class SemanticColorProvider : IClassifierProvider + { + [Import] internal EditorWorkspace Workspace = null; + [Import] internal IClassificationTypeRegistryService Registry = null; + public IClassifier GetClassifier(ITextBuffer buffer) + { var state = Workspace.Get(buffer); return state == null ? null : buffer.Properties.GetOrCreateSingletonProperty(() => new SemanticColors(state, Registry)); } + } + internal sealed class SemanticColors : IClassifier + { + private readonly DocumentState state; + private readonly IClassificationTypeRegistryService registry; + internal SemanticColors(DocumentState state, IClassificationTypeRegistryService registry) + { this.state = state; this.registry = registry; state.Updated += (sender, args) => ClassificationChanged?.Invoke(this, new ClassificationChangedEventArgs(new SnapshotSpan(state.Buffer.CurrentSnapshot, 0, state.Buffer.CurrentSnapshot.Length))); } + public event EventHandler ClassificationChanged; + public IList GetClassificationSpans(SnapshotSpan span) + { + var result = new List(); var source = state.Current; + if (source == null || state.AnalyzedSnapshot != span.Snapshot) return result; + var names = state.Graph.SelectMany(m => m.Symbols).Where(s => new[] { "class", "interface", "enum", "namespace", "function", "method", "macro" }.Contains(s.Kind)).GroupBy(s => s.Name).ToDictionary(g => g.Key, g => g.Select(s => s.Kind).Distinct().Count() == 1 ? g.First().Kind : ""); + foreach (var token in source.Tokens.Where(t => t.Kind == "id" && t.Start >= span.Start.Position && t.End <= span.End.Position)) + { + if (LanguageModel.Keywords.Contains(token.Text) || !names.TryGetValue(token.Text, out string kind)) continue; + if (kind == "function" || kind == "method") + { int next = token.End; while (next < source.Text.Length && char.IsWhiteSpace(source.Text[next])) next++; if (next == source.Text.Length || source.Text[next] != '(') continue; } + string color = kind == "macro" ? ColorNames.Macro : kind == "function" || kind == "method" ? ColorNames.Function : ColorNames.Type; + result.Add(new ClassificationSpan(new SnapshotSpan(span.Snapshot, token.Start, token.End - token.Start), registry.GetClassificationType(color))); + } + foreach (var word in source.DirectiveWords.Where(t => t.Start >= span.Start.Position && t.End <= span.End.Position)) + if (names.TryGetValue(word.Text, out string kind) && kind == "macro") result.Add(new ClassificationSpan(new SnapshotSpan(span.Snapshot, word.Start, word.End - word.Start), registry.GetClassificationType(ColorNames.Macro))); + return result; + } + } +} diff --git a/tools/visualstudio-extension/Editor/SyntaxErrors.cs b/tools/visualstudio-extension/Editor/SyntaxErrors.cs new file mode 100644 index 000000000..00f68edf2 --- /dev/null +++ b/tools/visualstudio-extension/Editor/SyntaxErrors.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.Composition; +using System.Linq; +using Microsoft.VisualStudio.Text; +using Microsoft.VisualStudio.Text.Adornments; +using Microsoft.VisualStudio.Text.Tagging; +using Microsoft.VisualStudio.Utilities; + +namespace VerseAngelScript.VisualStudio.Editor +{ + [Export(typeof(ITaggerProvider)), ContentType("text"), TagType(typeof(ErrorTag))] + internal sealed class SyntaxErrorProvider : ITaggerProvider + { + [Import] internal EditorWorkspace Workspace = null; + public ITagger CreateTagger(ITextBuffer buffer) where T : ITag + { + var state = Workspace.Get(buffer); + return state == null ? null : buffer.Properties.GetOrCreateSingletonProperty(() => new SyntaxErrors(state)) as ITagger; + } + } + internal sealed class SyntaxErrors : ITagger + { + private readonly DocumentState state; + internal SyntaxErrors(DocumentState state) { + this.state = state; + state.Updated += (sender, args) => TagsChanged?.Invoke(this, new SnapshotSpanEventArgs(new SnapshotSpan(state.Buffer.CurrentSnapshot, 0, state.Buffer.CurrentSnapshot.Length))); + } + public event EventHandler TagsChanged; + public IEnumerable> GetTags(NormalizedSnapshotSpanCollection spans) { + if (spans.Count == 0 || state.AnalyzedSnapshot != spans[0].Snapshot || state.Current == null) yield break; + foreach (var problem in state.Current.Problems.Concat(state.CompilerProblems)) { + var span = new SnapshotSpan(state.AnalyzedSnapshot, problem.Start, problem.End - problem.Start); + if (spans.Any(s => s.IntersectsWith(span))) yield return new TagSpan(span, new ErrorTag(PredefinedErrorTypeNames.SyntaxError, problem.Message)); + } + } + } +} diff --git a/tools/visualstudio-extension/README.md b/tools/visualstudio-extension/README.md index 62bce4e82..f9250ee76 100644 --- a/tools/visualstudio-extension/README.md +++ b/tools/visualstudio-extension/README.md @@ -2,7 +2,9 @@ A VSIX for `.vas` editing and explicit native project builds in Visual Studio 2026 (18.x, x64). Canonical TextMate assets provide syntax colors, comments, bracket -pairs, indentation and ordinary editor undo. The extension does not claim `.as`, +pairs, indentation and ordinary editor undo. Read-only MEF providers add +import/include F12, native declaration/member/macro completion, async hover and +type/function/macro semantic colors. Source graph scans run in the background. The extension does not claim `.as`, `.cpp`, or the C++ language/content type. 中文安装、源码打包、示例与三端能力矩阵见 [安装与使用指南](../../docs/ide-setup.md)。 @@ -26,8 +28,7 @@ pairs, indentation and ordinary editor undo. The extension does not claim `.as`, The compiler owns the shared [project](../../docs/vas-project.md) and [JSONL report](../../docs/vas-build-report.md) contracts. Enumeration and selection create no output directories. Only a successful native compilation may create -its configured output. Opening, indexing, editing and saving settings never -execute the compiler. A repeated Build command while an operation is active is +its configured output. Opening, indexing and editing do not start a project build. An independent current-file live checker runs only when explicitly enabled in user Toolchain settings. A repeated Build command while an operation is active is ignored; cancel it before starting another. Compiler errors, warnings and information appear in the native Error List and @@ -66,7 +67,8 @@ workspace trust state remains unverified. Opening a solution or folder is not proof of native trust. The extension uses no reconstructed private COM interface, registry trust heuristic or `Microsoft.Internal` API. -This module does not provide Run Project, semantic analysis, LSP, debugger/DAP, +Conditional macro activation and complete compiler type binding are not inferred. +This module does not provide Run Project, semantic diagnostics, LSP, debugger/DAP, SDK generation, Unreal integration, or C++ feature parity. ## Build and verify @@ -131,3 +133,7 @@ References: [language configuration](https://learn.microsoft.com/en-us/visualstu [native trust behavior](https://learn.microsoft.com/en-us/visualstudio/ide/trust-settings?view=visualstudio), [Microsoft test harness](https://github.com/microsoft/vs-extension-testing), [runner images](https://github.com/actions/runner-images). + +## Editing diagnostics (0.3.0) + +Native function completion inserts call parentheses and Signature Help displays source parameters. Structural syntax errors have red squiggles without a compiler. Set the user Compiler executable and enable **Live diagnostics** to check unsaved source/dependency snapshots after a debounce. The nearest project ancestor must contain `.vas/vasbuild.config.txt`; checks publish current-file errors and reject stale snapshots. See [language service details](../../docs/ide-language-support.md). diff --git a/tools/visualstudio-extension/VasPackage.cs b/tools/visualstudio-extension/VasPackage.cs index ec633eb8a..b7a1b8dd1 100644 --- a/tools/visualstudio-extension/VasPackage.cs +++ b/tools/visualstudio-extension/VasPackage.cs @@ -60,6 +60,10 @@ public sealed class BuildOptions : DialogPage [DisplayName("Compiler executable")] [Description("Absolute path to your native vasbuild.exe. Project manifests never select an executable.")] public string CompilerPath { get; set; } = string.Empty; + [Category("Editor")] + [DisplayName("Check unsaved code with the compiler")] + [Description("Enable background compilation with the explicitly configured compiler. Structural syntax errors are checked without this option.")] + public bool LiveDiagnostics { get; set; } public override void LoadSettingsFromStorage() { @@ -67,6 +71,7 @@ public override void LoadSettingsFromStorage() var store = new ShellSettingsManager(Site).GetReadOnlySettingsStore(SettingsScope.UserSettings); CompilerPath = store.CollectionExists(Collection) && store.PropertyExists(Collection, "CompilerPath") ? store.GetString(Collection, "CompilerPath") : string.Empty; + LiveDiagnostics = store.CollectionExists(Collection) && store.PropertyExists(Collection, "LiveDiagnostics") && store.GetBoolean(Collection, "LiveDiagnostics"); } public override void SaveSettingsToStorage() { @@ -74,6 +79,7 @@ public override void SaveSettingsToStorage() var store = new ShellSettingsManager(Site).GetWritableSettingsStore(SettingsScope.UserSettings); if (!store.CollectionExists(Collection)) store.CreateCollection(Collection); store.SetString(Collection, "CompilerPath", CompilerPath ?? string.Empty); + store.SetBoolean(Collection, "LiveDiagnostics", LiveDiagnostics); } } } diff --git a/tools/visualstudio-extension/scripts/test-vs2026.ps1 b/tools/visualstudio-extension/scripts/test-vs2026.ps1 index 6b4daf2b6..ed6435ee1 100644 --- a/tools/visualstudio-extension/scripts/test-vs2026.ps1 +++ b/tools/visualstudio-extension/scripts/test-vs2026.ps1 @@ -28,6 +28,7 @@ $env:VAS_TEST_WORKSPACE = Join-Path $ResultsDirectory 'fixtures' $env:VAS_TEST_RESULTS = $ResultsDirectory $env:XUNIT_LOGS = Join-Path $ResultsDirectory 'harness' $repositoryRoot = [IO.Path]::GetFullPath((Join-Path $extensionRoot '../..')) +$env:VAS_LANGUAGE_EXAMPLES = Join-Path $repositoryRoot 'examples/arena' $nativeBuild = Join-Path $ResultsDirectory 'native-build' $projectEvidence = Join-Path $ResultsDirectory 'project-build' # Remove stale evidence before any run; a previous native pass cannot satisfy this gate. diff --git a/tools/visualstudio-extension/source.extension.vsixmanifest b/tools/visualstudio-extension/source.extension.vsixmanifest index 50dfd91bd..1a4c24ace 100644 --- a/tools/visualstudio-extension/source.extension.vsixmanifest +++ b/tools/visualstudio-extension/source.extension.vsixmanifest @@ -1,9 +1,9 @@ - + VerseAngelScript editor - VAS editing and explicit native project builds with navigable compiler diagnostics for Visual Studio 2026. + VAS module navigation, completion, semantic colors and explicit native project builds with navigable compiler diagnostics for Visual Studio 2026. VAS,VerseAngelScript,AngelScript,TextMate @@ -16,6 +16,7 @@ + diff --git a/tools/visualstudio-extension/test/CoreTests/CoreTests.csproj b/tools/visualstudio-extension/test/CoreTests/CoreTests.csproj index 63a256d41..2e0134578 100644 --- a/tools/visualstudio-extension/test/CoreTests/CoreTests.csproj +++ b/tools/visualstudio-extension/test/CoreTests/CoreTests.csproj @@ -11,6 +11,8 @@ + + diff --git a/tools/visualstudio-extension/test/CoreTests/LanguageModelTests.cs b/tools/visualstudio-extension/test/CoreTests/LanguageModelTests.cs new file mode 100644 index 000000000..095dc67a4 --- /dev/null +++ b/tools/visualstudio-extension/test/CoreTests/LanguageModelTests.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Diagnostics; +using Newtonsoft.Json; +using VerseAngelScript.VisualStudio.Editor; + +internal static class LanguageModelTests +{ + internal static void Measure() + { + var directory = new DirectoryInfo(Environment.CurrentDirectory); + while (directory != null && !Directory.Exists(Path.Combine(directory.FullName, "examples", "arena"))) directory = directory.Parent; + if (directory == null) throw new Exception("Arena example not found."); + string entry = Path.Combine(directory.FullName, "examples", "arena", "main.vas"); + var durations = new List(); int symbols = 0; + for (int repeat = 0; repeat < 31; repeat++) + { + var timer = Stopwatch.StartNew(); var cache = new Dictionary(StringComparer.OrdinalIgnoreCase); + Func read = file => { if (cache.TryGetValue(file, out var prior)) return prior; var model = File.Exists(file) ? LanguageModel.Parse(File.ReadAllText(file), file) : null; cache[file] = model; return model; }; + var graph = LanguageModel.Graph(read(entry), read, CancellationToken.None); + if (graph.Count != 9) throw new Exception("Arena graph changed during measurement."); + symbols = graph.Sum(m => m.Symbols.Count); durations.Add(timer.Elapsed.TotalMilliseconds); + } + durations.Sort(); + string json = JsonConvert.SerializeObject(new { files = 9, symbols, samples = 31, uncachedMedianMs = durations[15], uncachedP95Ms = durations[29], scope = "source model/import graph only; excludes IDE startup/rendering; filesystem cache may be warm" }, Formatting.Indented); + string output = Path.Combine(directory.FullName, "out", "verification", "ide", "vs-model-performance.json"); + Directory.CreateDirectory(Path.GetDirectoryName(output)); File.WriteAllText(output, json); Console.WriteLine(json); + } + + internal static void Run(Action check) + { + var model = LanguageModel.Parse("/* import Wrong; */ string Text = \"import Fake; class Spoof {}\";\n#define CODE class Forged {}\nint Value = 0xAB'CD;\nimport Real.Library;\nimport int External(int Value) from \"Legacy\";", "main.vas"); + check(model.Includes.Select(i => i.Path).SequenceEqual(new[] { "Real/Library.vas" }), "Only genuine module imports are dependencies"); + check(model.Symbols.Any(s => s.Name == "External" && s.Kind == "function"), "Legacy function imports remain declarations"); + check(model.Symbols.Any(s => s.Name == "CODE" && s.Kind == "macro"), "Macro declaration remains indexed"); + check(LanguageModel.Parse("void Main() {", "main.vas").Problems.Any(p => p.Message == "Expected '}'"), "Missing closing brace is diagnosed"); + check(LanguageModel.Parse("void Main(] {}", "main.vas").Problems.Any(p => p.Message == "Unexpected ']'"), "Mismatched brackets are diagnosed"); + check(LanguageModel.Parse("string Text = \"unfinished", "main.vas").Problems.Any(p => p.Message.Contains("string")), "Unterminated string is diagnosed"); + check(LanguageModel.Parse("void Main() { string Text = \"} )\"; int Value = 0xAB'CD; /* ] */ }", "main.vas").Problems.Count == 0, "Protected tokens do not manufacture syntax errors"); + check(!model.Symbols.Any(s => new[] { "Spoof", "Forged", "AB", "CD" }.Contains(s.Name)), "Strings, macro bodies and numbers cannot forge symbols"); + var library = LanguageModel.Parse("namespace Arena { class FHero { int Health; void Heal(int Amount) {} } int Add(int A, int B) { return A+B; } }", "library.vas"); + var source = LanguageModel.Parse("import Arena.Library;\nvoid Main() { Arena::FHero Hero; int Value = 1; { int Value = 2; print(Value); } print(Value); Hero.Heal(3); Arena::Add(1,2); }", "main.vas"); + var graph = new List { source, library }; + check(LanguageModel.Resolve(graph, source, source.Text.IndexOf("Heal(3)", StringComparison.Ordinal)).Single().QualifiedName == "Arena::FHero::Heal", "Typed member navigation"); + check(LanguageModel.Resolve(graph, source, source.Text.IndexOf("Add(1,2)", StringComparison.Ordinal)).Single().QualifiedName == "Arena::Add", "Namespace navigation"); + check(LanguageModel.Resolve(graph, source, source.Text.IndexOf("print(Value)", StringComparison.Ordinal) + 6).Single().Start == source.Text.IndexOf("Value = 2", StringComparison.Ordinal), "Nested local shadows outer declaration"); + check(LanguageModel.Resolve(graph, source, source.Text.LastIndexOf("print(Value)", StringComparison.Ordinal) + 6).Single().Start == source.Text.IndexOf("Value = 1", StringComparison.Ordinal), "Outer local restores after nested scope"); + check(library.Symbols.Any(s => s.Name == "Amount" && s.Kind == "parameter"), "Parameters retain their own scope"); + var roles = LanguageModel.Parse("namespace Arena { enum ERole { Warrior, Medic } void Main() { print(Warrior); print(ERole::Warrior); } }", "roles.vas"); + check(LanguageModel.Resolve(new List { roles }, roles, roles.Text.IndexOf("Warrior);", StringComparison.Ordinal)).Single().Kind == "enumMember", "Enum values export to their namespace"); + check(LanguageModel.Resolve(new List { roles }, roles, roles.Text.LastIndexOf("Warrior);", StringComparison.Ordinal)).Single().Kind == "enumMember", "Explicit relative enum qualification"); + var directory = new DirectoryInfo(Environment.CurrentDirectory); + while (directory != null && !Directory.Exists(Path.Combine(directory.FullName, "examples", "arena"))) directory = directory.Parent; + if (directory == null) throw new Exception("Run core tests from the repository tree to verify the real arena example."); + string entry = Path.Combine(directory.FullName, "examples", "arena", "main.vas"); + var cache = new Dictionary(StringComparer.OrdinalIgnoreCase); + Func read = file => { if (cache.TryGetValue(file, out var prior)) return prior; var result = File.Exists(file) ? LanguageModel.Parse(File.ReadAllText(file), file) : null; cache[file] = result; return result; }; + var main = read(entry); var arena = LanguageModel.Graph(main, read, CancellationToken.None); + check(arena.Count == 9, "Real nine-file arena dependency closure"); + check(Path.GetFileName(LanguageModel.Resolve(arena, main, main.Text.IndexOf("RunDemo(", StringComparison.Ordinal)).Single().File) == "Demo.vas", "Cross-module RunDemo definition"); + check(arena.SelectMany(m => m.Symbols).Any(s => s.Name == "VAS_ARENA_MAX_ROUNDS" && s.Kind == "macro"), "Transitive exported macro visible"); + check(arena.Single(m => m.File.EndsWith("Report.vas", StringComparison.Ordinal)).Symbols.Any(s => s.Name == "PrintStandings"), "Generic/handle parameters preserve function indexing"); + } +} diff --git a/tools/visualstudio-extension/test/CoreTests/Program.cs b/tools/visualstudio-extension/test/CoreTests/Program.cs index 1849474e6..9ca9b995d 100644 --- a/tools/visualstudio-extension/test/CoreTests/Program.cs +++ b/tools/visualstudio-extension/test/CoreTests/Program.cs @@ -19,10 +19,16 @@ internal static class Program private static int Main(string[] args) { if (args.Length >= 2 && args[0] == "--fixture") return Fixture(args[1]); + if (args.Length == 1 && args[0] == "--language") + { + try { LanguageModelTests.Run(Check); LanguageModelTests.Measure(); Console.WriteLine("PASS " + checks + " language assertions"); return 0; } + catch (Exception error) { Console.Error.WriteLine(error); return 1; } + } try { DescriptorTests(); ReportTests(); PositionTests(); CompilerPathTests(); InputEventTests(); WorkspaceEventTests(); ProcessTests(); FixtureMutationTests.Run(Check); + LanguageModelTests.Run(Check); string native = Environment.GetEnvironmentVariable("VAS_NATIVE_ARGV_FIXTURE"); if (!string.IsNullOrEmpty(native)) NativeArguments(native); else if (Environment.OSVersion.Platform == PlatformID.Win32NT) throw new Exception("Windows core gate requires VAS_NATIVE_ARGV_FIXTURE (tests/vasbuild/rider_argv_fixture.cpp)."); diff --git a/tools/visualstudio-extension/test/HostTests/EditorTests.cs b/tools/visualstudio-extension/test/HostTests/EditorTests.cs index 375decfcb..262c25714 100644 --- a/tools/visualstudio-extension/test/HostTests/EditorTests.cs +++ b/tools/visualstudio-extension/test/HostTests/EditorTests.cs @@ -12,6 +12,7 @@ using Microsoft.VisualStudio; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; +using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; @@ -20,6 +21,9 @@ using Microsoft.VisualStudio.Text.BraceCompletion; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; +using Microsoft.VisualStudio.Text.Tagging; +using Microsoft.VisualStudio.Settings; +using Microsoft.VisualStudio.Shell.Settings; using Xunit; using Xunit.Harness; @@ -34,6 +38,135 @@ public sealed class EditorTests : IDisposable { private const string Source = "// Unicode 注释\r\nvoid Main() {\r\n int count = 42;\r\n string title = \"你好 VAS\";\r\n}\r\n"; + [IdeFact(MinVersion = VisualStudioVersion.VS18, MaxVersion = VisualStudioVersion.VS18, RootSuffix = "VASIntegration", MaxAttempts = 1)] + public async Task TypingCompletionParameterHelpAndLiveErrors() + { + await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); + const string collection = "VerseAngelScript/Toolchain"; + var settings = new ShellSettingsManager(ServiceProvider.GlobalProvider).GetWritableSettingsStore(SettingsScope.UserSettings); + bool hadCompiler = settings.CollectionExists(collection) && settings.PropertyExists(collection, "CompilerPath"); + bool hadLive = settings.CollectionExists(collection) && settings.PropertyExists(collection, "LiveDiagnostics"); + string previousCompiler = hadCompiler ? settings.GetString(collection, "CompilerPath") : ""; + bool previousLive = hadLive && settings.GetBoolean(collection, "LiveDiagnostics"); + if (!settings.CollectionExists(collection)) settings.CreateCollection(collection); + settings.SetString(collection, "CompilerPath", Environment.GetEnvironmentVariable("VAS_NATIVE_COMPILER")); settings.SetBoolean(collection, "LiveDiagnostics", true); + string entry = WriteFixture("editing/editor.vas", "void Main() {}"); + string examples = Environment.GetEnvironmentVariable("VAS_LANGUAGE_EXAMPLES"); + string hostConfig = Path.GetFullPath(Path.Combine(examples, "../../sdk/samples/asbuild/bin/config.txt")); + string config = Path.Combine(Path.GetDirectoryName(entry), ".vas", "vasbuild.config.txt"); Directory.CreateDirectory(Path.GetDirectoryName(config)); File.Copy(hostConfig, config, true); + try { + using (var editor = Open(entry)) { + var components = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel)); + var completions = components.GetService(); var signatures = components.GetService(); + using (var errors = components.GetService().CreateTagAggregator(editor.View)) { + Action replace = text => { + foreach (var completion in completions.GetSessions(editor.View)) completion.Dismiss(); + foreach (var signature in signatures.GetSessions(editor.View)) signature.Dismiss(); + using (var edit = editor.View.TextBuffer.CreateEdit()) { edit.Replace(0, editor.Text.Length, text); edit.Apply(); } editor.End(); + }; + Func waitError = async message => { + for (int attempt = 0; attempt < 100; attempt++) { + var span = new SnapshotSpan(editor.View.TextBuffer.CurrentSnapshot, 0, editor.Text.Length); + if (errors.GetTags(span).Any(t => (t.Tag.ToolTipContent?.ToString() ?? "").Contains(message))) return; + await Task.Delay(100); + } + Assert.Fail("Expected live squiggle: " + message); + }; + string prefix = "int CalculateScore(int Left, int Right) { return Left + Right; }\nvoid Main() { Calcu"; + replace(prefix); await Task.Delay(250); await editor.ExecuteCommandAsync("Edit.ListMembers"); + var session = completions.GetSessions(editor.View).Single(); var set = session.CompletionSets.Single(s => s.Moniker == "VAS"); + var item = set.Completions.Single(c => c.DisplayText == "CalculateScore"); + session.SelectedCompletionSet = set; set.SelectionStatus = new CompletionSelectionStatus(item, true, true); + editor.Command(VSConstants.VSStd2KCmdID.TAB); + Assert.EndsWith("CalculateScore()", editor.Text); Assert.Equal(')', editor.Text[editor.View.Caret.Position.BufferPosition.Position]); + await Task.Delay(250); await editor.ExecuteCommandAsync("Edit.ParameterInfo"); + var hint = signatures.GetSessions(editor.View).FirstOrDefault(s => s.Signatures.Any(signature => signature.Content.Contains("CalculateScore"))); + Assert.NotNull(hint); Assert.Equal(2, hint.Signatures.First(s => s.Content.Contains("CalculateScore")).Parameters.Count); + replace("void Main() {"); await waitError("Expected '}'"); + replace("void Main() { int Value = MissingEditorName; }"); await waitError("MissingEditorName"); + replace("void Main() { int Value = 1 return; }"); await waitError("Expected"); + replace("void Main() { int Value = 1; }"); await Task.Delay(800); + Assert.Empty(errors.GetTags(new SnapshotSpan(editor.View.TextBuffer.CurrentSnapshot, 0, editor.Text.Length))); + File.WriteAllText(Path.Combine(Environment.GetEnvironmentVariable("VAS_TEST_RESULTS"), "vs-editing.json"), + "{\"host\":\"VS18\",\"nativeFunctionCompletion\":true,\"parameterHelp\":true,\"structuralErrors\":true,\"nativeCompilerErrors\":true,\"missingSemicolon\":true,\"clearedErrorsAfterFix\":true}"); + } + } + } finally { + if (hadCompiler) settings.SetString(collection, "CompilerPath", previousCompiler); else settings.DeleteProperty(collection, "CompilerPath"); + if (hadLive) settings.SetBoolean(collection, "LiveDiagnostics", previousLive); else settings.DeleteProperty(collection, "LiveDiagnostics"); + } + } + + [IdeFact(MinVersion = VisualStudioVersion.VS18, MaxVersion = VisualStudioVersion.VS18, RootSuffix = "VASIntegration", MaxAttempts = 1)] + public async Task ArenaModulesCompleteNavigateAndHaveSemanticColors() + { + await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); + string examples = Environment.GetEnvironmentVariable("VAS_LANGUAGE_EXAMPLES"); + Assert.True(Directory.Exists(examples), "Use the actual arena example as the editor fixture."); + string entry = null; + foreach (string file in Directory.GetFiles(examples, "*.vas", SearchOption.AllDirectories)) + { + string relative = file.Substring(examples.TrimEnd('\\', '/').Length + 1); + string copied = WriteFixture("arena/" + relative, File.ReadAllText(file)); + if (relative == "main.vas") entry = copied; + } + Assert.NotNull(entry); + using (var editor = Open(entry)) + { + await AssertClassificationAsync(editor, "RunDemo", "VAS function"); + var components = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel)); + var broker = components.GetService(); + int call = editor.Text.IndexOf("RunDemo(", StringComparison.Ordinal); + editor.View.Caret.MoveTo(new SnapshotPoint(editor.View.TextBuffer.CurrentSnapshot, call)); + await editor.ExecuteCommandAsync("Edit.ListMembers"); + var session = broker.GetSessions(editor.View).Single(); + // TextMate can contribute separate lexical word guesses. Verify the native VAS declaration set. + var names = session.CompletionSets.Single(set => set.Moniker == "VAS").Completions.Select(c => c.DisplayText).ToList(); + Assert.Contains("RunDemo", names); + Assert.Contains("RunBatch", names); + Assert.DoesNotContain("VAS_ARENA_MAX_ROUNDS", names); + session.Dismiss(); + editor.View.Caret.MoveTo(new SnapshotPoint(editor.View.TextBuffer.CurrentSnapshot, editor.Text.IndexOf("return 0;", StringComparison.Ordinal))); + await editor.ExecuteCommandAsync("Edit.ListMembers"); + session = broker.GetSessions(editor.View).Single(); + names = session.CompletionSets.Single(set => set.Moniker == "VAS").Completions.Select(c => c.DisplayText).ToList(); + Assert.Contains("VAS_ARENA_MAX_ROUNDS", names); + Assert.Contains("println", names); + session.Dismiss(); + editor.View.Caret.MoveTo(new SnapshotPoint(editor.View.TextBuffer.CurrentSnapshot, call)); + await editor.ExecuteCommandAsync("Edit.GoToDefinition"); + for (int attempt = 0; attempt < 100 && !editor.Dte.ActiveDocument.FullName.EndsWith("Demo.vas", StringComparison.OrdinalIgnoreCase); attempt++) await Task.Delay(100); + Assert.EndsWith("Demo.vas", editor.Dte.ActiveDocument.FullName); + string demoPath = editor.Dte.ActiveDocument.FullName; + using (var demo = Open(demoPath)) + { + int declaration = demo.Text.IndexOf("RunDemo(", StringComparison.Ordinal); + using (var change = demo.View.TextBuffer.CreateEdit()) { change.Replace(declaration, 7, "RunChangedDemo"); change.Apply(); } + editor.View.Caret.MoveTo(new SnapshotPoint(editor.View.TextBuffer.CurrentSnapshot, call)); + for (int attempt = 0; attempt < 100 && editor.HasClassification("RunDemo", "VAS function"); attempt++) await Task.Delay(100); + AssertNoClassification(editor, "RunDemo", "VAS function"); + await editor.ExecuteCommandAsync("Edit.ListMembers"); + session = broker.GetSessions(editor.View).Single(); + names = session.CompletionSets.Single(set => set.Moniker == "VAS").Completions.Select(c => c.DisplayText).ToList(); + Assert.Contains("RunChangedDemo", names); + Assert.DoesNotContain("RunDemo", names); + session.Dismiss(); + } + await AssertClassificationAsync(editor, "RunDemo", "VAS function"); + using (var config = Open(Path.Combine(Path.GetDirectoryName(entry), "Arena", "Config.vas"))) + await AssertClassificationAsync(config, "VAS_ARENA_MAX_ROUNDS", "VAS macro"); + using (var combatant = Open(Path.Combine(Path.GetDirectoryName(entry), "Arena", "Combatant.vas"))) { + int valueUse = combatant.Text.IndexOf("Warrior, 90", StringComparison.Ordinal); + combatant.View.Caret.MoveTo(new SnapshotPoint(combatant.View.TextBuffer.CurrentSnapshot, valueUse)); + await combatant.ExecuteCommandAsync("Edit.GoToDefinition"); + for (int attempt = 0; attempt < 100 && combatant.View.Caret.Position.BufferPosition.Position >= valueUse; attempt++) await Task.Delay(100); + Assert.True(combatant.View.Caret.Position.BufferPosition.Position < valueUse, "Enum value F12 must navigate to its declaration."); + } + string results = Environment.GetEnvironmentVariable("VAS_TEST_RESULTS"); + File.WriteAllText(Path.Combine(results, "vs-language.json"), "{\"host\":\"VS18\",\"fixtureFiles\":9,\"semanticColors\":true,\"completion\":true,\"macroCompletion\":true,\"f12\":true,\"unsavedInvalidation\":true,\"enumNavigation\":true}"); + } + } + [IdeFact(MinVersion = VisualStudioVersion.VS18, MaxVersion = VisualStudioVersion.VS18, RootSuffix = "VASIntegration", MaxAttempts = 1)] public async Task RunsInsideVisualStudio2026ExperimentalHost() { @@ -346,6 +479,7 @@ public async Task ExecuteCommandAsync(string name) do { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); + if (!View.HasAggregateFocus) { Dte.MainWindow.Activate(); window.Activate(); View.VisualElement.Focus(); } var activeResult = textManager.GetActiveView(1, null, out var activeNativeView); var active = ErrorHandler.Succeeded(activeResult) && activeNativeView != null && ReferenceEquals(View, adapters.GetWpfTextView(activeNativeView)); diff --git a/tools/visualstudio-extension/test/HostTests/ProjectBuildTests.cs b/tools/visualstudio-extension/test/HostTests/ProjectBuildTests.cs index 9fcd1a617..17855cbc8 100644 --- a/tools/visualstudio-extension/test/HostTests/ProjectBuildTests.cs +++ b/tools/visualstudio-extension/test/HostTests/ProjectBuildTests.cs @@ -1109,7 +1109,7 @@ private async Task InvokeNativeProcessAsync(string executable, string[] { var type = package.GetType().Assembly.GetType("VerseAngelScript.VisualStudio.Build.NativeProcess", true); var method = type.GetMethod("RunAsync", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); - var task = (Task)method.Invoke(null, new object[] { executable, arguments, root, TimeSpan.FromSeconds(15), (long)(1024 * 1024), CancellationToken.None, null, null }); + var task = (Task)method.Invoke(null, new object[] { executable, arguments, root, TimeSpan.FromSeconds(15), (long)(1024 * 1024), CancellationToken.None, null, null, null }); await task; return Member(task, "Result"); } diff --git a/tools/visualstudio-extension/test/check_package.py b/tools/visualstudio-extension/test/check_package.py index d546f5266..04c1286fb 100644 --- a/tools/visualstudio-extension/test/check_package.py +++ b/tools/visualstudio-extension/test/check_package.py @@ -29,10 +29,12 @@ def test_scoped_registration(self): def test_production_package_manifest(self): manifest = ET.parse(ROOT / "source.extension.vsixmanifest").getroot() assets = manifest.findall("v:Assets/v:Asset", NS) - self.assertEqual(len(assets), 2) - self.assertTrue(all(a.attrib["Type"] == "Microsoft.VisualStudio.VsPackage" for a in assets)) - self.assertEqual(assets[0].attrib["Path"], "VAS.pkgdef") - self.assertEqual(assets[1].attrib["Path"], "|%CurrentProject%;PkgdefProjectOutputGroup|") + self.assertEqual(len(assets), 3) + mef = [a for a in assets if a.attrib["Type"] == "Microsoft.VisualStudio.MefComponent"] + packages = [a for a in assets if a.attrib["Type"] == "Microsoft.VisualStudio.VsPackage"] + self.assertEqual(len(mef), 1) + self.assertEqual(mef[0].attrib["Path"], "|%CurrentProject%|") + self.assertEqual([a.attrib["Path"] for a in packages], ["VAS.pkgdef", "|%CurrentProject%;PkgdefProjectOutputGroup|"]) target = manifest.find("v:Installation/v:InstallationTarget", NS) self.assertEqual(target.attrib["Version"], "[18.0,19.0)") self.assertEqual(target.find("v:ProductArchitecture", NS).text, "amd64") @@ -90,6 +92,7 @@ def verify_vsix(path, evidence_path=None, pkgdef_evidence_path=None): manifest = ET.fromstring(archive.read("extension.vsixmanifest")) assets = manifest.findall("v:Assets/v:Asset", NS) assert [(a.attrib["Type"], a.attrib["Path"]) for a in assets] == [ + ("Microsoft.VisualStudio.MefComponent", "VerseAngelScript.dll"), ("Microsoft.VisualStudio.VsPackage", "VAS.pkgdef"), ("Microsoft.VisualStudio.VsPackage", "VerseAngelScript.pkgdef")] # Only container bookkeeping may accompany the intentional payload. diff --git a/tools/visualstudio-extension/test/check_results.py b/tools/visualstudio-extension/test/check_results.py index 0874ff5a9..e445ca004 100644 --- a/tools/visualstudio-extension/test/check_results.py +++ b/tools/visualstudio-extension/test/check_results.py @@ -7,6 +7,8 @@ import xml.etree.ElementTree as ET EDITOR_EXPECTED = { + "TypingCompletionParameterHelpAndLiveErrors", + "ArenaModulesCompleteNavigateAndHaveSemanticColors", "RunsInsideVisualStudio2026ExperimentalHost", "ClassifiesUnicodeSpacePathAndReopens", "TripleStringsAndNonNestingCommentsUseCanonicalGrammar", diff --git a/tools/visualstudio-extension/test/test_validation.py b/tools/visualstudio-extension/test/test_validation.py index 0813ef116..0f8d70033 100644 --- a/tools/visualstudio-extension/test/test_validation.py +++ b/tools/visualstudio-extension/test/test_validation.py @@ -195,11 +195,14 @@ def registration(): "{d3a6e112-5f40-4df1-8bb7-0b79f0e74226}"=", 1, 1" """ - def write_package(self, altered=False, assembly=False, missing=False, registration_bytes=None): + def write_package(self, altered=False, assembly=False, missing=False, registration_bytes=None, missing_mef=False): if registration_bytes is None: registration_bytes = codecs.BOM_UTF16_LE + self.registration().encode("utf-16-le") with zipfile.ZipFile(self.path, "w") as archive: manifest = (ROOT / "source.extension.vsixmanifest").read_text().replace("|%CurrentProject%;PkgdefProjectOutputGroup|", "VerseAngelScript.pkgdef") + manifest = manifest.replace("|%CurrentProject%|", "VerseAngelScript.dll") + if missing_mef: + manifest = "\n".join(line for line in manifest.splitlines() if 'Type="Microsoft.VisualStudio.MefComponent"' not in line) archive.writestr("extension.vsixmanifest", manifest) archive.writestr("VerseAngelScript.dll", b"MZsynthetic managed payload") archive.writestr("Newtonsoft.Json.dll", b"MZsynthetic JSON dependency") @@ -217,6 +220,11 @@ def test_byte_identical_package_with_exact_runtime_allowlist_passes(self): with contextlib.redirect_stdout(io.StringIO()): verify_vsix(self.path) + def test_missing_editor_mef_registration_fails(self): + self.write_package(missing_mef=True) + with self.assertRaises(AssertionError): + verify_vsix(self.path) + def test_generated_registration_uses_strict_utf16le_bom(self): registration = self.registration() + '; Unicode fixture 漢字 😀\r\n' self.write_package(registration_bytes=codecs.BOM_UTF16_LE + registration.encode("utf-16-le")) diff --git a/tools/vscode-extension/README.md b/tools/vscode-extension/README.md index 286681267..a4b156477 100644 --- a/tools/vscode-extension/README.md +++ b/tools/vscode-extension/README.md @@ -1,8 +1,8 @@ # Verse AngelScript for VS Code -VAS 的 VS Code 基础扩展:`.vas` 语法高亮、注释/括号/缩进、代码片段,以及由真实 `vasbuild` / `vasrun` 驱动的构建、运行和 Problems 错误列表。 +VAS 的 VS Code 扩展:`.vas` 词法/语义高亮、import/include F12、声明/成员/宏补全、文档符号与悬浮、注释/括号/缩进、代码片段,以及由真实 `vasbuild` / `vasrun` 驱动的构建、运行和 Problems 错误列表。 -当前已交付编辑/当前文件任务基础,并增加独立的编译器工程构建客户端。当前没有语义补全、跨文件重命名、格式化器、后台诊断或 IDE 断点调试;完整验收范围见 [IDE 路线图](https://github.com/Aceared0829/VerseAngelScript/blob/master/docs/ide-roadmap.md)。 +当前已交付编辑/当前文件任务基础,并增加独立的编译器工程构建客户端。编辑服务使用源码声明与依赖闭包,支持未保存模块修改失效;宏条件、复杂表达式和继承推导仍需编译器确定。当前没有跨文件重命名、格式化器或 IDE 断点调试;完整验收范围见 [IDE 路线图](https://github.com/Aceared0829/VerseAngelScript/blob/master/docs/ide-roadmap.md)。 三端能力矩阵、可直接使用的工程与统一入门步骤见 [安装与使用指南](https://github.com/Aceared0829/VerseAngelScript/blob/master/docs/ide-setup.md)。 @@ -17,7 +17,7 @@ npm test npm run package ``` -在 VS Code 执行 **Extensions: Install from VSIX...**,选择生成的 `verseangelscript-vscode-0.1.0.vsix`。这里仅生成本地安装包,不发布到 Marketplace。 +在 VS Code 执行 **Extensions: Install from VSIX...**,选择生成的 `verseangelscript-vscode-0.3.0.vsix`。这里仅生成本地安装包,不发布到 Marketplace。 从仓库根目录构建本机工具: @@ -62,10 +62,10 @@ Windows 使用本机 `.exe`,如 `C:\\VAS\\vasbuild.exe`。不接受 PATH 查 - Build 使用原生 VS Code Task 和 CustomExecution/Pseudoterminal;扩展通过独立 stdout/stderr 管道启动 `vasbuild`,不经过 shell 或 Windows ConPTY。真实错误与警告直接进入原生 Problems,Unicode 路径不会经过终端屏幕文本重建;完整输出仍流式显示在任务终端 - Build 将编译器的 UTF-8 字节列映射为 VS Code UTF-16 列,支持中文、emoji、制表符和 include 文件。不能读取源文件时退回到行定位 - Build 按入口保存独立诊断集合;其他入口、工作区的构建或 Run 不会清除它。相同入口重建会替换旧诊断,较旧的并发构建不能覆盖新结果 -- 在 VS Code 编辑任何磁盘文件时,会保守地清除所有 Build 诊断并放弃旧位置结果;项目构建还监视工作区 VAS/manifest 与已观察到的配置/include 文件变更并失效项目结果。保存后需再次显式 Build;不会因打开、编辑或任务枚举启动编译器 +- 在 VS Code 编辑任何磁盘文件时,会保守地清除所有 Build 诊断并放弃旧位置结果;项目构建还监视工作区 VAS/manifest 与已观察到的配置/include 文件变更并失效项目结果。保存后需再次显式 Build;项目任务不会因打开、编辑或任务枚举自动启动;可配置的当前文件后台检查使用独立诊断集合 - Run 保留 ProcessExecution,支持交互式程序和终端输入。其终端问题匹配器只定位到行、共用 Run 诊断集合;Windows ConPTY(尤其 VS Code 1.96)可能损坏终端重建的长 Unicode 路径。需要精确 Problems 时请执行 Build - 使用 VS Code 的 **Tasks: Terminate Task** 停止运行;程序可通过终端读取输入 -- Restricted Mode 保留静态编辑功能,但禁用构建和运行;仅打开/编辑文件不会启动工具 +- Restricted Mode 保留静态编辑与结构诊断,但禁用构建、运行及后台编译。已信任工作区配置 User/Remote 编译器后,可由打开/编辑文件触发后台检查 仍可用原生当前文件任务固定入口(不读取工程 manifest),即使正在编辑辅助文件也能构建整个模块: @@ -146,3 +146,7 @@ npm run test:integration ``` Linux 无桌面环境时使用 `xvfb-run -a npm run test:integration`。默认验证最低支持版本 1.96.4;设置 `VSCODE_TEST_VERSION=stable` 验证当前稳定版。Windows、macOS 和 Linux 的真实客户端行为由 CI 分别测试,不用路径单元测试代替宿主验证。 + +## 输入与后台检查(0.3.0) + +函数补全插入调用括号,原生 Signature Help 支持 `(` / `,` 触发;即时结构诊断检查未闭合符号。已信任工作区配置 `vas.compilerPath` 与 `vas.configFile` 后,`vas.liveDiagnostics`(默认 true)以 450 ms 防抖检查未保存模块快照;编辑后取消旧检查。入口上下文及范围见 [语言服务说明](https://github.com/Aceared0829/VerseAngelScript/blob/master/docs/ide-language-support.md)。 diff --git a/tools/vscode-extension/language-configuration.json b/tools/vscode-extension/language-configuration.json index 812920def..67357a305 100644 --- a/tools/vscode-extension/language-configuration.json +++ b/tools/vscode-extension/language-configuration.json @@ -5,9 +5,9 @@ }, "brackets": [["{", "}"], ["[", "]"], ["(", ")"]], "autoClosingPairs": [ - { "open": "{", "close": "}" }, - { "open": "[", "close": "]" }, - { "open": "(", "close": ")" }, + { "open": "{", "close": "}", "notIn": ["string", "comment"] }, + { "open": "[", "close": "]", "notIn": ["string", "comment"] }, + { "open": "(", "close": ")", "notIn": ["string", "comment"] }, { "open": "\"", "close": "\"", "notIn": ["string", "comment"] }, { "open": "'", "close": "'", "notIn": ["string", "comment"] }, { "open": "/*", "close": " */", "notIn": ["string", "comment"] } diff --git a/tools/vscode-extension/package-lock.json b/tools/vscode-extension/package-lock.json index d19895574..ddce4a5a7 100644 --- a/tools/vscode-extension/package-lock.json +++ b/tools/vscode-extension/package-lock.json @@ -1,12 +1,12 @@ { "name": "verseangelscript-vscode", - "version": "0.1.0", + "version": "0.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "verseangelscript-vscode", - "version": "0.1.0", + "version": "0.3.0", "license": "SEE LICENSE IN LICENSE.md", "devDependencies": { "@vscode/test-electron": "3.1.0", diff --git a/tools/vscode-extension/package.json b/tools/vscode-extension/package.json index 0ac1fcc44..89f2d0ac3 100644 --- a/tools/vscode-extension/package.json +++ b/tools/vscode-extension/package.json @@ -2,7 +2,7 @@ "name": "verseangelscript-vscode", "displayName": "Verse AngelScript", "description": "VAS language editing and explicit compiler/runner tasks for VS Code", - "version": "0.1.0", + "version": "0.3.0", "publisher": "VerseAngelScript", "license": "SEE LICENSE IN LICENSE.md", "repository": { @@ -20,6 +20,7 @@ "workspace" ], "activationEvents": [ + "onLanguage:vas", "onTaskType:vas" ], "capabilities": { @@ -105,6 +106,11 @@ "scope": "machine", "description": "Absolute path to a trusted vasbuild executable. Configure in User or Remote settings; workspace executables are never auto-discovered." }, + "vas.liveDiagnostics": { + "type": "boolean", + "default": true, + "description": "Check unsaved VAS snapshots after typing pauses. Compiler checks require a trusted workspace and an explicitly configured compiler; structural checks always work." + }, "vas.runnerPath": { "type": "string", "default": "", diff --git a/tools/vscode-extension/src/editingSupport.js b/tools/vscode-extension/src/editingSupport.js new file mode 100644 index 000000000..5d2b96b85 --- /dev/null +++ b/tools/vscode-extension/src/editingSupport.js @@ -0,0 +1,53 @@ +'use strict'; +const { tokenize } = require('./languageModel'); + +function inspectSyntax(text) { + const { tokens, lexicalProblems, directives } = tokenize(text), problems = [...lexicalProblems], stack = []; + const conditional = directives.some(d => /^#(?:if|ifdef|ifndef)\b/.test(d.text)); + if (conditional) return problems; + for (const token of tokens) { + if (['(', '[', '{'].includes(token.text)) stack.push(token); + else if ([')', ']', '}'].includes(token.text)) { + if (!stack.length || '([{'.indexOf(stack.at(-1).text) !== ')]}'.indexOf(token.text)) + problems.push({ start: token.start, end: token.end, message: `Unexpected '${token.text}'` }); + else stack.pop(); + } + } + const closes = { '(': ')', '[': ']', '{': '}' }; + for (const token of stack) problems.push({ start: token.start, end: token.end, message: `Expected '${closes[token.text]}'` }); + return problems; +} +function inCode(text, offset) { + return !tokenize(text).protectedSpans.some(span => span.start < offset && (offset < span.end || offset === span.end && !span.closed)); +} + +function callAt(text, offset) { + const { tokens } = tokenize(text), stack = []; let previous; + for (const token of tokens) { + if (token.start >= offset) break; + if (['(', '[', '{'].includes(token.text)) stack.push({ name: token.text === '(' && previous?.kind === 'id' ? previous.text : '', nameOffset: previous?.start, open: token.start, parameter: 0 }); + else if ([')', ']', '}'].includes(token.text)) stack.pop(); + else if (token.text === ',' && stack.length) stack.at(-1).parameter++; + previous = token; + } + return stack.reverse().find(call => call.name && !['if', 'for', 'while', 'switch', 'catch'].includes(call.name)); +} + +function signature(label) { + const { tokens } = tokenize(label), open = tokens.findIndex(t => t.text === '('), parameters = []; + if (open < 0) return { label, parameters }; + let nesting = 0, begin = tokens[open].end; + for (const token of tokens.slice(open + 1)) { + if (['(', '[', '{', '<'].includes(token.text)) nesting++; + else if (token.text === ')' && nesting === 0 || token.text === ',' && nesting === 0) { + let start = begin, end = token.start; + while (start < end && /\s/.test(label[start])) start++; + while (end > start && /\s/.test(label[end - 1])) end--; + if (end > start) parameters.push([start, end]); + begin = token.end; if (token.text === ')') break; + } else if ([')', ']', '}', '>'].includes(token.text)) nesting--; + } + return { label, parameters }; +} + +module.exports = { inspectSyntax, callAt, signature, inCode }; diff --git a/tools/vscode-extension/src/extension.js b/tools/vscode-extension/src/extension.js index 83be683b9..7b076f684 100644 --- a/tools/vscode-extension/src/extension.js +++ b/tools/vscode-extension/src/extension.js @@ -156,6 +156,7 @@ async function buildProject(builds) { } function activate(context) { + if (vscode.languages.registerDefinitionProvider) require('./languageFeatures').registerLanguageFeatures(vscode, context); let collectionId = 0; const builds = { diagnostics: new BuildDiagnostics(() => vscode.languages.createDiagnosticCollection(`vas-build-${++collectionId}`)), diff --git a/tools/vscode-extension/src/languageFeatures.js b/tools/vscode-extension/src/languageFeatures.js new file mode 100644 index 000000000..749dfeb3d --- /dev/null +++ b/tools/vscode-extension/src/languageFeatures.js @@ -0,0 +1,147 @@ +'use strict'; + +const path = require('node:path'); +const { LanguageWorkspace, resolve, wordAt, keywords, runtime } = require('./languageModel'); +const { callAt, signature, inCode } = require('./editingSupport'); + +function registerLanguageFeatures(vscode, context) { + const selector = { language: 'vas', scheme: 'file' }, workspace = new LanguageWorkspace(() => vscode.workspace.textDocuments); + const kinds = { class: 'Class', interface: 'Interface', enum: 'Enum', enumMember: 'EnumMember', namespace: 'Module', function: 'Function', method: 'Method', property: 'Field', parameter: 'Variable', variable: 'Variable', macro: 'Constant' }; + const legendTypes = ['class', 'interface', 'enum', 'enumMember', 'namespace', 'function', 'method', 'property', 'parameter', 'variable', 'macro']; + const legend = new vscode.SemanticTokensLegend(legendTypes, ['declaration']); + const range = (document, start, end) => new vscode.Range(document.positionAt(start), document.positionAt(end)); + const location = async symbol => { + const document = await vscode.workspace.openTextDocument(vscode.Uri.file(symbol.file)); + return new vscode.Location(document.uri, range(document, symbol.start, symbol.end)); + }; + const graphAt = async (document, token) => { const graph = await workspace.graph(document, token); return { graph, model: graph[0] }; }; + require('./liveDiagnostics').registerLiveDiagnostics(vscode, context, workspace); + context.subscriptions.push( + vscode.languages.registerDefinitionProvider(selector, { + async provideDefinition(document, position, token) { + const { graph, model } = await graphAt(document, token); + if (!model || token.isCancellationRequested) return []; + const offset = document.offsetAt(position), include = model.includes.find(i => i.start <= offset && offset < i.end); + if (include) { + const dependency = await workspace.dependency(model.file, include, await workspace.roots(model.file)); + return dependency ? new vscode.Location(vscode.Uri.file(dependency.file), new vscode.Position(0, 0)) : []; + } + // A macro in a directive has no ordinary lexer token. Keep it read-only. + const word = document.getWordRangeAtPosition(position), name = word && document.getText(word); + const declarations = wordAt(model, offset) ? resolve(graph, model, offset) : graph.flatMap(m => m.symbols.filter(s => s.kind === 'macro' && s.name === name)); + return Promise.all(declarations.map(location)); + } + }), + vscode.languages.registerCompletionItemProvider(selector, { + async provideCompletionItems(document, position, token) { + if (!inCode(document.getText(), document.offsetAt(position))) return []; + const { graph, model } = await graphAt(document, token); + if (!model || token.isCancellationRequested) return []; + const offset = document.offsetAt(position), prefix = document.getText().slice(0, offset), member = /([\p{L}_][\p{L}\p{N}_]*(?:::[\p{L}_][\p{L}\p{N}_]*)*)(::|\.)[\p{L}\p{N}_]*$/u.exec(prefix); + let symbols = graph.flatMap(m => m.symbols.filter(s => m !== model ? s.exported : s.exported || s.start <= offset && s.scopeStart <= offset && offset <= s.scopeEnd)); + if (member) { + let owner = member[1]; + if (member[2] === '.') { + const receiver = model.tokens.find(t => t.start === member.index), variable = receiver && resolve(graph, model, receiver.start); + if (!variable || variable.length !== 1 || !variable[0].type) return []; + const type = variable[0].type, qualified = `${variable[0].container}::${type}`; + const resolvedType = symbols.find(s => ['class', 'interface'].includes(s.kind) && (s.qualifiedName === type || s.qualifiedName === qualified)); + owner = resolvedType?.qualifiedName || type; + } + if (member[2] === '::' && !owner.includes('::')) { + const head = model.tokens.find(t => t.start === member.index); + const containers = head ? resolve(graph, model, head.start).filter(s => ['class', 'interface', 'enum', 'namespace'].includes(s.kind)) : []; + const identities = [...new Set(containers.map(s => s.qualifiedName))]; + if (identities.length === 1) owner = identities[0]; + } + symbols = symbols.filter(s => (s.container === owner || s.kind === 'enumMember' && s.type === owner) && s.exported); + } + const items = [], seen = new Set(); + for (const symbol of symbols) { + const identity = `${symbol.qualifiedName || symbol.name}/${symbol.detail}/${symbol.file}`; + if (seen.has(identity)) continue; + seen.add(identity); + const item = new vscode.CompletionItem(symbol.name, vscode.CompletionItemKind[kinds[symbol.kind]]); + item.range = document.getWordRangeAtPosition(position) || new vscode.Range(position, position); + item.detail = symbol.detail || `${symbol.kind} ${symbol.qualifiedName || symbol.name}`; + item.documentation = `${path.basename(symbol.file)}${symbol.kind === 'macro' ? '\nMacro activation depends on the compilation unit.' : ''}`; + item.sortText = `${symbol.file === model.file ? '0' : '1'}${symbol.name}`; + if (['function', 'method'].includes(symbol.kind) && !/^\s*\(/.test(document.getText().slice(offset))) { + const parameters = signature(symbol.detail || `${symbol.name}()`).parameters; + item.insertText = new vscode.SnippetString(`${symbol.name}(${parameters.length ? '$0' : ''})`); + item.command = { command: 'editor.action.triggerParameterHints', title: 'Show VAS parameters' }; + } + items.push(item); + } + if (!member) for (const name of [...keywords, ...runtime]) if (!symbols.some(s => s.name === name)) { + const item = new vscode.CompletionItem(name, keywords.has(name) ? vscode.CompletionItemKind.Keyword : vscode.CompletionItemKind.Function); + item.sortText = '2' + name; + if (!keywords.has(name) && !/^\s*\(/.test(document.getText().slice(offset))) item.insertText = new vscode.SnippetString(`${name}($0)`); + items.push(item); + } + return items; + } + }, '.', ':'), + vscode.languages.registerSignatureHelpProvider(selector, { + async provideSignatureHelp(document, position, token) { + const call = callAt(document.getText(), document.offsetAt(position)); if (!call) return undefined; + const { graph, model } = await graphAt(document, token); if (!model || token.isCancellationRequested) return undefined; + const declarations = resolve(graph, model, call.nameOffset).filter(s => ['function', 'method'].includes(s.kind)); + const labels = declarations.map(s => s.detail); + if (!labels.length && ['print', 'println'].includes(call.name)) labels.push(`${call.name}(const string &in Format, const ?&in Arguments...)`, `${call.name}(Value)`); + if (!labels.length) return undefined; + const help = new vscode.SignatureHelp(); + help.signatures = [...new Set(labels)].map(label => { + const parsed = signature(label), info = new vscode.SignatureInformation(label); + info.parameters = parsed.parameters.map(range => new vscode.ParameterInformation(range)); return info; + }); + help.activeParameter = call.parameter; + help.activeSignature = Math.max(0, help.signatures.findIndex(s => s.parameters.length > call.parameter)); + return help; + } + }, '(', ','), + vscode.languages.registerDocumentSymbolProvider(selector, { + provideDocumentSymbols(document) { + const { parse } = require('./languageModel'); + return parse(document.getText(), document.uri.fsPath).symbols.filter(s => s.exported).map(s => + new vscode.DocumentSymbol(s.name, s.detail || s.container, vscode.SymbolKind[kinds[s.kind]], range(document, s.start, s.end), range(document, s.start, s.end))); + } + }), + vscode.languages.registerHoverProvider(selector, { + async provideHover(document, position, token) { + const { graph, model } = await graphAt(document, token); + if (!model || token.isCancellationRequested) return undefined; + const declarations = resolve(graph, model, document.offsetAt(position)); + if (!declarations.length) return undefined; + return new vscode.Hover(declarations.map(s => { + const contents = new vscode.MarkdownString(); + contents.appendCodeblock(s.detail || `${s.type || s.kind} ${s.qualifiedName}`, 'vas'); + contents.appendText(`\n${path.basename(s.file)}`); return contents; + })); + } + }), + vscode.languages.registerDocumentSemanticTokensProvider(selector, { + async provideDocumentSemanticTokens(document, token) { + const version = document.version, { graph, model } = await graphAt(document, token), builder = new vscode.SemanticTokensBuilder(legend); + if (!model || token.isCancellationRequested || document.version !== version) return builder.build(); + const declarations = new Map(model.symbols.map(s => [s.start, s])); + for (const word of model.tokens) { + if (word.kind !== 'id' || keywords.has(word.text)) continue; + const targets = declarations.has(word.start) ? [declarations.get(word.start)] : resolve(graph, model, word.start); + const kindsFound = new Set(targets.map(s => s.kind)); + if (kindsFound.size === 1) builder.push(range(document, word.start, word.end), [...kindsFound][0], declarations.has(word.start) ? ['declaration'] : []); + } + const macroNames = new Set(graph.flatMap(m => m.symbols.filter(s => s.kind === 'macro').map(s => s.name))); + for (const word of model.directiveWords) if (macroNames.has(word.text)) builder.push(range(document, word.start, word.end), 'macro', declarations.has(word.start) ? ['declaration'] : []); + return builder.build(); + } + }, legend) + ); + context.subscriptions.push(vscode.workspace.onDidChangeTextDocument(event => { + if (event.document.languageId === 'vas' && event.contentChanges.length) workspace.invalidate(); + })); + const watcher = vscode.workspace.createFileSystemWatcher('**/*.{vas,json}'); + context.subscriptions.push(watcher, watcher.onDidChange(() => workspace.invalidate()), watcher.onDidCreate(() => workspace.invalidate()), watcher.onDidDelete(() => workspace.invalidate())); +} + +module.exports = { registerLanguageFeatures }; diff --git a/tools/vscode-extension/src/languageModel.js b/tools/vscode-extension/src/languageModel.js new file mode 100644 index 000000000..309fff8dd --- /dev/null +++ b/tools/vscode-extension/src/languageModel.js @@ -0,0 +1,249 @@ +'use strict'; + +const fs = require('node:fs/promises'); +const path = require('node:path'); + +const keywords = new Set(('abstract auto bool break case cast class const continue default do double else enum explicit external false final float for foreach from funcdef get if import in inout int int8 int16 int32 int64 interface is mixin namespace null out override private protected property public return set shared string super switch this true try typedef uint uint8 uint16 uint32 uint64 void while').split(' ')); +const modifiers = new Set(['const', 'private', 'protected', 'public', 'shared', 'external', 'explicit', 'import']); +const nonTypes = new Set(['return', 'new', 'throw', 'case', 'else', 'break', 'continue', 'namespace', 'class', 'interface', 'enum']); +const runtime = ['print', 'println', 'getCommandLineArgs', 'getSystemTime', 'assert', 'formatInt', 'formatUInt', 'formatFloat', 'parseInt', 'parseUInt', 'parseFloat']; +const isId = text => /^[\p{L}\p{N}_]+$/u.test(text) && !/^\d/.test(text); + +/** UTF-16 offsets match editor APIs. Comments, strings and directives never become declarations. */ +function tokenize(text) { + const tokens = [], directives = [], lexicalProblems = [], protectedSpans = []; + const pattern = /\s+|\/\/[^\r\n]*|\/\*[\s\S]*?(?:\*\/|$)|"""[\s\S]*?(?:"""|$)|"(?:\\[\s\S]|[^"\\])*(?:"|$)|'(?:\\[\s\S]|[^'\\])*(?:'|$)|0[xX][\da-fA-F](?:[\da-fA-F]|'(?=[\da-fA-F]))*|0[bB][01](?:[01]|'(?=[01]))*|0[oO][0-7](?:[0-7]|'(?=[0-7]))*|0[dD]\d(?:\d|'(?=\d))*|(?:\d(?:\d|'(?=\d))*(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[fF]?|[\p{L}_][\p{L}\p{N}_]*|::|==|!=|<=|>=|&&|\|\||[\s\S]/gu; + let match; + while ((match = pattern.exec(text))) { + const value = match[0], start = match.index; + if (value.startsWith('//') || value.startsWith('/*') || /^["']/.test(value)) protectedSpans.push({ start, end: pattern.lastIndex, + closed: value.startsWith('/*') ? value.endsWith('*/') : !value.startsWith('//') && value.length > 1 && value.endsWith(value.startsWith('"""') ? '"""' : value[0]) }); + if (value.startsWith('/*') && !value.endsWith('*/')) lexicalProblems.push({ start, end: start + 2, message: 'Unterminated block comment' }); + if (/^["']/.test(value)) { + const delimiter = value.startsWith('"""') ? '"""' : value[0]; + const slashes = delimiter.length === 1 ? /\\*$/.exec(value.slice(0, -1))[0].length : 0; + if (value.length < delimiter.length * 2 || !value.endsWith(delimiter) || slashes % 2) + lexicalProblems.push({ start, end: start + delimiter.length, message: 'Unterminated string literal' }); + } + if (/^\s/.test(value) || value.startsWith('//') || value.startsWith('/*')) continue; + if (value === '#') { + const end = text.indexOf('\n', start), stop = end < 0 ? text.length : end; + const raw = text.slice(start, stop).replace(/\r$/, ''); + directives.push({ text: raw, start, end: stop }); + pattern.lastIndex = stop; + continue; + } + tokens.push({ text: value, start, end: pattern.lastIndex, kind: /^["']/.test(value) ? 'string' : isId(value) ? 'id' : /^\d|^\.\d/.test(value) ? 'number' : 'punctuation' }); + } + return { tokens, directives, lexicalProblems, protectedSpans }; +} + +function parse(text, file = '') { + const { tokens: t, directives } = text.length > 4 * 1024 * 1024 ? { tokens: [], directives: [] } : tokenize(text), symbols = [], includes = [], pairs = new Map(), stack = []; + for (let i = 0; i < t.length; i++) { + if (['(', '[', '{'].includes(t[i].text)) stack.push(i); + else if ([')', ']', '}'].includes(t[i].text)) { + const left = stack.pop(); + if (left !== undefined && '([{'.indexOf(t[left].text) === ')]}'.indexOf(t[i].text)) pairs.set(left, i); + } + } + for (const directive of directives) { + const include = /^#include\s*(?:"([^"\r\n]+)"|'([^'\r\n]+)'|<([^>\r\n]+)>)/.exec(directive.text); + if (include) includes.push({ path: include[1] || include[2] || include[3], kind: include[3] ? 'system' : 'quoted', start: directive.start, end: directive.start + include[0].length }); + const macro = /^#define[ \t]+([A-Za-z_]\w*)(.*)/.exec(directive.text); + if (macro) symbols.push({ name: macro[1], kind: 'macro', start: directive.start + macro.index + macro[0].indexOf(macro[1]), end: directive.start + macro[0].indexOf(macro[1]) + macro[1].length, scopeStart: 0, scopeEnd: text.length, container: '', exported: true, detail: directive.text, file }); + } + const scopes = [], bodyScopes = new Map(), declarations = new Set(); + const container = () => scopes.filter(s => ['namespace', 'class', 'interface', 'enum'].includes(s.kind)).map(s => s.name).join('::'); + const inFunction = () => scopes.some(s => s.kind === 'function'); + const add = (i, kind, extra = {}) => { + declarations.add(i); + const scope = scopes.at(-1); + const symbol = { name: t[i].text, kind, start: t[i].start, end: t[i].end, file, container: container(), + scopeStart: scope?.start || 0, scopeEnd: scope?.end ?? text.length, exported: !inFunction(), detail: '', ...extra }; + symbol.qualifiedName = symbol.container ? `${symbol.container}::${symbol.name}` : symbol.name; + symbols.push(symbol); return symbol; + }; + function typeBefore(i) { + let j = i - 1; + while (j >= 0 && ['@', '&', 'const', 'in', 'out', 'inout'].includes(t[j].text)) j--; + if (t[j]?.text === '>') { let depth = 1; while (--j >= 0 && depth) { if (t[j].text === '>') depth++; if (t[j].text === '<') depth--; } } + if (!t[j] || t[j].kind !== 'id' || nonTypes.has(t[j].text)) return null; + const end = j; + while (j >= 2 && t[j - 1].text === '::' && t[j - 2].kind === 'id') j -= 2; + const name = t.slice(j, end + 1).map(x => x.text).join(''); + let head = j - 1; + while (head >= 0 && modifiers.has(t[head].text)) head--; + if (head >= 0 && ![';', '{', '}', '(', ','].includes(t[head].text)) return null; + return name; + } + for (let i = 0; i < t.length; i++) { + const token = t[i], next = t[i + 1]?.text; + if (token.text === '{') { + const scope = bodyScopes.get(i) || { kind: 'block', name: '', start: token.start, end: t[pairs.get(i)]?.end ?? text.length }; + scopes.push(scope); continue; + } + if (token.text === '}') { scopes.pop(); continue; } + if (token.text === 'import' && scopes.length === 0) { + let j = i + 1, parts = []; + while (t[j]?.kind === 'id' && !keywords.has(t[j].text)) { + parts.push(t[j++].text); + if (t[j]?.text !== '.') break; + j++; + } + if (parts.length && t[j]?.text === ';') { + includes.push({ path: parts.join('/') + '.vas', kind: 'module', start: token.start, end: t[j].end }); + i = j; continue; + } + } + if (['namespace', 'class', 'interface', 'enum'].includes(token.text) && t[i + 1]?.kind === 'id') { + let j = i + 2; + while (j < t.length && !['{', ';'].includes(t[j].text)) j++; + const type = add(i + 1, token.text); + if (t[j]?.text === '{') bodyScopes.set(j, { kind: token.text, name: type.name, start: t[j].start, end: t[pairs.get(j)]?.end ?? text.length }); + continue; + } + if (token.kind !== 'id' || keywords.has(token.text) || declarations.has(i)) continue; + if (next === '(' && pairs.has(i + 1) && !inFunction()) { + const close = pairs.get(i + 1); + let tail = close + 1; + while (['const', 'override', 'final', 'property'].includes(t[tail]?.text)) tail++; + const type = typeBefore(i); + const ctor = scopes.at(-1)?.name === token.text && ['class', 'interface'].includes(scopes.at(-1)?.kind); + if ((type || ctor) && (['{', ';'].includes(t[tail]?.text) || t[tail]?.text === 'from' && t[tail + 1]?.kind === 'string' && t[tail + 2]?.text === ';')) { + const parameters = [], start = t[tail]?.text === '{' ? t[tail].start : text.length, end = t[pairs.get(tail)]?.end ?? start; + let partStart = i + 2, depth = 0; + for (let j = partStart; j <= close; j++) { + if (['(', '[', '<'].includes(t[j]?.text)) depth++; + if ([')', ']', '>'].includes(t[j]?.text) && j !== close) depth--; + if (j === close || t[j].text === ',' && depth === 0) { + const part = t.slice(partStart, j), beforeDefault = part.slice(0, part.findIndex(x => x.text === '=') < 0 ? part.length : part.findIndex(x => x.text === '=')); + const nameToken = [...beforeDefault].reverse().find(x => x.kind === 'id' && !keywords.has(x.text)); + if (part.length) parameters.push(text.slice(part[0].start, part.at(-1).end)); + if (nameToken && beforeDefault.indexOf(nameToken) > 0) { + const at = t.indexOf(nameToken); add(at, 'parameter', { type: typeBefore(at), scopeStart: start, scopeEnd: end, exported: false }); + } + partStart = j + 1; + } + } + const fn = add(i, scopes.some(s => ['class', 'interface'].includes(s.kind)) ? 'method' : 'function', { type, parameters, detail: `${type || ''} ${token.text}(${parameters.join(', ')})` }); + if (t[tail]?.text === '{') bodyScopes.set(tail, { kind: 'function', name: fn.name, start, end }); + i = close; continue; + } + } + const type = typeBefore(i); + if (type && ['=', ';', ',', '['].includes(next)) add(i, inFunction() ? 'variable' : scopes.some(s => ['class', 'interface'].includes(s.kind)) ? 'property' : 'variable', { type }); + else if (scopes.at(-1)?.kind === 'enum' && ['=', ',', '}'].includes(next)) add(i, 'enumMember', { type: container(), container: scopes.filter(s => ['namespace', 'class', 'interface'].includes(s.kind)).map(s => s.name).join('::') }); + } + const directiveWords = directives.flatMap(d => tokenize(d.text.slice(1)).tokens.filter(t => t.kind === 'id').map(t => ({ ...t, start: d.start + 1 + t.start, end: d.start + 1 + t.end }))); + return { text, file, tokens: t, symbols, includes, directiveWords }; +} + +function wordAt(model, offset) { return model.tokens.find(t => t.kind === 'id' && t.start <= offset && offset <= t.end); } + +function resolve(graph, model, offset) { + const word = wordAt(model, offset); + if (!word) return []; + const index = model.tokens.indexOf(word), t = model.tokens; + const own = model.symbols.find(s => s.start === word.start); + if (own) return [own]; + const all = graph.flatMap(m => m.symbols.filter(s => m === model || s.exported)); + const locals = model.symbols.filter(s => s.name === word.text && !s.exported && s.start <= offset && s.scopeStart <= offset && offset <= s.scopeEnd); + if (locals.length) return locals.sort((a, b) => (a.scopeEnd - a.scopeStart) - (b.scopeEnd - b.scopeStart) || b.start - a.start).slice(0, 1); + if (t[index - 1]?.text === '.') { + const receiver = t[index - 2]; + if (!receiver || receiver.kind !== 'id') return []; + const variables = resolve(graph, model, receiver.start); + if (variables.length !== 1 || !variables[0].type) return []; + const variable = variables[0], names = [variable.type, `${variable.container}::${variable.type}`]; + return all.filter(s => s.name === word.text && names.includes(s.container)); + } + let qualifier = '', j = index; + while (j >= 2 && t[j - 1].text === '::' && t[j - 2].kind === 'id') { qualifier = t[j - 2].text + (qualifier ? '::' + qualifier : ''); j -= 2; } + if (qualifier) { + let lexical = model.symbols.filter(s => s.start <= offset && s.scopeStart <= offset && offset <= s.scopeEnd).sort((a, b) => b.container.length - a.container.length)[0]?.container || ''; + const owners = [qualifier]; + for (;;) { if (lexical) owners.push(`${lexical}::${qualifier}`); if (!lexical.includes('::')) break; lexical = lexical.slice(0, lexical.lastIndexOf('::')); } + for (const owner of owners) { + const matches = all.filter(s => s.name === word.text && (s.container === owner || s.kind === 'enumMember' && s.type === owner)); + if (matches.length) return matches; + } + return []; + } + const candidates = all.filter(s => s.name === word.text && s.exported); + // Unqualified names first belong to the lexical namespace/class, then its parents. + const context = model.symbols.filter(s => s.start <= offset && s.scopeStart <= offset && offset <= s.scopeEnd).sort((a, b) => b.container.length - a.container.length)[0]?.container || ''; + let owner = context; + for (;;) { + const selected = candidates.filter(s => s.container === owner); + if (selected.length) return selected; + if (!owner) break; + owner = owner.includes('::') ? owner.slice(0, owner.lastIndexOf('::')) : ''; + } + return []; +} + +class LanguageWorkspace { + constructor(documents = () => []) { this.documents = documents; this.cache = new Map(); this.rootCache = new Map(); this.generation = 0; } + invalidate() { this.generation++; this.cache.clear(); this.rootCache.clear(); } + async read(file) { + const open = this.documents().find(d => d.uri.scheme === 'file' && path.resolve(d.uri.fsPath) === path.resolve(file)); + if (open) { + const text = open.getText(), prior = this.cache.get(file); + if (prior && prior.open && prior.model.text === text) return prior.model; + const model = parse(text, file); this.cache.set(file, { open: true, model }); return model; + } + try { + const stat = await fs.stat(file); + if (!stat.isFile() || stat.size > 4 * 1024 * 1024) return null; + const prior = this.cache.get(file); + if (prior && !prior.open && prior.mtime === stat.mtimeMs && prior.size === stat.size) return prior.model; + const model = parse(await fs.readFile(file, 'utf8'), file); + if (this.cache.size >= 256) this.cache.clear(); + this.cache.set(file, { mtime: stat.mtimeMs, size: stat.size, model }); return model; + } catch (error) { if (['ENOENT', 'ENOTDIR', 'EACCES', 'EPERM'].includes(error.code)) return null; throw error; } + } + async roots(file) { + if (this.rootCache.has(file)) return this.rootCache.get(file); + const roots = [], original = path.dirname(file); + for (let directory = original, depth = 0; depth < 16; directory = path.dirname(directory), depth++) { + roots.push(directory); + try { + const manifestFile = path.join(directory, 'vas-project.json'); + if ((await fs.stat(manifestFile)).size > 1024 * 1024) break; + const manifest = JSON.parse(await fs.readFile(manifestFile, 'utf8')); + for (const unit of manifest.compilationUnits || []) if (typeof unit.entry === 'string') roots.push(path.dirname(path.resolve(directory, unit.entry))); + break; + } catch { /* malformed or absent manifest does not disable source editing */ } + try { await fs.stat(path.join(directory, '.git')); break; } catch { } + if (directory === path.dirname(directory)) break; + } + for (const root of (process.env.VAS_INCLUDE_PATH || '').split(path.delimiter).filter(Boolean)) roots.push(path.resolve(original, root)); + const unique = [...new Set(roots)]; + if (this.rootCache.size >= 256) this.rootCache.clear(); + this.rootCache.set(file, unique); return unique; + } + async dependency(file, include, roots) { + if (path.isAbsolute(include.path) || include.path.includes(':')) return null; + const relative = include.path.replace(/\\/g, '/'); + if (include.kind !== 'system') { const local = await this.read(path.resolve(path.dirname(file), relative)); if (local) return local; } + const matches = new Map(); + for (const root of roots) { const candidate = await this.read(path.resolve(root, relative)); if (candidate) matches.set(candidate.file, candidate); } + return matches.size === 1 ? [...matches.values()][0] : null; + } + async graph(document, cancel) { + const source = parse(document.getText(), document.uri.fsPath), roots = await this.roots(source.file), graph = [], queue = [source], visited = new Set(); + let bytes = 0; + while (queue.length && graph.length < 256 && !cancel?.isCancellationRequested) { + const model = queue.shift(), identity = process.platform === 'win32' ? path.resolve(model.file).toLowerCase() : path.resolve(model.file); + if (visited.has(identity)) continue; + visited.add(identity); bytes += model.text.length; + if (bytes > 16 * 1024 * 1024) break; + graph.push(model); + for (const include of model.includes) { const dependency = await this.dependency(model.file, include, roots); if (dependency) queue.push(dependency); } + } + return graph; + } +} + +module.exports = { tokenize, parse, resolve, wordAt, LanguageWorkspace, keywords, runtime }; diff --git a/tools/vscode-extension/src/liveDiagnostics.js b/tools/vscode-extension/src/liveDiagnostics.js new file mode 100644 index 000000000..2ef8c02a4 --- /dev/null +++ b/tools/vscode-extension/src/liveDiagnostics.js @@ -0,0 +1,91 @@ +'use strict'; +const fs = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const { execFile } = require('node:child_process'); +const { compilerPath } = require('./project'); +const { parseDiagnostic, sourcePosition } = require('./diagnostics'); +const { inspectSyntax } = require('./editingSupport'); + +function registerLiveDiagnostics(vscode, context, workspace) { + const collection = vscode.languages.createDiagnosticCollection('vas-live'); + let generation = 0, timer, child, disposed = false; + const structural = document => inspectSyntax(document.getText()).map(problem => new vscode.Diagnostic( + new vscode.Range(document.positionAt(problem.start), document.positionAt(problem.end)), problem.message, vscode.DiagnosticSeverity.Error)); + const opened = () => vscode.workspace.textDocuments.filter(d => d.languageId === 'vas' && d.uri.scheme === 'file' && !d.isClosed); + const publishStructure = document => collection.set(document.uri, structural(document)); + const run = async (document, revision) => { + if (!vscode.workspace.isTrusted || !vscode.workspace.getConfiguration('vas', document.uri).get('liveDiagnostics', true)) return; + const folder = vscode.workspace.getWorkspaceFolder(document.uri); + if (!folder) return; + const root = path.resolve(folder.uri.fsPath), config = vscode.workspace.getConfiguration('vas', document.uri); + let compiler; + try { compiler = compilerPath(config); } catch { return; } + if (!compiler) return; + const text = document.getText(), version = document.version; + const revisions = opened().map(d => [d, d.version]); + let interfaceFile = config.get('configFile', '${workspaceFolder}/.vas/vasbuild.config.txt').replaceAll('${workspaceFolder}', root); + if (!path.isAbsolute(interfaceFile)) interfaceFile = path.resolve(root, interfaceFile); + try { if (!(await fs.stat(interfaceFile)).isFile()) return; } catch { return; } + const graph = await workspace.graph(document, { get isCancellationRequested() { return revision !== generation; } }); + if (!graph.length || revision !== generation) return; + // A graph outside this workspace needs a selected compilation root. Do not + // silently compile a partial mirror and manufacture missing-module errors. + if (graph.some(source => { const relative = path.relative(root, source.file); return relative.startsWith('..') || path.isAbsolute(relative); })) return; + let temporary; + try { + temporary = await fs.mkdtemp(path.join(os.tmpdir(), 'vas-vscode-diagnostics-')); + for (const source of graph) { + const target = path.join(temporary, path.relative(root, source.file)); + await fs.mkdir(path.dirname(target), { recursive: true }); await fs.writeFile(target, source.text, 'utf8'); + } + const source = path.join(temporary, path.relative(root, document.uri.fsPath)); + const roots = []; + for (let parent = path.dirname(source); parent.startsWith(temporary); parent = path.dirname(parent)) { + roots.push(parent); if (parent === temporary) break; + } + if (revision !== generation || disposed) return; + const output = await new Promise(resolve => { + const compilerProcess = execFile(compiler, [interfaceFile, source, path.join(temporary, 'diagnostics.vasbc')], { + cwd: temporary, windowsHide: true, timeout: 10000, maxBuffer: 2 * 1024 * 1024, encoding: 'utf8', + env: { ...process.env, VAS_INCLUDE_PATH: roots.join(path.delimiter) } + }, (error, stdout, stderr) => { if (child === compilerProcess) child = undefined; resolve(error?.killed ? '' : stdout + stderr); }); + child = compilerProcess; + }); + if (disposed || revision !== generation || document.isClosed || document.version !== version || revisions.some(([d, v]) => d.isClosed || d.version !== v)) return; + const diagnostics = structural(document); + for (const line of output.split(/\r?\n/)) { + const issue = parseDiagnostic(line, temporary); + if (!issue || issue.row < 1 || issue.column < 1) continue; + const reportedFile = path.resolve(issue.file), entryFile = path.resolve(source); + if (process.platform === 'win32' ? reportedFile.toLowerCase() !== entryFile.toLowerCase() : reportedFile !== entryFile) continue; + const start = sourcePosition(text, issue.row, issue.column); + const position = new vscode.Position(start.line, start.character); + const range = document.getWordRangeAtPosition(position) || new vscode.Range(position, position.translate(0, Math.min(1, document.lineAt(position.line).text.length - position.character))); + if (!diagnostics.some(d => d.message === issue.message && d.range.start.isEqual(position))) { + const diagnostic = new vscode.Diagnostic(range, issue.message, issue.severity === 'ERR' ? vscode.DiagnosticSeverity.Error : vscode.DiagnosticSeverity.Warning); + diagnostic.source = 'vasbuild'; diagnostics.push(diagnostic); + } + } + collection.set(document.uri, diagnostics); + } catch (error) { if (!['ENOENT', 'EACCES', 'EPERM'].includes(error.code)) console.error('VAS live diagnostics:', error.message); } + finally { + if (temporary && path.dirname(path.resolve(temporary)) === path.resolve(os.tmpdir()) && path.basename(temporary).startsWith('vas-vscode-diagnostics-')) await fs.rm(temporary, { recursive: true, force: true }); + } + }; + function schedule() { + const revision = ++generation; clearTimeout(timer); child?.kill(); + for (const document of opened()) publishStructure(document); + timer = setTimeout(async () => { + const active = vscode.window.activeTextEditor?.document, documents = opened().sort((a, b) => Number(b === active) - Number(a === active)); + for (const document of documents) { if (revision !== generation || disposed) break; await run(document, revision); } + }, 450); + } + context.subscriptions.push(collection, + vscode.workspace.onDidOpenTextDocument(schedule), vscode.workspace.onDidCloseTextDocument(document => { collection.delete(document.uri); schedule(); }), + vscode.workspace.onDidChangeTextDocument(event => { if (event.document.languageId === 'vas' && event.contentChanges.length) schedule(); }), + vscode.workspace.onDidChangeConfiguration(event => { if (event.affectsConfiguration('vas')) schedule(); }), + { dispose() { disposed = true; generation++; clearTimeout(timer); child?.kill(); } }); + schedule(); +} +module.exports = { registerLiveDiagnostics }; diff --git a/tools/vscode-extension/syntaxes/vas.tmLanguage.json b/tools/vscode-extension/syntaxes/vas.tmLanguage.json index 43314cc2b..5ea82dd79 100644 --- a/tools/vscode-extension/syntaxes/vas.tmLanguage.json +++ b/tools/vscode-extension/syntaxes/vas.tmLanguage.json @@ -5,9 +5,11 @@ "fileTypes": ["vas"], "patterns": [ { "include": "#comments" }, + { "include": "#macro-definition" }, { "include": "#preprocessor" }, { "include": "#strings" }, { "include": "#numbers" }, + { "include": "#module-import" }, { "include": "#declarations" }, { "include": "#keywords" }, { "include": "#functions" }, @@ -49,6 +51,65 @@ { "include": "#operators" } ] }, + "macro-definition": { + "name": "meta.preprocessor.vas", + "begin": "^\\s*(#)(define)[ \\t]+([A-Za-z_][A-Za-z0-9_]*)", + "beginCaptures": { + "1": { + "name": "punctuation.definition.directive.vas" + }, + "2": { + "name": "keyword.control.directive.vas" + }, + "3": { + "name": "entity.name.function.preprocessor.vas" + } + }, + "end": "$", + "patterns": [ + { + "include": "#comments" + }, + { + "include": "#strings" + }, + { + "include": "#numbers" + }, + { + "include": "#keywords" + }, + { + "include": "#operators" + } + ] + }, + "module-import": { + "match": "\\b(import)\\s+([[:alpha:]_][[:alnum:]_]*(?:\\s*\\.\\s*[[:alpha:]_][[:alnum:]_]*)*)\\s*(;)", + "captures": { + "1": { + "name": "keyword.control.vas" + }, + "2": { + "name": "entity.name.namespace.vas" + }, + "3": { + "name": "punctuation.terminator.vas" + } + } + }, + "format-fields": { + "patterns": [ + { + "name": "constant.character.escape.format.vas", + "match": "\\{\\{|\\}\\}" + }, + { + "name": "constant.other.placeholder.vas", + "match": "\\{(?:[0-9]+)?(?::[^{}]*(?:\\{[0-9]*\\}[^{}]*)*)?\\}" + } + ] + }, "strings": { "patterns": [ { @@ -65,7 +126,7 @@ "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.vas" } }, "end": "\"|$", "endCaptures": { "0": { "name": "punctuation.definition.string.end.vas" } }, - "patterns": [ { "include": "#escapes" } ] + "patterns": [ { "include": "#format-fields" }, { "include": "#escapes" } ] }, { "name": "string.quoted.single.vas", @@ -73,7 +134,7 @@ "beginCaptures": { "0": { "name": "punctuation.definition.string.begin.vas" } }, "end": "'|$", "endCaptures": { "0": { "name": "punctuation.definition.string.end.vas" } }, - "patterns": [ { "include": "#escapes" } ] + "patterns": [ { "include": "#format-fields" }, { "include": "#escapes" } ] } ] }, diff --git a/tools/vscode-extension/test/editingIntegration.js b/tools/vscode-extension/test/editingIntegration.js new file mode 100644 index 000000000..420fb1c20 --- /dev/null +++ b/tools/vscode-extension/test/editingIntegration.js @@ -0,0 +1,59 @@ +'use strict'; +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const path = require('node:path'); +const vscode = require('vscode'); + +async function run() { + const folder = vscode.workspace.workspaceFolders[0].uri.fsPath, file = path.join(folder, 'editor.vas'); + await fs.writeFile(file, ''); + await vscode.extensions.getExtension('VerseAngelScript.verseangelscript-vscode').activate(); + const document = await vscode.workspace.openTextDocument(file), editor = await vscode.window.showTextDocument(document); + const replace = async text => { + const edit = new vscode.WorkspaceEdit(); edit.replace(document.uri, new vscode.Range(document.positionAt(0), document.positionAt(document.getText().length)), text); + assert(await vscode.workspace.applyEdit(edit)); const end = document.positionAt(document.getText().length); editor.selection = new vscode.Selection(end, end); + }; + for (const [open, close] of [['{', '}'], ['(', ')'], ['[', ']'], ['"', '"'], ["'", "'"]]) { + await replace(''); await vscode.commands.executeCommand('type', { text: open }); assert.equal(document.getText(), open + close); + assert.equal(document.offsetAt(editor.selection.active), 1); + await vscode.commands.executeCommand('deleteLeft'); assert.equal(document.getText(), ''); + await vscode.commands.executeCommand('type', { text: open }); await vscode.commands.executeCommand('type', { text: close }); + assert.equal(document.getText(), open + close); assert.equal(document.offsetAt(editor.selection.active), 2); + } + await replace('// comment '); await vscode.commands.executeCommand('type', { text: '{' }); assert.equal(document.getText(), '// comment {'); + const prefix = 'int CalculateScore(int Left, int Right) { return Left + Right; }\nvoid Main() { Calcu'; + await replace(prefix); + const items = await vscode.commands.executeCommand('vscode.executeCompletionItemProvider', document.uri, editor.selection.active); + const functionItem = items.items.find(item => item.label === 'CalculateScore'); assert(functionItem); assert.equal(functionItem.insertText.value, 'CalculateScore($0)'); + await vscode.commands.executeCommand('editor.action.triggerSuggest'); await new Promise(r => setTimeout(r, 300)); + await vscode.commands.executeCommand('acceptSelectedSuggestion'); + assert(document.getText().endsWith('CalculateScore()'), document.getText()); + assert.equal(document.getText()[document.offsetAt(editor.selection.active)], ')'); + const help = await vscode.commands.executeCommand('vscode.executeSignatureHelpProvider', document.uri, editor.selection.active, '('); + assert(help.signatures[0].label.includes('CalculateScore')); assert.equal(help.signatures[0].parameters.length, 2); + const waitFor = async predicate => { + for (let i = 0; i < 100; i++) { const values = vscode.languages.getDiagnostics(document.uri); if (predicate(values)) return values; await new Promise(r => setTimeout(r, 100)); } + throw new Error('Diagnostic wait failed: ' + JSON.stringify(vscode.languages.getDiagnostics(document.uri))); + }; + await replace('void Main() {'); await waitFor(values => values.some(d => d.message === "Expected '}'")); + await replace('void Main() { int Value = MissingEditorName; }'); + await waitFor(values => values.some(d => d.source === 'vasbuild' && d.message.includes('MissingEditorName'))); + await replace('void Main() { int Value = 1 return; }'); await waitFor(values => values.some(d => d.source === 'vasbuild')); + await replace('void Main() { int Value = 1; }'); await waitFor(values => values.length === 0); + const libraryFile = path.join(folder, 'Library.vas'); await fs.writeFile(libraryFile, 'namespace Library { int Value() { return 1; } }'); + const library = await vscode.workspace.openTextDocument(libraryFile); + const change = new vscode.WorkspaceEdit(); change.replace(library.uri, new vscode.Range(library.positionAt(0), library.positionAt(library.getText().length)), 'namespace Library { int NewValue() { return 2; } }'); assert(await vscode.workspace.applyEdit(change)); + await replace('import Library;\nvoid Main() { int Value = Library::NewValue(); }'); await waitFor(values => values.length === 0); + await new Promise(r => setTimeout(r, 800)); assert.equal(vscode.languages.getDiagnostics(document.uri).length, 0); + if (process.platform === 'linux') { + await fs.writeFile(path.join(folder, 'Editor.vas'), 'void BrokenCase() { UnknownCaseName(); }'); + await replace('import Editor;\nvoid Main() {}'); + await new Promise(r => setTimeout(r, 2000)); + assert.equal(vscode.languages.getDiagnostics(document.uri).length, 0, 'case-distinct imported errors must not be published on editor.vas'); + } + const evidence = { host: vscode.version, nativeTyping: true, pairs: 5, closingSkip: true, pairedBackspace: true, commentProtection: true, + nativeFunctionCompletion: true, parameterHelp: true, structuralErrors: true, nativeCompilerErrors: true, missingSemicolon: true, clearedErrorsAfterFix: true, unsavedImport: true }; + await fs.writeFile(process.env.VAS_EDITING_EVIDENCE, JSON.stringify(evidence, null, 2)); + console.log('VAS editing integration PASS ' + JSON.stringify(evidence)); +} +module.exports = { run }; diff --git a/tools/vscode-extension/test/editingSupport.test.js b/tools/vscode-extension/test/editingSupport.test.js new file mode 100644 index 000000000..33f648054 --- /dev/null +++ b/tools/vscode-extension/test/editingSupport.test.js @@ -0,0 +1,23 @@ +'use strict'; +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { inspectSyntax, callAt, signature } = require('../src/editingSupport'); + +test('structural diagnostics protect literals, comments, number separators and inactive branches', () => { + assert.deepEqual(inspectSyntax('void Main() { string S = "} )"; int Value = 0xAB\'CD; /* ] */ }'), []); + assert.deepEqual(inspectSyntax('string S = """} ] (\n""";'), []); + assert(inspectSyntax('void Main(] {}').some(p => p.message === "Unexpected ']'")); + assert(inspectSyntax('void Main() {').some(p => p.message === "Expected '}'")); + assert(inspectSyntax('string S = "escaped\\"').some(p => p.message.includes('string'))); + assert(inspectSyntax('/* unterminated').some(p => p.message.includes('comment'))); + assert.deepEqual(inspectSyntax('#if OTHER\nvoid Different() {\n#else\nvoid Main() {}\n#endif'), []); +}); +test('parameter help tracks innermost argument, nested expressions and default parameter commas', () => { + const text = 'Outer(Inner(1, 2), {3,4}, "comma,", '; + assert.equal(callAt(text, text.length).name, 'Outer'); + assert.equal(callAt(text, text.length).parameter, 3); + assert.equal(callAt('Outer(Inner(1, ', 15).name, 'Inner'); + const info = signature('Add(array@ Values, int Count = Other(1,2), string S = "a,b")'); + assert.equal(info.parameters.length, 3); + assert.equal(info.label.slice(...info.parameters[2]), 'string S = "a,b"'); +}); diff --git a/tools/vscode-extension/test/language.test.js b/tools/vscode-extension/test/language.test.js index 6d8cd68f3..66fa2b207 100644 --- a/tools/vscode-extension/test/language.test.js +++ b/tools/vscode-extension/test/language.test.js @@ -263,3 +263,14 @@ test('snippets are well-formed and use standalone VAS syntax', () => { assert.ok(snippets['Include VAS file'].body[0].endsWith('.vas"')); assert.equal(snippets['VAS entry point'].body[0], 'void main()'); }); + + +test('module imports, exported macro names and format fields have separate scopes', () => { + const lines = ['import Arena.Demo;', '#define VAS_ARENA_MAX_ROUNDS 12', 'println("ABC {} {1:04d} {{literal}}", Value, Other);']; + const tokens = tokenize(lines.join('\n')); + assertScope(tokens[0], lines[0], 'Arena.Demo', 'entity.name.namespace.vas'); + assertScope(tokens[1], lines[1], 'VAS_ARENA_MAX_ROUNDS', 'entity.name.function.preprocessor.vas'); + assertScope(tokens[2], lines[2], '{}', 'constant.other.placeholder.vas'); + assertScope(tokens[2], lines[2], '{1:04d}', 'constant.other.placeholder.vas'); + assertScope(tokens[2], lines[2], '{{', 'constant.character.escape.format.vas'); +}); diff --git a/tools/vscode-extension/test/languageIntegration.js b/tools/vscode-extension/test/languageIntegration.js new file mode 100644 index 000000000..c28c91fd1 --- /dev/null +++ b/tools/vscode-extension/test/languageIntegration.js @@ -0,0 +1,51 @@ +'use strict'; +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const path = require('node:path'); +const vscode = require('vscode'); + +async function run() { + const root = path.resolve(__dirname, '../../..'), entry = path.join(root, 'examples/arena/main.vas'); + const extension = vscode.extensions.getExtension('VerseAngelScript.verseangelscript-vscode'); + assert(extension); await extension.activate(); + const document = await vscode.workspace.openTextDocument(entry); + await vscode.window.showTextDocument(document); + assert.equal(document.languageId, 'vas'); + const position = text => document.positionAt(document.getText().indexOf(text)); + const definitions = await vscode.commands.executeCommand('vscode.executeDefinitionProvider', document.uri, position('RunDemo(')); + assert.equal(definitions.length, 1); assert.equal(path.basename(definitions[0].uri.fsPath), 'Demo.vas'); + const imported = await vscode.commands.executeCommand('vscode.executeDefinitionProvider', document.uri, position('Arena.Demo')); + assert.equal(path.basename(imported[0].uri.fsPath), 'Demo.vas'); + const completion = await vscode.commands.executeCommand('vscode.executeCompletionItemProvider', document.uri, position('RunDemo(')); + assert(completion.items.some(item => item.label === 'RunDemo')); + assert(completion.items.some(item => item.label === 'RunBatch')); + assert(!completion.items.some(item => item.label === 'VAS_ARENA_MAX_ROUNDS'), 'namespace completion must exclude global macros'); + const unqualified = await vscode.commands.executeCommand('vscode.executeCompletionItemProvider', document.uri, position('return 0;')); + assert(unqualified.items.some(item => item.label === 'VAS_ARENA_MAX_ROUNDS')); + assert(unqualified.items.some(item => item.label === 'println')); + const symbols = await vscode.commands.executeCommand('vscode.executeDocumentSymbolProvider', document.uri); + assert(symbols.some(symbol => symbol.name === 'main')); + const hover = await vscode.commands.executeCommand('vscode.executeHoverProvider', document.uri, position('RunDemo(')); + assert(hover.length > 0); + const legend = await vscode.commands.executeCommand('vscode.provideDocumentSemanticTokensLegend', document.uri); + const semantic = await vscode.commands.executeCommand('vscode.provideDocumentSemanticTokens', document.uri); + assert(legend.tokenTypes.includes('macro')); assert(semantic.data.length >= 5); + const combatant = await vscode.workspace.openTextDocument(path.join(root, 'examples/arena/Arena/Combatant.vas')); + const role = await vscode.commands.executeCommand('vscode.executeDefinitionProvider', combatant.uri, combatant.positionAt(combatant.getText().indexOf('Warrior, 90'))); + assert.equal(role.length, 1); assert.equal(path.basename(role[0].uri.fsPath), 'Combatant.vas'); + assert(role[0].range.start.line < combatant.positionAt(combatant.getText().indexOf('Warrior, 90')).line); + const demo = await vscode.workspace.openTextDocument(definitions[0].uri), before = demo.getText(); + const edit = new vscode.WorkspaceEdit(); + const start = before.indexOf('RunDemo('); + edit.replace(demo.uri, new vscode.Range(demo.positionAt(start), demo.positionAt(start + 7)), 'RunChangedDemo'); + assert(await vscode.workspace.applyEdit(edit)); + const after = await vscode.commands.executeCommand('vscode.executeDefinitionProvider', document.uri, position('RunDemo(')); + assert.equal(after.length, 0, 'unsaved imported source must invalidate navigation'); + await vscode.window.showTextDocument(demo); await vscode.commands.executeCommand('workbench.action.files.revert'); + const restored = await vscode.commands.executeCommand('vscode.executeDefinitionProvider', document.uri, position('RunDemo(')); + assert.equal(restored.length, 1); + const evidence = { version: vscode.version, files: 9, definition: 'Arena/Demo.vas:RunDemo', importNavigation: true, completion: true, macros: true, documentSymbols: true, hover: true, semanticTokens: semantic.data.length / 5, unsavedInvalidation: true, enumNavigation: true }; + if (process.env.VAS_LANGUAGE_EVIDENCE) await fs.writeFile(process.env.VAS_LANGUAGE_EVIDENCE, JSON.stringify(evidence, null, 2)); + console.log('VAS language integration PASS ' + JSON.stringify(evidence)); +} +module.exports = { run }; diff --git a/tools/vscode-extension/test/languageModel.test.js b/tools/vscode-extension/test/languageModel.test.js new file mode 100644 index 000000000..ccb70677c --- /dev/null +++ b/tools/vscode-extension/test/languageModel.test.js @@ -0,0 +1,68 @@ +'use strict'; +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const path = require('node:path'); +const os = require('node:os'); +const { parse, resolve, LanguageWorkspace } = require('../src/languageModel'); + +test('strings, comments, based integers and macro bodies cannot forge declarations/imports', () => { + const model = parse('/* import Wrong; */ string Text = "import Fake; class Spoof {}";\n#define CODE class Forged {}\nint Value = 0xAB\'CD;\nimport Real.Library;\nimport int External(int Value) from "Legacy";'); + assert.deepEqual(model.includes.map(i => i.path), ['Real/Library.vas']); + assert(model.symbols.some(s => s.name === 'External' && s.kind === 'function')); + assert(model.symbols.some(s => s.name === 'CODE' && s.kind === 'macro')); + assert(!model.symbols.some(s => ['Spoof', 'Forged', 'AB', 'CD'].includes(s.name))); +}); + +test('declarations, lexical shadowing, namespace and typed receiver navigation', () => { + const library = parse('namespace Arena { class FHero { int Health; void Heal(int Amount) {} } int Add(int A, int B) { return A+B; } }', 'library.vas'); + const source = parse('import Arena.Library;\nvoid Main() { Arena::FHero Hero; int Value = 1; { int Value = 2; print(Value); } print(Value); Hero.Heal(3); Arena::Add(1,2); }', 'main.vas'); + const graph = [source, library]; + const localUses = [...source.text.matchAll(/print\(Value/g)].map(m => m.index + 6); + assert.equal(resolve(graph, source, localUses[0])[0].start, source.text.indexOf('Value = 2')); + assert.equal(resolve(graph, source, localUses[1])[0].start, source.text.indexOf('Value = 1')); + assert.equal(resolve(graph, source, source.text.indexOf('Heal(3)'))[0].qualifiedName, 'Arena::FHero::Heal'); + assert.equal(resolve(graph, source, source.text.indexOf('Add(1,2)'))[0].qualifiedName, 'Arena::Add'); + assert.equal(library.symbols.find(s => s.name === 'Amount').kind, 'parameter'); +}); + +test('arena example: nine-file import closure, transitive macros, typed members and unsaved changes', async () => { + const file = path.resolve(__dirname, '../../../examples/arena/main.vas'); + const text = await fs.readFile(file, 'utf8'), document = { uri: { scheme: 'file', fsPath: file }, getText: () => text }; + const workspace = new LanguageWorkspace(), graph = await workspace.graph(document); + assert.equal(graph.length, 9); + const target = resolve(graph, graph[0], text.indexOf('RunDemo(')); + assert.equal(target.length, 1); + assert.equal(path.basename(target[0].file), 'Demo.vas'); + assert.equal(target[0].container, 'Arena'); + assert(graph.flatMap(m => m.symbols).some(s => s.name === 'VAS_ARENA_MAX_ROUNDS' && s.kind === 'macro')); + const report = graph.find(m => m.file.endsWith('Report.vas')); + assert(report.symbols.some(s => s.name === 'PrintStandings')); + const original = graph.find(m => m.file.endsWith('Demo.vas')); + workspace.documents = () => [{ uri: { scheme: 'file', fsPath: original.file }, getText: () => original.text.replace('RunDemo(', 'RunChangedDemo(') }]; + const changed = await workspace.graph(document); + assert.equal(resolve(changed, changed[0], text.indexOf('RunDemo(')).length, 0); +}); + +test('dependency cycles deduplicate; ambiguous entry roots do not choose an arbitrary file', async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'vas-language-')); + try { + await fs.mkdir(path.join(root, 'src', 'Nested'), { recursive: true }); + await fs.writeFile(path.join(root, 'vas-project.json'), JSON.stringify({ compilationUnits: [{ entry: 'src/main.vas' }] })); + await fs.writeFile(path.join(root, 'src/main.vas'), 'import Nested.Module;'); + await fs.writeFile(path.join(root, 'src/Nested/Module.vas'), 'import Common;'); + await fs.writeFile(path.join(root, 'src/Common.vas'), '#include "main.vas"\nint Value;'); + const document = { uri: { scheme: 'file', fsPath: path.join(root, 'src/main.vas') }, getText: () => 'import Nested.Module;' }; + const workspace = new LanguageWorkspace(); + assert.equal((await workspace.graph(document)).length, 3); + await fs.writeFile(path.join(root, 'Common.vas'), 'int Unrelated;'); + assert.equal((await workspace.graph(document)).length, 2); + } finally { await fs.rm(root, { recursive: true, force: true }); } +}); + + +test('enum constants support both namespace exports and explicit enum qualification', () => { + const model = parse('namespace Arena { enum ERole { Warrior, Medic } void Main() { print(Warrior); print(ERole::Warrior); print(Arena::ERole::Warrior); } }'); + const offsets = [...model.text.matchAll(/Warrior\);/g)].map(match => match.index); + for (const offset of offsets) assert.equal(resolve([model], model, offset)[0].kind, 'enumMember'); +}); diff --git a/tools/vscode-extension/test/measureLanguage.js b/tools/vscode-extension/test/measureLanguage.js new file mode 100644 index 000000000..f043dfbd2 --- /dev/null +++ b/tools/vscode-extension/test/measureLanguage.js @@ -0,0 +1,37 @@ +'use strict'; +const { performance } = require('node:perf_hooks'); +const fs = require('node:fs/promises'); +const path = require('node:path'); +const assert = require('node:assert/strict'); +const { LanguageWorkspace, resolve } = require('../src/languageModel'); + +async function main() { + const file = path.resolve(__dirname, '../../../examples/arena/main.vas'), text = await fs.readFile(file, 'utf8'); + const document = { uri: { scheme: 'file', fsPath: file }, getText: () => text }, workspace = new LanguageWorkspace(); + const phases = {}; + for (const phase of ['uncached', 'cached']) { + const durations = []; + for (let repeat = 0; repeat < 31; repeat++) { + if (phase === 'uncached') workspace.invalidate(); + const start = performance.now(), graph = await workspace.graph(document); + assert.equal(graph.length, 9); + assert.equal(resolve(graph, graph[0], text.indexOf('RunDemo(')).length, 1); + durations.push(performance.now() - start); + } + durations.sort((a, b) => a - b); + phases[phase] = { medianMs: durations[15], p95Ms: durations[29] }; + } + const graph = await workspace.graph(document), durations = []; + for (let repeat = 0; repeat < 31; repeat++) { + const start = performance.now(); let resolved = 0; + for (const word of graph[0].tokens.filter(t => t.kind === 'id')) if (resolve(graph, graph[0], word.start).length) resolved++; + assert(resolved > 0); durations.push(performance.now() - start); + } + durations.sort((a, b) => a - b); + phases.semanticLookup = { medianMs: durations[15], p95Ms: durations[29] }; + const result = { node: process.version, files: 9, samples: 31, scope: 'source model/import graph only; excludes IDE startup/rendering; filesystem cache may be warm', ...phases }; + const output = path.resolve(__dirname, '../../../out/verification/ide/vscode-performance.json'); + await fs.mkdir(path.dirname(output), { recursive: true }); await fs.writeFile(output, JSON.stringify(result, null, 2)); + console.log(JSON.stringify(result, null, 2)); +} +if (require.main === module) main().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/tools/vscode-extension/test/runIntegration.js b/tools/vscode-extension/test/runIntegration.js index 4ad01a3ab..3f8d49a18 100644 --- a/tools/vscode-extension/test/runIntegration.js +++ b/tools/vscode-extension/test/runIntegration.js @@ -1,5 +1,6 @@ 'use strict'; +const assert = require('node:assert/strict'); const fs = require('node:fs/promises'); const path = require('node:path'); const os = require('node:os'); @@ -320,6 +321,8 @@ async function main() { // Test extension dirty-input guards with deterministic unsaved editors. // The workbench's own save-before-run must not clear the test condition. 'task.saveBeforeRun': 'never', 'files.autoSave': 'off', + // Project-command process audits are separate from live editing checks below. + 'vas.liveDiagnostics': false, 'vas.compilerPath': process.env.VAS_TEST_COMPILER, 'vas.runnerPath': process.env.VAS_TEST_RUNNER }); @@ -342,6 +345,34 @@ async function main() { // Retain source/config bytes and hardlinks across alias and legacy modes. await removeBuildArtifacts(workspaces); } + const editingWorkspace = path.join(root, 'language editing'); + await fs.mkdir(path.join(editingWorkspace, '.vas'), { recursive: true }); + await fs.copyFile(path.resolve(__dirname, '../../../sdk/samples/asbuild/bin/config.txt'), + path.join(editingWorkspace, '.vas', 'vasbuild.config.txt')); + for (const mode of ['language', 'editing']) { + const userData = path.join(root, mode); + await fs.mkdir(path.join(userData, 'User'), { recursive: true }); + await writeJson(path.join(userData, 'User', 'settings.json'), { + 'update.mode': 'none', 'telemetry.telemetryLevel': 'off', 'files.autoSave': 'off', + 'vas.compilerPath': process.env.VAS_TEST_COMPILER, + 'vas.liveDiagnostics': true + }); + const key = mode === 'editing' ? 'VAS_EDITING_EVIDENCE' : 'VAS_LANGUAGE_EVIDENCE'; + const previous = process.env[key]; + const result = path.join(evidenceFile ? path.dirname(evidenceFile) : root, `${mode}-evidence.json`); + process.env[key] = result; + try { + await launch(executable, [editingWorkspace, '--user-data-dir', userData, + '--extensions-dir', path.join(userData, 'extensions'), '--disable-extensions', + '--disable-workspace-trust', '--skip-welcome', '--skip-release-notes', '--disable-updates', '--no-sandbox', + `--extensionDevelopmentPath=${path.resolve(__dirname, '..')}`, + `--extensionTestsPath=${path.join(__dirname, `${mode}Integration.js`)}`], mode); + const report = JSON.parse(await fs.readFile(result, 'utf8')); + assert.equal(report.host || report.version, identity?.version || report.host || report.version); + } finally { + if (previous === undefined) delete process.env[key]; else process.env[key] = previous; + } + } if (evidenceFile) await runtimeEvidence.finish(evidenceFile, identity, process.env.VSCODE_TEST_VERSION || '1.96.4', passedModes); } catch (error) { cleanupRoot = !error.hostCleanupFailed;