Initial commit from sysy-main
This commit is contained in:
41
.gitignore
vendored
Normal file
41
.gitignore
vendored
Normal file
@ -0,0 +1,41 @@
|
||||
# Prerequisites
|
||||
*.d
|
||||
|
||||
# Compiled Object files
|
||||
*.slo
|
||||
*.lo
|
||||
*.o
|
||||
*.obj
|
||||
|
||||
# Precompiled Headers
|
||||
*.gch
|
||||
*.pch
|
||||
|
||||
# Compiled Dynamic libraries
|
||||
*.so
|
||||
*.dylib
|
||||
*.dll
|
||||
|
||||
# Fortran module files
|
||||
*.mod
|
||||
*.smod
|
||||
|
||||
# Compiled Static libraries
|
||||
*.lai
|
||||
*.la
|
||||
*.a
|
||||
*.lib
|
||||
|
||||
# Executables
|
||||
*.exe
|
||||
*.out
|
||||
*.app
|
||||
|
||||
.cache
|
||||
.~
|
||||
doxygen
|
||||
|
||||
!/testdata/functional/*.out
|
||||
!/testdata/performance/*.out
|
||||
build
|
||||
.antlr
|
||||
39
CMakeLists.txt
Normal file
39
CMakeLists.txt
Normal file
@ -0,0 +1,39 @@
|
||||
cmake_minimum_required (VERSION 3.19)
|
||||
|
||||
# cmake_policy(SET CMP0135 OLD)
|
||||
|
||||
set(CMAKE_DISABLE_IN_SOURCE_BUILD ON)
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
|
||||
project(sysy
|
||||
VERSION 0.0.0.1
|
||||
DESCRIPTION "The SysY language compiler"
|
||||
LANGUAGES CXX
|
||||
)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17 CACHE STRING "C++ standard to conform to")
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED YES)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
if(NOT CMAKE_BUILD_TYPE)
|
||||
message(STATUS "Build type not set, falling back to Debug mode.")
|
||||
set(CMAKE_BUILD_TYPE "Release" CACHE STRING
|
||||
"Choose the type of build, options are: Debug Release." FORCE)
|
||||
endif(NOT CMAKE_BUILD_TYPE)
|
||||
|
||||
# Set output directories
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)
|
||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)
|
||||
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin)
|
||||
|
||||
# ANTLR
|
||||
set(ANTLR_EXECUTABLE "${PROJECT_SOURCE_DIR}/antlr/antlr-4.13.2-complete.jar")
|
||||
set(ANTLR_RUNTIME "${PROJECT_SOURCE_DIR}/antlr/antlr4-runtime-4.13.2")
|
||||
|
||||
set(ANTLR4_INSTALL ON)
|
||||
set(WITH_DEMO OFF)
|
||||
set(ANTLR_BUILD_CPP_TESTS OFF)
|
||||
add_subdirectory(${ANTLR_RUNTIME})
|
||||
|
||||
# Project source files
|
||||
add_subdirectory(src)
|
||||
401
README.md
Normal file
401
README.md
Normal file
@ -0,0 +1,401 @@
|
||||
# CCRG SysY Compiler
|
||||
|
||||
用于实现SysY编译器的代码框架。
|
||||
|
||||
## Getting Started
|
||||
|
||||
建议使用Ubuntu 22.04系统,原生版本与WSL版本均可。
|
||||
|
||||
[Ubuntu下载与安装说明](https://ubuntu.com/download/desktop)
|
||||
|
||||
[WSL Ubuntu安装说明](https://learn.microsoft.com/en-us/windows/wsl/install)
|
||||
|
||||
SysY编译器前端基于[ANTLR](https://www.antlr.org/index.html)工具实现,本仓库已经包含ANTLR 4.12.0版本的可执行程序与C++运行时库,但编译ANTLR运行时库存在一些依赖,需要提前安装。
|
||||
|
||||
```bash
|
||||
sudo apt update
|
||||
sudo apt install -y uuid-dev libutfcpp-dev pkg-config make git cmake openjdk-11-jre
|
||||
```
|
||||
|
||||
依赖安装完成后,可以开始构建SysY编译器(构建过程包含了ANTLR运行时库的构建)。
|
||||
|
||||
```bash
|
||||
git clone https://gitee.com/xsu1989/sysy.git
|
||||
cd sysy
|
||||
cmake -S . -B build
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
构建完成后,可以运行一个小的测试用例。该测试将逗号分隔的整数或字符串列表进行格式化后重新输出,即将相邻参数之间的分隔统一调整为逗号外加一个空格。
|
||||
|
||||
```bash
|
||||
cat /test/funcrparams.sysy
|
||||
# -> 1,0xa , 011, "hellow"
|
||||
./build/bin/sysyc -f test/funcrparams.sy
|
||||
# -> 1, 0xa, 011, "hellow"
|
||||
```
|
||||
|
||||
## 参考资料
|
||||
|
||||
所有资料均存放于`doc`目录
|
||||
|
||||
[ANTLR手册](doc/The%20Definitive%20ANTLR%204%20Reference.pdf)
|
||||
|
||||
[SysY语言规范](doc/sysy-2022-spec.pdf)
|
||||
|
||||
[SysY运行时库](doc/sysy-2022-runtime.pdf)
|
||||
|
||||
[ARM相关资料](doc/arm/)
|
||||
|
||||
[RISC-V相关资料](doc/riscv/)
|
||||
|
||||
## 实验1:用ANTLR实现SysY词法/语法分析器
|
||||
|
||||
当前的代码框架已经部署好了编译环境,同学们可专注于程序开发。
|
||||
|
||||
在实验1中,同学们需要完成的任务包括
|
||||
|
||||
- 参照SysY语言规范,修改`src/SysY.g4`文件,实现SysY词法/语法的完整定义
|
||||
- (进阶内容)SysY格式化器。修改`src/ASTPrinter.h`与`src/ASTPrinter.cpp`,实现从AST输出源程序,但输出的源程序是经过格式化的,测试用例为`test/format-test.sy`,格式化后的参考结果为`test/format-ref.sy`
|
||||
|
||||
修改代码后只需要执行`cmake --build build`命令重新构建项目,ANTLR工具会从`SysY.g4`生成词法/语法分析器,生成的文件位于`./build/src`目录。
|
||||
|
||||
```bash
|
||||
$ ls build/src/
|
||||
CMakeFiles SysYBaseVisitor.cpp SysY.interp SysYLexer.h SysYLexer.tokens SysYParser.h SysYVisitor.cpp
|
||||
cmake_install.cmake SysYBaseVisitor.h SysYLexer.cpp SysYLexer.interp SysYParser.cpp SysY.tokens SysYVisitor.h
|
||||
```
|
||||
|
||||
完成实验1后,可以通过执行`sysyc`观察生成的IR。
|
||||
|
||||
```bash
|
||||
./build/sysyc -s ast test/funcrparams.sy
|
||||
```
|
||||
|
||||
完成格式化器进阶内容后,可以通过执行`sysyc`观察格式化器的执行效果。
|
||||
|
||||
```bash
|
||||
./build/sysyc -f test/format-test.sy
|
||||
```
|
||||
|
||||
## 实验2:从AST生成中间表示
|
||||
|
||||
代码框架提供的基础设施包括
|
||||
|
||||
- IR相关数据结构的定义:`src/IR.h`
|
||||
- 创建IR对象的工具类`src/IRBuilder.h`
|
||||
- IR生成器的示例代码`src/SysYIRGenerator.h`
|
||||
|
||||
在实验2中,同学们需要完成的任务包括
|
||||
|
||||
- 熟悉掌握IR定义与相关数据结构
|
||||
- 向`src/SysYIRGenerator.h`、`src/SysYIRGenerator.cpp`中增加相关代码,从AST生成IR(基于visitor机制)。
|
||||
|
||||
完成实验2后,可以通过执行`sysyc`观察生成的IR。
|
||||
|
||||
```bash
|
||||
./build/sysyc -s ir 01_add.sy
|
||||
```
|
||||
|
||||
请同学们仔细阅读代码学习IR的定义。可以使用doxygen工具自动生成HTML文档
|
||||
|
||||
```bash
|
||||
sudo apt install doxygen graphviz
|
||||
doxygen doc/Doxyfile
|
||||
```
|
||||
|
||||
上述命令执行完毕后,将在doxygen/html下找到生成的代码文档。
|
||||
|
||||
## 实验3:从SysY IR 生成ARMv7汇编代码
|
||||
|
||||
### 后端相关源码
|
||||
|
||||
当前ref2分支为ARMv7后端代码实验,已经包含了后端代码生成的代码框架,包含
|
||||
|
||||
- 后端生成代码头文件`src/Backend.h`
|
||||
- 后端生成代码源文件`src/Backend.cpp`
|
||||
|
||||
本实验需要基于以上两个源文件添加ARMv7后端生成代码,完成这两个源文件中所有空函数的实现.
|
||||
也可以按照自己的设计重头编写整个后端生成代码,不局限于本实验提供的后端代码框架,自由设计自己的ARMv7后端实现.
|
||||
|
||||
### 后端代码的编译与运行
|
||||
|
||||
在`src/sysyc.cpp`中调用了后端生成的最顶层函数接口`code_gen()`,该函数会逐层调用各层级的代码生成函数并最终生成ARMv7汇编代码并打印至屏幕。
|
||||
|
||||
通过下列命令运行编译产生的sysyc
|
||||
|
||||
```bash
|
||||
./build/sysyc 01_add.sy
|
||||
```
|
||||
|
||||
或者通过下列命令只生成SysY IR代码
|
||||
|
||||
```bash
|
||||
./build/sysyc 01_add.sy ir
|
||||
```
|
||||
|
||||
### 测试
|
||||
|
||||
本实验提供了2个sysy源文件用于调测试,分别是 test/01_add.sy (基础) 和 test/11_add2.sy (带函数调用); 当完成sysyc的编译器后端后,可以通过test下的Makefile文件编译生成测试程序的可
|
||||
执行二进制.
|
||||
|
||||
#### 在x86平台编译运行测试代码
|
||||
|
||||
##### 下载并配置ARMv7交叉编译器工具链
|
||||
|
||||
在[Arm GNU Toolchain](https://developer.arm.com/downloads/-/arm-gnu-toolchain-downloads)下载安装交叉编译工具链,并设置环境变量PATH来使用交叉编译工具链
|
||||
|
||||
```bash
|
||||
export PATH=${your_arm-gnu-toolchain_path}/bin:$PATH;
|
||||
```
|
||||
|
||||
##### 安装qemu模拟器
|
||||
|
||||
```bash
|
||||
sudo apt update
|
||||
sudo apt install qemu-system-arm qemu-user
|
||||
```
|
||||
|
||||
##### 编译测试程序
|
||||
|
||||
使用如下命令调用完成后端实现的sysyc生成ARMv7汇编代码,并调用ARMv7交叉编译工具链汇编并链接生成可执行文件.
|
||||
|
||||
```bash
|
||||
cd test
|
||||
../build/sysyc 01_add.sy > 01_add.s
|
||||
arm-none-linux-gnueabihf-gcc 01_add.s -o 01_add.out -static #注意使用-static选项来静态链接
|
||||
```
|
||||
|
||||
##### 使用qemu-arm模拟运行测试程序
|
||||
|
||||
```bash
|
||||
cd test
|
||||
qemu-arm ./01_add.out
|
||||
echo $? #查看测试程序返回值
|
||||
```
|
||||
|
||||
##### 使用makefile编译与运行
|
||||
|
||||
```bash
|
||||
cd test
|
||||
make all -r #利用sysyc编译两个测试程序
|
||||
make run -r #使用qemu-arm模拟运行两个测试程序
|
||||
```
|
||||
|
||||
#### 在树莓派上编译运行测试代码
|
||||
|
||||
参见'Raspberry.pdf'设置树莓派的编译运行环境,也可以在自己的x86电脑上利用ARMv7交叉编译工具链来编译测试程序, 将编译产生的可执行文件上传到树莓派上运行.
|
||||
|
||||
### 交叉编译器生成汇编代码
|
||||
|
||||
可以通过如下的命令让交叉编译器生成汇编代码,以参考gcc后端的编译行为.
|
||||
|
||||
```bash
|
||||
cd test
|
||||
cp 01_add.sy 01_add.c # 修改代码后缀名
|
||||
arm-none-linux-gnueabihf-gcc 01_add.c -O0 -S -o 01_add.S #O0编译优化
|
||||
```
|
||||
|
||||
请自己构造一些简单的c程序,阅读交叉编译器编译产生的汇编代码来理解ARMv7汇编代码与编译器后端行为.
|
||||
|
||||
### 实验考核
|
||||
|
||||
实验考核使用的sysy程序是 test/10_test.sy,考核时需要展示完整测试过程,包括(1)调用实现了后端代码生成功能的sysyc生成汇编代码,(2)经过汇编链接生成二进制可执行文件,(3)在Qemu或
|
||||
树莓派平台上运行结果正确
|
||||
|
||||
### 参考文档
|
||||
|
||||
参见doc/backend/下的ARMv7相关文档
|
||||
|
||||
## 实验4:标量优化
|
||||
|
||||
### 实验任务
|
||||
|
||||
在前三次实验打通编译器前端-中端-后端基本功能的基础上,在编译中端增加标量优化支持
|
||||
|
||||
- 优化一: 循环优化,在控制流图中找出循环,完成循环不变量外提和强度削弱 (选作)
|
||||
- 优化二:冗余删除,在公用子表达式删除、死代码删除、值编号、常数折叠和常数传播四种冗余优化中,选择完成至少一种优化。
|
||||
- 进阶内容:在中端增加遍管理器支持
|
||||
|
||||
### 实验目标
|
||||
|
||||
通过实验,掌握到达定值分析、活跃变量分析、可用表达式分析等数据流分析方法,能够利用数据流分析和公用子表达式删除、死代码删除、值编号、常数折叠和常数传播等冗余优化算法实现相应的代码优化。
|
||||
|
||||
### 实验方法与主要步骤
|
||||
|
||||
1. 在编译中端增加到达定值分析、活跃变量分析、可用表达式分析等数据流分析遍
|
||||
2. 实现所选循环优化和冗余删除任务种对应的优化算法,实现为对应的优化遍
|
||||
3. 进阶内容:在中端增加遍管理器,管理实现的多个分析遍和优化遍,以更灵活的方式配置编译遍顺序
|
||||
|
||||
### 测试与验证
|
||||
|
||||
测试源程序为test/20_test_licm_sr.sy,test/21_test_cse.sy,test/22_test_dce.sy,test/23_test_vn.sy,test/24_test_cp_cf.sy,经过实验四生成的sysyc编译器能够
|
||||
|
||||
1. 生成经过循环优化或冗余删除优化后的汇编代码,交叉编译后的二进制文件可以在Qemu模拟器/树莓派上正确运行;
|
||||
2. 对比查看优化前和优化后的IR,是否达到了要实现的优化目标。
|
||||
|
||||
## 实验5:寄存器分配
|
||||
|
||||
### 实验任务
|
||||
|
||||
在编译后端增加寄存器分配支持,选择一种分配方法实现寄存器分配
|
||||
|
||||
- 使用计数寄存器分配方法
|
||||
- 进阶内容:图着色寄存器分配方法或线性扫描寄存器分配方法
|
||||
|
||||
### 实验目标
|
||||
|
||||
通过实验理解和掌握编译后端的寄存器分配方法,理解不同寄存器分配方法的优缺点
|
||||
|
||||
### 实验方法与主要步骤
|
||||
|
||||
1. 将ARMv7的R0-R10, R12作为可用寄存器资源
|
||||
2. 遍历所有Function, 在每个Function内部,做寄存器分配
|
||||
3. 维护RegTable符号表,记录哪些LocalValue分配到寄存器,以及具体寄存器编号
|
||||
4. 维护StackTable符号表,记录哪些LocalValue分配到栈上,以及栈上的位置
|
||||
|
||||
### 测试与验证
|
||||
|
||||
测试源程序为test/30_test_reg_alloc.sy,验证经过实验五生成的sysyc编译器,能够生成完成了寄存器分配的的汇编代码,交叉编译后的二进制文件可以在Qemu模拟器/树莓派上正确运行。
|
||||
|
||||
1. 功能验证:能够生成完成了寄存器分配的的汇编代码,交叉编译后的二进制文件可以在Qemu模拟器/树莓派上运行且结果正确;
|
||||
2. 性能验证:经寄存器分配后的代码在树莓派上的运行时间有效缩短。
|
||||
|
||||
|
||||
## 实验6:循环优化
|
||||
|
||||
### 实验任务
|
||||
|
||||
在之前实现编译器的基础上,在编译中端增加循环优化支持。
|
||||
|
||||
+ 任务一
|
||||
针对特定的测试用例,手动应用循环变换技术,如循环展开、循环融合、循环拆分等循环优化手段。对比变换前后的程序性能,例如程序执行时间、资源消耗等指标的测量和评估,分析优化效果。
|
||||
+ 任务二
|
||||
SROA(标量替换),在编译中端增加标量替换的优化遍,能够对循环进行一致性依赖分析,识别循环中存在的可替换内存访问模式,并将其替换为标量变量,以减少内存访问开销并可能揭示更多的优化机会。
|
||||
+ 任务三
|
||||
循环展开,在编译中端增加循环展开的优化遍,增加指令级并行性,减少循环控制开销。同时分析循环展开对程序性能的影响,包括执行速度提升和潜在的代码膨胀问题。
|
||||
+ 进阶内容:在编译中端增加循环分块(Loop Tiling)的优化遍。将循环嵌套划分为更小、更规则的块,以提高数据局部性和缓存利用率。探索循环分块对程序性能的具体影响,以及如何根据目标硬件特性调整分块策略。
|
||||
|
||||
|
||||
### 实验目标
|
||||
|
||||
通过实验,加深学生对编译器中循环优化算法的理解,提升他们在实际编译器开发中应用这些技术的能力。
|
||||
|
||||
### 实验方法与主要步骤
|
||||
|
||||
#### 实验方法
|
||||
|
||||
+ 可以从现有的成熟编译器入手,例如LLVM,分析LLVM中关于循环优化遍的实现。通过LLVM中的工具,对循环变化前后的控制流图进行输出,方便直观感受循环变换对循环结构带来的影响。
|
||||
+ 之后根据课堂上的理论知识,设计所需的循环优化算法,并将其实现为编译器中端的新优化遍。
|
||||
+ 最后,对优化结果进行评估,根据性能分析结果调整优化策略。
|
||||
|
||||
#### 主要步骤
|
||||
|
||||
1. 在编译器中端实现循环分析遍,该遍能够识别程序中的循环结构,并收集循环相关的信息,如循环边界、循环内的变量及其数据依赖关系等。
|
||||
2. 根据实验任务要求,依次实现标量替换优化遍、循环展开优化遍和循环分块优化遍。
|
||||
3. 如果在实验四中实现了遍管理器,将本实验实现的循环优化遍进行管理。
|
||||
4. 将测试程序依次经过三个优化遍处理,对每次优化前后的程序进行基准测试,收集性能数据。分析每种优化方案对程序带来的性能提升,考虑不同优化顺序对性能优化带来的影响。
|
||||
|
||||
### 实验测试
|
||||
|
||||
测试程序为test/40_mm1.sy, test/41_mm2.sy, test/42_mm3.sy。经过实验六生成的sysyc编译器
|
||||
|
||||
1. 能够生成经过标量替换、循环展开或循环分块优化后的汇编代码,交叉编译后的二进制文件可以在Qemu模拟器/树莓派上运行且结果正确
|
||||
2. 对比优化前和优化后的IR,查看是否达到了要实现的优化目标。
|
||||
3. 对程序的性能指标进行分析,如程序执行时间、程序大小、访存次数等,计算优化带来的性能收益,并分析其中的原因。
|
||||
|
||||
|
||||
# 实验7:自动向量化
|
||||
|
||||
### 实验任务
|
||||
|
||||
在已有编译器框架的基础上,实验任务分为三个部分,旨在逐步引导学生掌握向量化技术的应用与开发。
|
||||
+ 任务一:测试现有编译器的向量化支持,通过给定的测试用例,对Clang编译器的自动向量化功能进行测试。熟悉Clang编译器在自动向量化和编译指导向量化方面的使用方法。分析给定循环的向量化可能性,判断循环是否适合向量化,并用Clang编译器进行测试,对比循环向量化前后的中间表示(IR),理解向量化对IR的影响。
|
||||
+ 任务二:从理论出发,设计并实现编译器中端的向量化优化遍。通过循环分析,识别适合向量化的循环,并进行必要的变换以满足向量化条件。
|
||||
+ 任务三:探索NEON指令集扩展在向量化中的应用,并通过Intrinsic函数实现向量化。
|
||||
+ 进阶任务:实现循环的多版本控制,从硬件角度看,由于向量运算的启动开销比变量运算大,所以当向量长度较小时,向量运算速度可能会低于对应的标量运算速度。所以进阶任务是对循环进行版本控制,为循环生成一个标量执行版本和向量执行版本。当迭代次数小时,用标量计算该循环,反之用向量计算。
|
||||
|
||||
### 实验目标
|
||||
|
||||
通过实验,理解向量化的基本概念,包括SIMD架构、自动向量化和编译指导向量化的原理。熟悉Clang编译器的自动向量化功能,理解编译指导向量化的使用方法。最终设计并实现编译器中端的向量化优化遍,通过循环分析识别并转换适合向量化的循环。
|
||||
|
||||
### 实验方法与主要步骤
|
||||
|
||||
#### 实验方法
|
||||
|
||||
可以先从简单的向量化场景出发,针对特定的指令进行向量化操作,然后在此基础上进行补充,考虑更全面的向量化场景。
|
||||
例如,可以先对循环中的以下两种指令进行循环向量化:
|
||||
1. 循环体中的```dst[i] = c``` (c是常数, i是迭代变量)
|
||||
2. 循环体中的```dst[i]=src[i]```
|
||||
|
||||
在确定要并行化的循环形式之后,对原始循环按照如下流程实现向量化:
|
||||
1. 检查循环体中的指令,确保符合向量化的基本条件。
|
||||
例如,循环迭代步为1,迭代变量递增,比较指令为小于等。
|
||||
2. 识别循环体中可以向量化的语句: ```dst[i] = c``` 或 ```dst[i]=src[i]```
|
||||
3. 更新循环的迭代步: ```i=i+1``` => ```i=i+4```
|
||||
4. 尾循环处理。
|
||||
上述就是针对简单场景进行循环向量化的实现流程,进而可以扩展到更复杂的应用场景中。
|
||||
|
||||
#### 主要步骤
|
||||
1. 实现循环向量化所需要的分析遍,例如数据依赖分析。同时,为了对不能进行向量化的循环进行转化以实现向量化,还需要实现基本的循环优化遍,例如循环分裂、循环剥除等。
|
||||
2. 编码实现循环向量化优化遍,将设计的算法集成到编译器中端。
|
||||
3. 如果在实验四中实现了遍管理器,将本实验实现的循环向量化优化遍进行管理。
|
||||
4. 分析性能数据,评估向量化对性能的具体影响,并根据测试结果调整优化策略。
|
||||
|
||||
### 实验测试
|
||||
测试程序包括test/40_mm1.sy, test/41_mm2.sy, test/42_mm3.sy。通过本实验七生成的 sysyc 编译器需要满足以下要求:
|
||||
|
||||
1. 能够生成经过循环向量化优化后的汇编代码,交叉编译后的二进制文件可以在Qemu模拟器/树莓派上运行且结果正确。
|
||||
2. 对比优化前和优化后的IR,查看是否达到了要实现的优化目标。分析 IR 的变化,理解向量化对代码结构的影响。
|
||||
3. 对程序的性能指标进行分析,如程序执行时间、程序大小、访存次数等,计算优化带来的性能收益,并分析其中的原因。
|
||||
|
||||
|
||||
|
||||
# 实验8:自动并行化
|
||||
|
||||
### 实验任务
|
||||
|
||||
在已有编译器框架的基础上,实现多线程并行技术。
|
||||
+ 任务一:对给定的测试程序进行手工并行化,使用OpenMP的编译指导命令来指导编译器生成并行代码。对比并行化前后的性能,包括但不限于执行时间、资源消耗等,分析并行化带来的性能提升原因。
|
||||
+ 任务二:在编译器中端开发一个并行化优化遍,自动将给定的矩阵相乘的串行程序进行并行化处理,以提高计算效率。对于不满足并行化的循环程序,能够进行适当的循环变换,暴露循环中的并行特征。
|
||||
+ 任务三:通过交叉编译,将并行化后的程序部署到开发板上,检查程序输出的正确性,确保并行化没有改变程序的逻辑结果。记录并行化前后的程序性能数据,如执行时间、内存使用情况等,并计算加速比。
|
||||
+ 进阶任务:选择一个复杂算法(如快速傅里叶变换、LU分解等),分析其并行化潜力。在编译器中实现对该算法的并行化优化遍,对比并行化前后的性能数据,分析并行化在不同算法中的应用效果。
|
||||
|
||||
|
||||
### 实验目标
|
||||
|
||||
深入理解并行化的判定条件,能够对不满足并行化的循环进行简单的循环变换从而实现并行化,实现基本的并行化优化遍。通过矩阵乘法等计算密集型程序的优化,实际演示并行化技术对提升程序性能的效果,并与现有的成熟自动并行化编译器进行效果比较,从而分析并行化性能提升的原因。
|
||||
|
||||
### 实验方法与主要步骤
|
||||
|
||||
#### 实验方法
|
||||
|
||||
+ 以矩阵乘测试程序为例,首先需要对程序中的循环进行依赖性检查,识别出其中不存在跨迭代依赖的循环。对于不满足并行化条件的循环进行必要的循环优化,暴露出其中的并行化机会。
|
||||
|
||||
+ 识别出可并行化的循环后,需要对线程任务进行划分。
|
||||
|
||||
+ 由于线程创建、销毁和同步等操作具有性能损耗,以矩阵乘为例,在并行化时要使线程处理的任务粒度足够大,尽可能并行化最外层循环。
|
||||
|
||||
+ 计算新的循环结构,确定每个线程要处理循环的上下界。
|
||||
最后修改循环结构,并在循环前后分别插入线程创建(```_thread_create```)和线程等待(```_thread_join```)函数。
|
||||
|
||||
#### 主要步骤
|
||||
|
||||
1. 实现循环并行所需要的分析遍,例如数据依赖分析。同时,为了对不能进行并行化的循环进行转化以实现并行化,还需要实现基本的循环优化遍,例如循环分裂、循环剥除等。
|
||||
2. 实现循环并行化对应的优化算法,实现对应的循环并行化优化遍
|
||||
3. 如果在实验四中实现了遍管理器,将本实验实现的循环并行化优化遍进行管理。
|
||||
4. 在开发板上运行并行化后的程序,验证其输出的正确性。并收集并行化前后的性能数据,计算并行化前后的加速比,量化并行化带来的性能提升。
|
||||
|
||||
### 实验测试
|
||||
|
||||
测试程序包括 test/40_mm1.sy, test/41_mm2.sy, test/42_mm3.sy。通过本实验八生成的 sysyc 编译器需要满足以下要求:
|
||||
|
||||
1. 能够生成经过循环并行化优化后的汇编代码,交叉编译后的二进制文件可以在Qemu模拟器/树莓派上运行且结果正确。
|
||||
2. 对比优化前和优化后的IR,查看是否达到了要实现的优化目标。
|
||||
3. 记录并行化前后的程序性能数据,包括但不限于执行时间、内存使用、处理器负载等,计算加速比,评估并行化对程序性能的提升效果。
|
||||
|
||||
|
||||
## 致谢
|
||||
|
||||
[全国大学生计算机系统能力大赛](https://compiler.educg.net): 本实验使用全国大学生计算机系统能力大赛-编译系统实现赛SysY语言规范,测试用例部分参考大赛设计。
|
||||
|
||||
BIN
antlr/antlr-4.13.2-complete.jar
Normal file
BIN
antlr/antlr-4.13.2-complete.jar
Normal file
Binary file not shown.
216
antlr/antlr4-runtime-4.12.0/CMakeLists.txt
Normal file
216
antlr/antlr4-runtime-4.12.0/CMakeLists.txt
Normal file
@ -0,0 +1,216 @@
|
||||
# -*- mode:cmake -*-
|
||||
cmake_minimum_required (VERSION 3.15)
|
||||
# 3.14 needed because of FetchContent
|
||||
# 3.15 needed to avid spew of warnings related to overriding cl command line flags
|
||||
|
||||
set(CMAKE_MACOSX_RPATH OFF)
|
||||
|
||||
enable_testing()
|
||||
|
||||
# Detect build type, fallback to release and throw a warning if use didn't specify any
|
||||
if(NOT CMAKE_BUILD_TYPE)
|
||||
message(WARNING "Build type not set, falling back to Release mode.
|
||||
To specify build type use:
|
||||
-DCMAKE_BUILD_TYPE=<mode> where <mode> is Debug or Release.")
|
||||
set(CMAKE_BUILD_TYPE "Release" CACHE STRING
|
||||
"Choose the type of build, options are: Debug Release."
|
||||
FORCE)
|
||||
endif(NOT CMAKE_BUILD_TYPE)
|
||||
|
||||
if(NOT WITH_DEMO)
|
||||
message(STATUS "Building without demo. To enable demo build use: -DWITH_DEMO=True")
|
||||
set(WITH_DEMO False CACHE STRING
|
||||
"Chose to build with or without demo executable"
|
||||
FORCE)
|
||||
endif(NOT WITH_DEMO)
|
||||
|
||||
option(WITH_LIBCXX "Building with clang++ and libc++(in Linux). To enable with: -DWITH_LIBCXX=On" Off)
|
||||
option(WITH_STATIC_CRT "(Visual C++) Enable to statically link CRT, which avoids requiring users to install the redistribution package.
|
||||
To disable with: -DWITH_STATIC_CRT=Off" On)
|
||||
option(DISABLE_WARNINGS "Suppress compiler warnings for all built ANTLR targets" OFF)
|
||||
|
||||
cmake_policy(SET CMP0091 NEW) # Enable use of CMAKE_MSVC_RUNTIME_LIBRARY
|
||||
if(WITH_STATIC_CRT)
|
||||
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
|
||||
else()
|
||||
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>DLL")
|
||||
endif(WITH_STATIC_CRT)
|
||||
|
||||
project(LIBANTLR4)
|
||||
|
||||
if(APPLE)
|
||||
find_library(COREFOUNDATION_LIBRARY CoreFoundation)
|
||||
endif()
|
||||
|
||||
file(STRINGS "VERSION" ANTLR_VERSION)
|
||||
|
||||
if(WITH_DEMO)
|
||||
# Java is not necessary if building without demos.
|
||||
find_package(Java COMPONENTS Runtime REQUIRED)
|
||||
|
||||
if(NOT ANTLR_JAR_LOCATION)
|
||||
message(FATAL_ERROR "Missing antlr4.jar location. You can specify it's path using: -DANTLR_JAR_LOCATION=<path>")
|
||||
else()
|
||||
get_filename_component(ANTLR_NAME ${ANTLR_JAR_LOCATION} NAME_WE)
|
||||
if(NOT EXISTS "${ANTLR_JAR_LOCATION}")
|
||||
message(FATAL_ERROR "Unable to find ${ANTLR_NAME} in ${ANTLR_JAR_LOCATION}")
|
||||
else()
|
||||
message(STATUS "Found ${ANTLR_NAME}: ${ANTLR_JAR_LOCATION}")
|
||||
endif()
|
||||
endif()
|
||||
endif(WITH_DEMO)
|
||||
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
|
||||
set(MY_CXX_WARNING_FLAGS " /W4")
|
||||
|
||||
if(DISABLE_WARNINGS)
|
||||
set(MY_CXX_WARNING_FLAGS " /w")
|
||||
endif()
|
||||
else()
|
||||
set(MY_CXX_WARNING_FLAGS " -Wall -pedantic -W")
|
||||
|
||||
if(DISABLE_WARNINGS)
|
||||
set(MY_CXX_WARNING_FLAGS " -w")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Define USE_UTF8_INSTEAD_OF_CODECVT macro.
|
||||
# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DUSE_UTF8_INSTEAD_OF_CODECVT")
|
||||
|
||||
# Initialize CXXFLAGS.
|
||||
if(NOT DEFINED CMAKE_CXX_STANDARD)
|
||||
# only set CMAKE_CXX_STANDARD if not already set
|
||||
# this allows the standard to be set by the caller, for example with -DCMAKE_CXX_STANDARD:STRING=17
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
endif()
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${MY_CXX_WARNING_FLAGS}")
|
||||
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /Od /Zi /MP ${MY_CXX_WARNING_FLAGS}")
|
||||
set(CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL} /O1 /Oi /Ob2 /Gy /MP /DNDEBUG ${MY_CXX_WARNING_FLAGS}")
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /O2 /Oi /Ob2 /Gy /MP /DNDEBUG ${MY_CXX_WARNING_FLGAS}")
|
||||
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} /O2 /Oi /Ob2 /Gy /MP /Zi ${MY_CXX_WARNING_FLAGS}")
|
||||
else()
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g ${MY_CXX_WARNING_FLAGS}")
|
||||
set(CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS_MINSIZEREL} -Os -DNDEBUG ${MY_CXX_WARNING_FLAGS}")
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -O3 -DNDEBUG ${MY_CXX_WARNING_FLGAS}")
|
||||
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -O2 -g ${MY_CXX_WARNING_FLAGS}")
|
||||
endif()
|
||||
|
||||
# Compiler-specific C++17 activation.
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES "Intel")
|
||||
execute_process(
|
||||
COMMAND ${CMAKE_CXX_COMPILER} -dumpversion OUTPUT_VARIABLE GCC_VERSION)
|
||||
# Just g++-5.0 and greater contain <codecvt> header. (test in ubuntu)
|
||||
if(NOT (GCC_VERSION VERSION_GREATER 5.0 OR GCC_VERSION VERSION_EQUAL 5.0))
|
||||
message(FATAL_ERROR "${PROJECT_NAME} requires g++ 5.0 or greater.")
|
||||
endif ()
|
||||
elseif (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND ANDROID)
|
||||
# Need -Os cflag and cxxflags here to work with exception handling on armeabi.
|
||||
# see https://github.com/android-ndk/ndk/issues/573
|
||||
# and without -stdlib=libc++ cxxflags
|
||||
elseif (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND APPLE)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -stdlib=libc++")
|
||||
elseif (CMAKE_CXX_COMPILER_ID MATCHES "Clang" AND ( CMAKE_SYSTEM_NAME MATCHES "Linux" OR CMAKE_SYSTEM_NAME MATCHES "FreeBSD") )
|
||||
execute_process(
|
||||
COMMAND ${CMAKE_CXX_COMPILER} -dumpversion OUTPUT_VARIABLE CLANG_VERSION)
|
||||
if(NOT (CLANG_VERSION VERSION_GREATER 4.2.1 OR CLANG_VERSION VERSION_EQUAL 4.2.1))
|
||||
message(FATAL_ERROR "${PROJECT_NAME} requires clang 4.2.1 or greater.")
|
||||
endif()
|
||||
# You can use libc++ to compile this project when g++ is NOT greater than or equal to 5.0.
|
||||
if(WITH_LIBCXX)
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++")
|
||||
endif()
|
||||
elseif(MSVC_VERSION GREATER 1800 OR MSVC_VERSION EQUAL 1800)
|
||||
# Visual Studio 2012+ supports C++17 features
|
||||
elseif(CMAKE_SYSTEM_NAME MATCHES "Emscripten")
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -stdlib=libc++")
|
||||
else()
|
||||
message(FATAL_ERROR "Your C++ compiler does not support C++17.")
|
||||
endif()
|
||||
|
||||
|
||||
add_subdirectory(runtime)
|
||||
if(WITH_DEMO)
|
||||
add_subdirectory(demo)
|
||||
endif(WITH_DEMO)
|
||||
|
||||
# Generate CMake Package Files only if install is active
|
||||
if (ANTLR4_INSTALL)
|
||||
|
||||
include(GNUInstallDirs)
|
||||
include(CMakePackageConfigHelpers)
|
||||
|
||||
if(NOT ANTLR4_CMAKE_DIR)
|
||||
set(ANTLR4_CMAKE_DIR ${CMAKE_INSTALL_LIBDIR}/cmake CACHE STRING
|
||||
"Installation directory for cmake files." FORCE )
|
||||
endif(NOT ANTLR4_CMAKE_DIR)
|
||||
|
||||
set(version_runtime_config ${PROJECT_BINARY_DIR}/antlr4-runtime-config-version.cmake)
|
||||
set(version_generator_config ${PROJECT_BINARY_DIR}/antlr4-generator-config-version.cmake)
|
||||
set(project_runtime_config ${PROJECT_BINARY_DIR}/antlr4-runtime-config.cmake)
|
||||
set(project_generator_config ${PROJECT_BINARY_DIR}/antlr4-generator-config.cmake)
|
||||
set(targets_export_name antlr4-targets)
|
||||
|
||||
set(ANTLR4_LIB_DIR ${CMAKE_INSTALL_LIBDIR} CACHE STRING
|
||||
"Installation directory for libraries, relative to ${CMAKE_INSTALL_PREFIX}.")
|
||||
|
||||
set(ANTLR4_INCLUDE_DIR ${CMAKE_INSTALL_INCLUDEDIR}/antlr4-runtime CACHE STRING
|
||||
"Installation directory for include files, relative to ${CMAKE_INSTALL_PREFIX}.")
|
||||
|
||||
configure_package_config_file(
|
||||
cmake/antlr4-runtime.cmake.in
|
||||
${project_runtime_config}
|
||||
INSTALL_DESTINATION ${ANTLR4_CMAKE_DIR}/antlr4-runtime
|
||||
PATH_VARS
|
||||
ANTLR4_INCLUDE_DIR
|
||||
ANTLR4_LIB_DIR )
|
||||
|
||||
configure_package_config_file(
|
||||
cmake/antlr4-generator.cmake.in
|
||||
${project_generator_config}
|
||||
INSTALL_DESTINATION ${ANTLR4_CMAKE_DIR}/antlr4-generator
|
||||
PATH_VARS
|
||||
ANTLR4_INCLUDE_DIR
|
||||
ANTLR4_LIB_DIR )
|
||||
|
||||
write_basic_package_version_file(
|
||||
${version_runtime_config}
|
||||
VERSION ${ANTLR_VERSION}
|
||||
COMPATIBILITY SameMajorVersion )
|
||||
|
||||
write_basic_package_version_file(
|
||||
${version_generator_config}
|
||||
VERSION ${ANTLR_VERSION}
|
||||
COMPATIBILITY SameMajorVersion )
|
||||
|
||||
install(EXPORT ${targets_export_name}
|
||||
DESTINATION ${ANTLR4_CMAKE_DIR}/antlr4-runtime )
|
||||
|
||||
install(FILES ${project_runtime_config}
|
||||
${version_runtime_config}
|
||||
DESTINATION ${ANTLR4_CMAKE_DIR}/antlr4-runtime )
|
||||
|
||||
install(FILES ${project_generator_config}
|
||||
${version_generator_config}
|
||||
DESTINATION ${ANTLR4_CMAKE_DIR}/antlr4-generator )
|
||||
|
||||
endif(ANTLR4_INSTALL)
|
||||
|
||||
if(EXISTS LICENSE.txt)
|
||||
install(FILES LICENSE.txt
|
||||
DESTINATION "share/doc/libantlr4")
|
||||
elseif(EXISTS ../../LICENSE.txt)
|
||||
install(FILES ../../LICENSE.txt
|
||||
DESTINATION "share/doc/libantlr4")
|
||||
endif()
|
||||
|
||||
install(FILES README.md VERSION
|
||||
DESTINATION "share/doc/libantlr4")
|
||||
|
||||
set(CPACK_PACKAGE_CONTACT "antlr-discussion@googlegroups.com")
|
||||
set(CPACK_PACKAGE_VERSION ${ANTLR_VERSION})
|
||||
include(CPack)
|
||||
28
antlr/antlr4-runtime-4.12.0/LICENSE.txt
Normal file
28
antlr/antlr4-runtime-4.12.0/LICENSE.txt
Normal file
@ -0,0 +1,28 @@
|
||||
Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither name of copyright holders nor the names of its contributors
|
||||
may be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
|
||||
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
72
antlr/antlr4-runtime-4.12.0/README.md
Normal file
72
antlr/antlr4-runtime-4.12.0/README.md
Normal file
@ -0,0 +1,72 @@
|
||||
# C++ target for ANTLR 4
|
||||
|
||||
This folder contains the C++ runtime support for ANTLR. See [the canonical antlr4 repository](https://github.com/antlr/antlr4) for in depth detail about how to use ANTLR 4.
|
||||
|
||||
## Authors and major contributors
|
||||
|
||||
ANTLR 4 is the result of substantial effort of the following people:
|
||||
|
||||
* [Terence Parr](http://www.cs.usfca.edu/~parrt/), parrt@cs.usfca.edu
|
||||
ANTLR project lead and supreme dictator for life
|
||||
[University of San Francisco](http://www.usfca.edu/)
|
||||
* [Sam Harwell](http://tunnelvisionlabs.com/)
|
||||
Tool co-author, Java and C# target)
|
||||
|
||||
The C++ target has been the work of the following people:
|
||||
|
||||
* Dan McLaughlin, dan.mclaughlin@gmail.com (initial port, got code to compile)
|
||||
* David Sisson, dsisson@google.com (initial port, made the runtime C++ tests runnable)
|
||||
* [Mike Lischke](http://www.soft-gems.net), mike@lischke-online.de (brought the initial port to a working library, made most runtime tests passing)
|
||||
|
||||
## Other contributors
|
||||
|
||||
* Marcin Szalowicz, mszalowicz@mailplus.pl (cmake build setup)
|
||||
* Tim O'Callaghan, timo@linux.com (additional superbuild cmake pattern script)
|
||||
|
||||
## Project Status
|
||||
|
||||
* Building on macOS, Windows, Android and Linux
|
||||
* No errors and warnings
|
||||
* Library linking
|
||||
* Some unit tests in the macOS project, for important base classes with almost 100% code coverage.
|
||||
* All memory allocations checked
|
||||
* Simple command line demo application working on all supported platforms.
|
||||
* All runtime tests pass.
|
||||
|
||||
### Build + Usage Notes
|
||||
|
||||
The minimum C++ version to compile the ANTLR C++ runtime with is C++17. The supplied projects can built the runtime either as static or dynamic library, as both 32bit and 64bit arch. The macOS project contains a target for iOS and can also be built using cmake (instead of XCode).
|
||||
|
||||
Include the antlr4-runtime.h umbrella header in your target application to get everything needed to use the library.
|
||||
|
||||
If you are compiling with cmake, the minimum version required is cmake 2.8.
|
||||
By default, the libraries produced by the CMake build target C++17. If you want to target a different C++ standard, you can explicitly pass the standard - e.g. `-DCMAKE_CXX_STANDARD=17`.
|
||||
|
||||
#### Compiling on Windows with Visual Studio using he Visual Studio projects
|
||||
Simply open the VS project from the runtime folder (VS 2019+) and build it.
|
||||
|
||||
#### Compiling on Windows using cmake with Visual Studio VS2019 and later
|
||||
Use the "Open Folder" Feature from the File->Open->Folder menu to open the runtime/Cpp directory.
|
||||
It will automatically use the CMake description to open up a Visual Studio Solution.
|
||||
|
||||
#### Compiling on macOS
|
||||
Either open the included XCode project and build that or use the cmake compilation as described for linux.
|
||||
|
||||
#### Compiling on Android
|
||||
Try run cmake -DCMAKE_ANDROID_NDK=/folder/of/android_ndkr17_and_above -DCMAKE_SYSTEM_NAME=Android -DCMAKE_ANDROID_API=14 -DCMAKE_ANDROID_ARCH_ABI=x86 -DCMAKE_ANDROID_STL_TYPE=c++_shared -DCMAKE_ANDROID_NDK_TOOLCHAIN_VERSION=clang -DCMAKE_BUILD_TYPE=Release /folder/antlr4_src_dir -G Ninja.
|
||||
|
||||
#### Compiling on Linux
|
||||
- cd \<antlr4-dir\>/runtime/Cpp (this is where this readme is located)
|
||||
- mkdir build && mkdir run && cd build
|
||||
- cmake .. -DANTLR_JAR_LOCATION=full/path/to/antlr4-4.5.4-SNAPSHOT.jar -DWITH_DEMO=True
|
||||
- make
|
||||
- DESTDIR=\<antlr4-dir\>/runtime/Cpp/run make install
|
||||
|
||||
If you don't want to build the demo then replace the "cmake .. -DANTLR_JAR_LOCATION<...>" command in the above recipe with "cmake .." without any further parameters.
|
||||
There is another cmake script available in the subfolder cmake/ for those who prefer the superbuild cmake pattern.
|
||||
|
||||
#### CMake Package support
|
||||
If the CMake variable 'ANTLR4_INSTALL' is set, CMake Packages will be build and installed during the install step.
|
||||
They expose two packages: antlr4_runtime and antlr4_generator which can be referenced to ease up the use of the
|
||||
ANTLR Generator and runtime.
|
||||
Use and Sample can be found [here](cmake/Antlr4Package.md)
|
||||
1
antlr/antlr4-runtime-4.12.0/VERSION
Normal file
1
antlr/antlr4-runtime-4.12.0/VERSION
Normal file
@ -0,0 +1 @@
|
||||
4.12.0
|
||||
136
antlr/antlr4-runtime-4.12.0/cmake/Antlr4Package.md
Normal file
136
antlr/antlr4-runtime-4.12.0/cmake/Antlr4Package.md
Normal file
@ -0,0 +1,136 @@
|
||||
# CMake Antlr4 Package Usage
|
||||
|
||||
## The `antlr4-generator` Package
|
||||
|
||||
To use the Package you must insert a
|
||||
```cmake
|
||||
find_package(antlr4-generator REQUIRED)
|
||||
```
|
||||
line in your `CMakeList.txt` file.
|
||||
|
||||
The package exposes a function `antlr4_generate` that generates the required setup to call ANTLR for a
|
||||
given input file during build.
|
||||
|
||||
The following table lists the parameters that can be used with the function:
|
||||
|
||||
Argument# | Required | Default | Use
|
||||
----------|-----------|---------|---
|
||||
0 | Yes | n/a | Unique target name. It is used to generate CMake Variables to reference the various outputs of the generation
|
||||
1 | Yes | n/a | Input file containing the lexer/parser definition
|
||||
2 | Yes | n/a | Type of Rules contained in the input: LEXER, PARSER or BOTH
|
||||
4 | No | FALSE | Boolean to indicate if a listener interface should be generated
|
||||
5 | No | FALSE | Boolean to indicate if a visitor interface should be generated
|
||||
6 | No | none | C++ namespace in which the generated classes should be placed
|
||||
7 | No | none | Additional files on which the input depends
|
||||
8 | No | none | Library path to use during generation
|
||||
|
||||
The `ANTLR4_JAR_LOCATION` CMake variable must be set to the location where the `antlr-4*-complete.jar` generator is located. You can download the file from [here](http://www.antlr.org/download.html).
|
||||
|
||||
Additional options to the ANTLR4 generator can be passed in the `ANTLR4_GENERATED_OPTIONS` variable. Add the installation prefix of `antlr4-runtime` to `CMAKE_PREFIX_PATH` or set
|
||||
`antlr4-runtime_DIR` to a directory containing the files.
|
||||
|
||||
The following CMake variables are available following a call to `antlr4_generate`
|
||||
|
||||
Output variable | Meaning
|
||||
---|---
|
||||
`ANTLR4_INCLUDE_DIR_<Target name>` | Directory containing the generated header files
|
||||
`ANTLR4_SRC_FILES_<Target name>` | List of generated source files
|
||||
`ANTLR4_TOKEN_FILES_<Target name>` | List of generated token files
|
||||
`ANTLR4_TOKEN_DIRECTORY_<Target name>` | Directory containing the generated token files
|
||||
|
||||
#### Sample:
|
||||
```cmake
|
||||
# generate parser with visitor classes.
|
||||
# put the classes in C++ namespace 'antlrcpptest::'
|
||||
antlr4_generate(
|
||||
antlrcpptest_parser
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/TLexer.g4
|
||||
LEXER
|
||||
FALSE
|
||||
TRUE
|
||||
"antlrcpptest"
|
||||
)
|
||||
```
|
||||
|
||||
**Remember that the ANTLR generator requires a working Java installation on your machine!**
|
||||
|
||||
## The `antlr4-runtime` Package
|
||||
|
||||
To use the Package you must insert a
|
||||
```cmake
|
||||
find_package(antlr4-runtime REQUIRED)
|
||||
```
|
||||
line in your `CMakeList.txt` file.
|
||||
|
||||
The package exposes two different targets:
|
||||
|
||||
Target|Use
|
||||
--|--
|
||||
antlr4_shared|Shared library version of the runtime
|
||||
antlr4_static|Static library version of the runtime
|
||||
|
||||
Both set the following CMake variables:
|
||||
|
||||
Output variable | Meaning
|
||||
---|---
|
||||
`ANTLR4_INCLUDE_DIR` | Include directory containing the runtime header files
|
||||
`ANTLR4_LIB_DIR` | Library directory containing the runtime library files
|
||||
|
||||
#### Sample:
|
||||
```cmake
|
||||
# add runtime include directories on this project.
|
||||
include_directories( ${ANTLR4_INCLUDE_DIR} )
|
||||
|
||||
# add runtime to project dependencies
|
||||
add_dependencies( Parsertest antlr4_shared )
|
||||
|
||||
# add runtime to project link libraries
|
||||
target_link_libraries( Parsertest PRIVATE
|
||||
antlr4_shared)
|
||||
```
|
||||
|
||||
### Full Example:
|
||||
```cmake
|
||||
# Bring in the required packages
|
||||
find_package(antlr4-runtime REQUIRED)
|
||||
find_package(antlr4-generator REQUIRED)
|
||||
|
||||
# Set path to generator
|
||||
set(ANTLR4_JAR_LOCATION ${PROJECT_SOURCE_DIR}/thirdparty/antlr/antlr-4.12.0-complete.jar)
|
||||
|
||||
# generate lexer
|
||||
antlr4_generate(
|
||||
antlrcpptest_lexer
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/TLexer.g4
|
||||
LEXER
|
||||
FALSE
|
||||
FALSE
|
||||
"antlrcpptest"
|
||||
)
|
||||
|
||||
# generate parser
|
||||
antlr4_generate(
|
||||
antlrcpptest_parser
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/TParser.g4
|
||||
PARSER
|
||||
FALSE
|
||||
TRUE
|
||||
"antlrcpptest"
|
||||
"${ANTLR4_TOKEN_FILES_antlrcpptest_lexer}"
|
||||
"${ANTLR4_TOKEN_DIRECTORY_antlrcpptest_lexer}"
|
||||
)
|
||||
|
||||
# add directories for generated include files
|
||||
include_directories( ${PROJECT_BINARY_DIR} ${ANTLR4_INCLUDE_DIR} ${ANTLR4_INCLUDE_DIR_antlrcpptest_lexer} ${ANTLR4_INCLUDE_DIR_antlrcpptest_parser} )
|
||||
|
||||
# add generated source files
|
||||
add_executable( Parsertest main.cpp ${ANTLR4_SRC_FILES_antlrcpptest_lexer} ${ANTLR4_SRC_FILES_antlrcpptest_parser} )
|
||||
|
||||
# add required runtime library
|
||||
add_dependencies( Parsertest antlr4_shared )
|
||||
|
||||
target_link_libraries( Parsertest PRIVATE
|
||||
antlr4_shared)
|
||||
|
||||
```
|
||||
|
||||
177
antlr/antlr4-runtime-4.12.0/cmake/ExternalAntlr4Cpp.cmake
Normal file
177
antlr/antlr4-runtime-4.12.0/cmake/ExternalAntlr4Cpp.cmake
Normal file
@ -0,0 +1,177 @@
|
||||
cmake_minimum_required(VERSION 3.7)
|
||||
|
||||
if(POLICY CMP0114)
|
||||
cmake_policy(SET CMP0114 NEW)
|
||||
endif()
|
||||
|
||||
include(ExternalProject)
|
||||
|
||||
set(ANTLR4_ROOT ${CMAKE_CURRENT_BINARY_DIR}/antlr4_runtime/src/antlr4_runtime)
|
||||
set(ANTLR4_INCLUDE_DIRS ${ANTLR4_ROOT}/runtime/Cpp/runtime/src)
|
||||
set(ANTLR4_GIT_REPOSITORY https://github.com/antlr/antlr4.git)
|
||||
if(NOT DEFINED ANTLR4_TAG)
|
||||
# Set to branch name to keep library updated at the cost of needing to rebuild after 'clean'
|
||||
# Set to commit hash to keep the build stable and does not need to rebuild after 'clean'
|
||||
set(ANTLR4_TAG master)
|
||||
endif()
|
||||
|
||||
# Ensure that the include dir already exists at configure time (to avoid cmake erroring
|
||||
# on non-existent include dirs)
|
||||
file(MAKE_DIRECTORY "${ANTLR4_INCLUDE_DIRS}")
|
||||
|
||||
if(${CMAKE_GENERATOR} MATCHES "Visual Studio.*")
|
||||
set(ANTLR4_OUTPUT_DIR ${ANTLR4_ROOT}/runtime/Cpp/dist/$(Configuration))
|
||||
elseif(${CMAKE_GENERATOR} MATCHES "Xcode.*")
|
||||
set(ANTLR4_OUTPUT_DIR ${ANTLR4_ROOT}/runtime/Cpp/dist/$(CONFIGURATION))
|
||||
else()
|
||||
set(ANTLR4_OUTPUT_DIR ${ANTLR4_ROOT}/runtime/Cpp/dist)
|
||||
endif()
|
||||
|
||||
if(MSVC)
|
||||
set(ANTLR4_STATIC_LIBRARIES
|
||||
${ANTLR4_OUTPUT_DIR}/antlr4-runtime-static.lib)
|
||||
set(ANTLR4_SHARED_LIBRARIES
|
||||
${ANTLR4_OUTPUT_DIR}/antlr4-runtime.lib)
|
||||
set(ANTLR4_RUNTIME_LIBRARIES
|
||||
${ANTLR4_OUTPUT_DIR}/antlr4-runtime.dll)
|
||||
else()
|
||||
set(ANTLR4_STATIC_LIBRARIES
|
||||
${ANTLR4_OUTPUT_DIR}/libantlr4-runtime.a)
|
||||
if(MINGW)
|
||||
set(ANTLR4_SHARED_LIBRARIES
|
||||
${ANTLR4_OUTPUT_DIR}/libantlr4-runtime.dll.a)
|
||||
set(ANTLR4_RUNTIME_LIBRARIES
|
||||
${ANTLR4_OUTPUT_DIR}/libantlr4-runtime.dll)
|
||||
elseif(CYGWIN)
|
||||
set(ANTLR4_SHARED_LIBRARIES
|
||||
${ANTLR4_OUTPUT_DIR}/libantlr4-runtime.dll.a)
|
||||
set(ANTLR4_RUNTIME_LIBRARIES
|
||||
${ANTLR4_OUTPUT_DIR}/cygantlr4-runtime-4.12.0.dll)
|
||||
elseif(APPLE)
|
||||
set(ANTLR4_RUNTIME_LIBRARIES
|
||||
${ANTLR4_OUTPUT_DIR}/libantlr4-runtime.dylib)
|
||||
else()
|
||||
set(ANTLR4_RUNTIME_LIBRARIES
|
||||
${ANTLR4_OUTPUT_DIR}/libantlr4-runtime.so)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(${CMAKE_GENERATOR} MATCHES ".* Makefiles")
|
||||
# This avoids
|
||||
# 'warning: jobserver unavailable: using -j1. Add '+' to parent make rule.'
|
||||
set(ANTLR4_BUILD_COMMAND $(MAKE))
|
||||
elseif(${CMAKE_GENERATOR} MATCHES "Visual Studio.*")
|
||||
set(ANTLR4_BUILD_COMMAND
|
||||
${CMAKE_COMMAND}
|
||||
--build .
|
||||
--config $(Configuration)
|
||||
--target)
|
||||
elseif(${CMAKE_GENERATOR} MATCHES "Xcode.*")
|
||||
set(ANTLR4_BUILD_COMMAND
|
||||
${CMAKE_COMMAND}
|
||||
--build .
|
||||
--config $(CONFIGURATION)
|
||||
--target)
|
||||
else()
|
||||
set(ANTLR4_BUILD_COMMAND
|
||||
${CMAKE_COMMAND}
|
||||
--build .
|
||||
--target)
|
||||
endif()
|
||||
|
||||
if(NOT DEFINED ANTLR4_WITH_STATIC_CRT)
|
||||
set(ANTLR4_WITH_STATIC_CRT ON)
|
||||
endif()
|
||||
|
||||
if(ANTLR4_ZIP_REPOSITORY)
|
||||
ExternalProject_Add(
|
||||
antlr4_runtime
|
||||
PREFIX antlr4_runtime
|
||||
URL ${ANTLR4_ZIP_REPOSITORY}
|
||||
DOWNLOAD_DIR ${CMAKE_CURRENT_BINARY_DIR}
|
||||
BUILD_COMMAND ""
|
||||
BUILD_IN_SOURCE 1
|
||||
SOURCE_DIR ${ANTLR4_ROOT}
|
||||
SOURCE_SUBDIR runtime/Cpp
|
||||
CMAKE_CACHE_ARGS
|
||||
-DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE}
|
||||
-DWITH_STATIC_CRT:BOOL=${ANTLR4_WITH_STATIC_CRT}
|
||||
-DDISABLE_WARNINGS:BOOL=ON
|
||||
# -DCMAKE_CXX_STANDARD:STRING=17 # if desired, compile the runtime with a different C++ standard
|
||||
# -DCMAKE_CXX_STANDARD:STRING=${CMAKE_CXX_STANDARD} # alternatively, compile the runtime with the same C++ standard as the outer project
|
||||
INSTALL_COMMAND ""
|
||||
EXCLUDE_FROM_ALL 1)
|
||||
else()
|
||||
ExternalProject_Add(
|
||||
antlr4_runtime
|
||||
PREFIX antlr4_runtime
|
||||
GIT_REPOSITORY ${ANTLR4_GIT_REPOSITORY}
|
||||
GIT_TAG ${ANTLR4_TAG}
|
||||
DOWNLOAD_DIR ${CMAKE_CURRENT_BINARY_DIR}
|
||||
BUILD_COMMAND ""
|
||||
BUILD_IN_SOURCE 1
|
||||
SOURCE_DIR ${ANTLR4_ROOT}
|
||||
SOURCE_SUBDIR runtime/Cpp
|
||||
CMAKE_CACHE_ARGS
|
||||
-DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE}
|
||||
-DWITH_STATIC_CRT:BOOL=${ANTLR4_WITH_STATIC_CRT}
|
||||
-DDISABLE_WARNINGS:BOOL=ON
|
||||
# -DCMAKE_CXX_STANDARD:STRING=17 # if desired, compile the runtime with a different C++ standard
|
||||
# -DCMAKE_CXX_STANDARD:STRING=${CMAKE_CXX_STANDARD} # alternatively, compile the runtime with the same C++ standard as the outer project
|
||||
INSTALL_COMMAND ""
|
||||
EXCLUDE_FROM_ALL 1)
|
||||
endif()
|
||||
|
||||
# Separate build step as rarely people want both
|
||||
set(ANTLR4_BUILD_DIR ${ANTLR4_ROOT})
|
||||
if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.14.0")
|
||||
# CMake 3.14 builds in above's SOURCE_SUBDIR when BUILD_IN_SOURCE is true
|
||||
set(ANTLR4_BUILD_DIR ${ANTLR4_ROOT}/runtime/Cpp)
|
||||
endif()
|
||||
|
||||
ExternalProject_Add_Step(
|
||||
antlr4_runtime
|
||||
build_static
|
||||
COMMAND ${ANTLR4_BUILD_COMMAND} antlr4_static
|
||||
# Depend on target instead of step (a custom command)
|
||||
# to avoid running dependent steps concurrently
|
||||
DEPENDS antlr4_runtime
|
||||
BYPRODUCTS ${ANTLR4_STATIC_LIBRARIES}
|
||||
EXCLUDE_FROM_MAIN 1
|
||||
WORKING_DIRECTORY ${ANTLR4_BUILD_DIR})
|
||||
ExternalProject_Add_StepTargets(antlr4_runtime build_static)
|
||||
|
||||
add_library(antlr4_static STATIC IMPORTED)
|
||||
add_dependencies(antlr4_static antlr4_runtime-build_static)
|
||||
set_target_properties(antlr4_static PROPERTIES
|
||||
IMPORTED_LOCATION ${ANTLR4_STATIC_LIBRARIES})
|
||||
target_include_directories(antlr4_static
|
||||
INTERFACE
|
||||
${ANTLR4_INCLUDE_DIRS}
|
||||
)
|
||||
|
||||
ExternalProject_Add_Step(
|
||||
antlr4_runtime
|
||||
build_shared
|
||||
COMMAND ${ANTLR4_BUILD_COMMAND} antlr4_shared
|
||||
# Depend on target instead of step (a custom command)
|
||||
# to avoid running dependent steps concurrently
|
||||
DEPENDS antlr4_runtime
|
||||
BYPRODUCTS ${ANTLR4_SHARED_LIBRARIES} ${ANTLR4_RUNTIME_LIBRARIES}
|
||||
EXCLUDE_FROM_MAIN 1
|
||||
WORKING_DIRECTORY ${ANTLR4_BUILD_DIR})
|
||||
ExternalProject_Add_StepTargets(antlr4_runtime build_shared)
|
||||
|
||||
add_library(antlr4_shared SHARED IMPORTED)
|
||||
add_dependencies(antlr4_shared antlr4_runtime-build_shared)
|
||||
set_target_properties(antlr4_shared PROPERTIES
|
||||
IMPORTED_LOCATION ${ANTLR4_RUNTIME_LIBRARIES})
|
||||
target_include_directories(antlr4_shared
|
||||
INTERFACE
|
||||
${ANTLR4_INCLUDE_DIRS}
|
||||
)
|
||||
|
||||
if(ANTLR4_SHARED_LIBRARIES)
|
||||
set_target_properties(antlr4_shared PROPERTIES
|
||||
IMPORTED_IMPLIB ${ANTLR4_SHARED_LIBRARIES})
|
||||
endif()
|
||||
124
antlr/antlr4-runtime-4.12.0/cmake/FindANTLR.cmake
Normal file
124
antlr/antlr4-runtime-4.12.0/cmake/FindANTLR.cmake
Normal file
@ -0,0 +1,124 @@
|
||||
find_package(Java QUIET COMPONENTS Runtime)
|
||||
|
||||
if(NOT ANTLR_EXECUTABLE)
|
||||
find_program(ANTLR_EXECUTABLE
|
||||
NAMES antlr.jar antlr4.jar antlr-4.jar antlr-4.12.0-complete.jar)
|
||||
endif()
|
||||
|
||||
if(ANTLR_EXECUTABLE AND Java_JAVA_EXECUTABLE)
|
||||
execute_process(
|
||||
COMMAND ${Java_JAVA_EXECUTABLE} -jar ${ANTLR_EXECUTABLE}
|
||||
OUTPUT_VARIABLE ANTLR_COMMAND_OUTPUT
|
||||
ERROR_VARIABLE ANTLR_COMMAND_ERROR
|
||||
RESULT_VARIABLE ANTLR_COMMAND_RESULT
|
||||
OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
|
||||
if(ANTLR_COMMAND_RESULT EQUAL 0)
|
||||
string(REGEX MATCH "Version [0-9]+(\\.[0-9]+)*" ANTLR_VERSION ${ANTLR_COMMAND_OUTPUT})
|
||||
string(REPLACE "Version " "" ANTLR_VERSION ${ANTLR_VERSION})
|
||||
else()
|
||||
message(
|
||||
SEND_ERROR
|
||||
"Command '${Java_JAVA_EXECUTABLE} -jar ${ANTLR_EXECUTABLE}' "
|
||||
"failed with the output '${ANTLR_COMMAND_ERROR}'")
|
||||
endif()
|
||||
|
||||
macro(ANTLR_TARGET Name InputFile)
|
||||
set(ANTLR_OPTIONS LEXER PARSER LISTENER VISITOR)
|
||||
set(ANTLR_ONE_VALUE_ARGS PACKAGE OUTPUT_DIRECTORY DEPENDS_ANTLR)
|
||||
set(ANTLR_MULTI_VALUE_ARGS COMPILE_FLAGS DEPENDS)
|
||||
cmake_parse_arguments(ANTLR_TARGET
|
||||
"${ANTLR_OPTIONS}"
|
||||
"${ANTLR_ONE_VALUE_ARGS}"
|
||||
"${ANTLR_MULTI_VALUE_ARGS}"
|
||||
${ARGN})
|
||||
|
||||
set(ANTLR_${Name}_INPUT ${InputFile})
|
||||
|
||||
get_filename_component(ANTLR_INPUT ${InputFile} NAME_WE)
|
||||
|
||||
if(ANTLR_TARGET_OUTPUT_DIRECTORY)
|
||||
set(ANTLR_${Name}_OUTPUT_DIR ${ANTLR_TARGET_OUTPUT_DIRECTORY})
|
||||
else()
|
||||
set(ANTLR_${Name}_OUTPUT_DIR
|
||||
${CMAKE_CURRENT_BINARY_DIR}/antlr4cpp_generated_src/${ANTLR_INPUT})
|
||||
endif()
|
||||
|
||||
unset(ANTLR_${Name}_CXX_OUTPUTS)
|
||||
|
||||
if((ANTLR_TARGET_LEXER AND NOT ANTLR_TARGET_PARSER) OR
|
||||
(ANTLR_TARGET_PARSER AND NOT ANTLR_TARGET_LEXER))
|
||||
list(APPEND ANTLR_${Name}_CXX_OUTPUTS
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}.h
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}.cpp)
|
||||
set(ANTLR_${Name}_OUTPUTS
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}.interp
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}.tokens)
|
||||
else()
|
||||
list(APPEND ANTLR_${Name}_CXX_OUTPUTS
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Lexer.h
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Lexer.cpp
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Parser.h
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Parser.cpp)
|
||||
list(APPEND ANTLR_${Name}_OUTPUTS
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Lexer.interp
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Lexer.tokens)
|
||||
endif()
|
||||
|
||||
if(ANTLR_TARGET_LISTENER)
|
||||
list(APPEND ANTLR_${Name}_CXX_OUTPUTS
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}BaseListener.h
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}BaseListener.cpp
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Listener.h
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Listener.cpp)
|
||||
list(APPEND ANTLR_TARGET_COMPILE_FLAGS -listener)
|
||||
endif()
|
||||
|
||||
if(ANTLR_TARGET_VISITOR)
|
||||
list(APPEND ANTLR_${Name}_CXX_OUTPUTS
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}BaseVisitor.h
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}BaseVisitor.cpp
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Visitor.h
|
||||
${ANTLR_${Name}_OUTPUT_DIR}/${ANTLR_INPUT}Visitor.cpp)
|
||||
list(APPEND ANTLR_TARGET_COMPILE_FLAGS -visitor)
|
||||
endif()
|
||||
|
||||
if(ANTLR_TARGET_PACKAGE)
|
||||
list(APPEND ANTLR_TARGET_COMPILE_FLAGS -package ${ANTLR_TARGET_PACKAGE})
|
||||
endif()
|
||||
|
||||
list(APPEND ANTLR_${Name}_OUTPUTS ${ANTLR_${Name}_CXX_OUTPUTS})
|
||||
|
||||
if(ANTLR_TARGET_DEPENDS_ANTLR)
|
||||
if(ANTLR_${ANTLR_TARGET_DEPENDS_ANTLR}_INPUT)
|
||||
list(APPEND ANTLR_TARGET_DEPENDS
|
||||
${ANTLR_${ANTLR_TARGET_DEPENDS_ANTLR}_INPUT})
|
||||
list(APPEND ANTLR_TARGET_DEPENDS
|
||||
${ANTLR_${ANTLR_TARGET_DEPENDS_ANTLR}_OUTPUTS})
|
||||
else()
|
||||
message(SEND_ERROR
|
||||
"ANTLR target '${ANTLR_TARGET_DEPENDS_ANTLR}' not found")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT ${ANTLR_${Name}_OUTPUTS}
|
||||
COMMAND ${Java_JAVA_EXECUTABLE} -jar ${ANTLR_EXECUTABLE}
|
||||
${InputFile}
|
||||
-o ${ANTLR_${Name}_OUTPUT_DIR}
|
||||
-no-listener
|
||||
-Dlanguage=Cpp
|
||||
${ANTLR_TARGET_COMPILE_FLAGS}
|
||||
DEPENDS ${InputFile}
|
||||
${ANTLR_TARGET_DEPENDS}
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
|
||||
COMMENT "Building ${Name} with ANTLR ${ANTLR_VERSION}")
|
||||
endmacro(ANTLR_TARGET)
|
||||
|
||||
endif(ANTLR_EXECUTABLE AND Java_JAVA_EXECUTABLE)
|
||||
|
||||
include(FindPackageHandleStandardArgs)
|
||||
find_package_handle_standard_args(
|
||||
ANTLR
|
||||
REQUIRED_VARS ANTLR_EXECUTABLE Java_JAVA_EXECUTABLE
|
||||
VERSION_VAR ANTLR_VERSION)
|
||||
165
antlr/antlr4-runtime-4.12.0/cmake/README.md
Normal file
165
antlr/antlr4-runtime-4.12.0/cmake/README.md
Normal file
@ -0,0 +1,165 @@
|
||||
## Getting started with Antlr4Cpp
|
||||
|
||||
Here is how you can use this external project to create the antlr4cpp demo to start your project off.
|
||||
|
||||
1. Create your project source folder somewhere. e.g. ~/srcfolder/
|
||||
1. Make a subfolder cmake
|
||||
2. Copy the files in this folder to srcfolder/cmake
|
||||
3. Cut below and use it to create srcfolder/CMakeLists.txt
|
||||
4. Copy main.cpp, TLexer.g4 and TParser.g4 to srcfolder/ from [here](https://github.com/antlr/antlr4/tree/master/runtime/Cpp/demo)
|
||||
2. Make a build folder e.g. ~/buildfolder/
|
||||
3. From the buildfolder, run `cmake ~/srcfolder; make`
|
||||
|
||||
```cmake
|
||||
# minimum required CMAKE version
|
||||
CMAKE_MINIMUM_REQUIRED(VERSION 3.7 FATAL_ERROR)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
|
||||
|
||||
# compiler must be 17
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
|
||||
# required if linking to static library
|
||||
add_definitions(-DANTLR4CPP_STATIC)
|
||||
|
||||
# using /MD flag for antlr4_runtime (for Visual C++ compilers only)
|
||||
set(ANTLR4_WITH_STATIC_CRT OFF)
|
||||
|
||||
# Specify the version of the antlr4 library needed for this project.
|
||||
# By default the latest version of antlr4 will be used. You can specify a
|
||||
# specific, stable version by setting a repository tag value or a link
|
||||
# to a zip file containing the libary source.
|
||||
# set(ANTLR4_TAG 4.12.0)
|
||||
# set(ANTLR4_ZIP_REPOSITORY https://github.com/antlr/antlr4/archive/refs/tags/4.12.0.zip)
|
||||
|
||||
# add external build for antlrcpp
|
||||
include(ExternalAntlr4Cpp)
|
||||
# add antrl4cpp artifacts to project environment
|
||||
include_directories(${ANTLR4_INCLUDE_DIRS})
|
||||
|
||||
# set variable pointing to the antlr tool that supports C++
|
||||
# this is not required if the jar file can be found under PATH environment
|
||||
set(ANTLR_EXECUTABLE /home/user/antlr-4.12.0-complete.jar)
|
||||
# add macros to generate ANTLR Cpp code from grammar
|
||||
find_package(ANTLR REQUIRED)
|
||||
|
||||
# Call macro to add lexer and grammar to your build dependencies.
|
||||
antlr_target(SampleGrammarLexer TLexer.g4 LEXER
|
||||
PACKAGE antlrcpptest)
|
||||
antlr_target(SampleGrammarParser TParser.g4 PARSER
|
||||
PACKAGE antlrcpptest
|
||||
DEPENDS_ANTLR SampleGrammarLexer
|
||||
COMPILE_FLAGS -lib ${ANTLR_SampleGrammarLexer_OUTPUT_DIR})
|
||||
|
||||
# include generated files in project environment
|
||||
include_directories(${ANTLR_SampleGrammarLexer_OUTPUT_DIR})
|
||||
include_directories(${ANTLR_SampleGrammarParser_OUTPUT_DIR})
|
||||
|
||||
# add generated grammar to demo binary target
|
||||
add_executable(demo main.cpp
|
||||
${ANTLR_SampleGrammarLexer_CXX_OUTPUTS}
|
||||
${ANTLR_SampleGrammarParser_CXX_OUTPUTS})
|
||||
target_link_libraries(demo antlr4_static)
|
||||
```
|
||||
|
||||
## Documentation for FindANTLR
|
||||
|
||||
The module defines the following variables:
|
||||
|
||||
```
|
||||
ANTLR_FOUND - true is ANTLR jar executable is found
|
||||
ANTLR_EXECUTABLE - the path to the ANTLR jar executable
|
||||
ANTLR_VERSION - the version of ANTLR
|
||||
```
|
||||
|
||||
If ANTLR is found, the module will provide the macros:
|
||||
|
||||
```
|
||||
ANTLR_TARGET(<name> <input>
|
||||
[PACKAGE namespace]
|
||||
[OUTPUT_DIRECTORY dir]
|
||||
[DEPENDS_ANTLR <target>]
|
||||
[COMPILE_FLAGS [args...]]
|
||||
[DEPENDS [depends...]]
|
||||
[LEXER]
|
||||
[PARSER]
|
||||
[LISTENER]
|
||||
[VISITOR])
|
||||
```
|
||||
|
||||
which creates a custom command to generate C++ files from `<input>`. Running the macro defines the following variables:
|
||||
|
||||
```
|
||||
ANTLR_${name}_INPUT - the ANTLR input used for the macro
|
||||
ANTLR_${name}_OUTPUTS - the outputs generated by ANTLR
|
||||
ANTLR_${name}_CXX_OUTPUTS - the C++ outputs generated by ANTLR
|
||||
ANTLR_${name}_OUTPUT_DIR - the output directory for ANTLR
|
||||
```
|
||||
|
||||
The options are:
|
||||
|
||||
* `PACKAGE` - defines a namespace for the generated C++ files
|
||||
* `OUTPUT_DIRECTORY` - the output directory for the generated files. By default it uses `${CMAKE_CURRENT_BINARY_DIR}`
|
||||
* `DEPENDS_ANTLR` - the dependent target generated from antlr_target for the current call
|
||||
* `COMPILE_FLAGS` - additional compile flags for ANTLR tool
|
||||
* `DEPENDS` - specify the files on which the command depends. It works the same way `DEPENDS` in [`add_custom_command()`](https://cmake.org/cmake/help/v3.11/command/add_custom_command.html)
|
||||
* `LEXER` - specify that the input file is a lexer grammar
|
||||
* `PARSER` - specify that the input file is a parser grammar
|
||||
* `LISTENER` - tell ANTLR tool to generate a parse tree listener
|
||||
* `VISITOR` - tell ANTLR tool to generate a parse tree visitor
|
||||
|
||||
### Examples
|
||||
|
||||
To generate C++ files from an ANTLR input file T.g4, which defines both lexer and parser grammar one may call:
|
||||
|
||||
```cmake
|
||||
find_package(ANTLR REQUIRED)
|
||||
antlr_target(Sample T.g4)
|
||||
```
|
||||
|
||||
Note that this command will do nothing unless the outputs of `Sample`, i.e. `ANTLR_Sample_CXX_OUTPUTS` gets used by some target.
|
||||
|
||||
## Documentation for ExternalAntlr4Cpp
|
||||
|
||||
Including ExternalAntlr4Cpp will add `antlr4_static` and `antlr4_shared` as an optional target. It will also define the following variables:
|
||||
|
||||
```
|
||||
ANTLR4_INCLUDE_DIRS - the include directory that should be included when compiling C++ source file
|
||||
ANTLR4_STATIC_LIBRARIES - path to antlr4 static library
|
||||
ANTLR4_SHARED_LIBRARIES - path to antlr4 shared library
|
||||
ANTLR4_RUNTIME_LIBRARIES - path to antlr4 shared runtime library (such as DLL, DYLIB and SO file)
|
||||
ANTLR4_TAG - branch/tag used for building antlr4 library
|
||||
```
|
||||
|
||||
`ANTLR4_TAG` is set to master branch by default to keep the antlr4 library up to date. However, this will require a rebuild after every `clean` is called. Set `ANTLR4_TAG` to a desired commit hash value to avoid rebuilding after every `clean` and keep the build stable, at the cost of not automatically updating to latest commit.
|
||||
|
||||
By defualt the ANTLR C++ runtime source is cloned from GitHub. However, users may specify `ANTLR4_ZIP_REPOSITORY` in order to download source as a zip file from [ANTLR downloads](http://www.antlr.org/download.html) (under *C++ Target*) or other locations. For example, this variable could list a zip file included in your the project directory. This is useful for maintaining a canonical source tree for each new build.
|
||||
|
||||
Visual C++ compiler users may want to additionally define `ANTLR4_WITH_STATIC_CRT` before including the file. Set `ANTLR4_WITH_STATIC_CRT` to true if ANTLR4 C++ runtime library should be compiled with `/MT` flag, otherwise will be compiled with `/MD` flag. This variable has a default value of `OFF`. Changing `ANTLR4_WITH_STATIC_CRT` after building the library may require reinitialization of CMake or `clean` for the library to get rebuilt.
|
||||
|
||||
You may need to modify your local copy of ExternalAntlr4Cpp.cpp to modify some build settings. For example, to specify the C++ standard to use when building the runtime, add `-DCMAKE_CXX_STANDARD:STRING=17` to `CMAKE_CACHE_ARGS`.
|
||||
|
||||
### Examples
|
||||
|
||||
To build and link ANTLR4 static library to a target one may call:
|
||||
|
||||
```cmake
|
||||
include(ExternalAntlr4Cpp)
|
||||
include_directories(${ANTLR4_INCLUDE_DIRS})
|
||||
add_executable(output main.cpp)
|
||||
target_link_libraries(output antlr4_static)
|
||||
```
|
||||
|
||||
It may also be a good idea to copy the runtime libraries (DLL, DYLIB or SO file) to the executable for it to run properly after build. i.e. To build and link antlr4 shared library to a target one may call:
|
||||
|
||||
```cmake
|
||||
include(ExternalAntlr4Cpp)
|
||||
include_directories(${ANTLR4_INCLUDE_DIRS})
|
||||
add_executable(output main.cpp)
|
||||
target_link_libraries(output antlr4_shared)
|
||||
add_custom_command(TARGET output
|
||||
POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-E copy ${ANTLR4_RUNTIME_LIBRARIES} .
|
||||
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
|
||||
```
|
||||
181
antlr/antlr4-runtime-4.12.0/cmake/antlr4-generator.cmake.in
Normal file
181
antlr/antlr4-runtime-4.12.0/cmake/antlr4-generator.cmake.in
Normal file
@ -0,0 +1,181 @@
|
||||
set(ANTLR_VERSION @ANTLR_VERSION@)
|
||||
|
||||
@PACKAGE_INIT@
|
||||
|
||||
if (NOT ANTLR4_CPP_GENERATED_SRC_DIR)
|
||||
set(ANTLR4_GENERATED_SRC_DIR ${CMAKE_BINARY_DIR}/antlr4_generated_src)
|
||||
endif()
|
||||
|
||||
FIND_PACKAGE(Java COMPONENTS Runtime REQUIRED)
|
||||
|
||||
#
|
||||
# The ANTLR generator will output the following files given the input file f.g4
|
||||
#
|
||||
# Input -> f.g4
|
||||
# Output -> f.h
|
||||
# -> f.cpp
|
||||
#
|
||||
# the following files will only be produced if there is a parser contained
|
||||
# Flag -visitor active
|
||||
# Output -> <f>BaseVisitor.h
|
||||
# -> <f>BaseVisitor.cpp
|
||||
# -> <f>Visitor.h
|
||||
# -> <f>Visitor.cpp
|
||||
#
|
||||
# Flag -listener active
|
||||
# Output -> <f>BaseListener.h
|
||||
# -> <f>BaseListener.cpp
|
||||
# -> <f>Listener.h
|
||||
# -> <f>Listener.cpp
|
||||
#
|
||||
# See documentation in markup
|
||||
#
|
||||
function(antlr4_generate
|
||||
Antlr4_ProjectTarget
|
||||
Antlr4_InputFile
|
||||
Antlr4_GeneratorType
|
||||
)
|
||||
|
||||
set( Antlr4_GeneratedSrcDir ${ANTLR4_GENERATED_SRC_DIR}/${Antlr4_ProjectTarget} )
|
||||
|
||||
get_filename_component(Antlr4_InputFileBaseName ${Antlr4_InputFile} NAME_WE )
|
||||
|
||||
list( APPEND Antlr4_GeneratorStatusMessage "Common Include-, Source- and Tokenfiles" )
|
||||
|
||||
if ( ${Antlr4_GeneratorType} STREQUAL "LEXER")
|
||||
set(Antlr4_LexerBaseName "${Antlr4_InputFileBaseName}")
|
||||
set(Antlr4_ParserBaseName "")
|
||||
else()
|
||||
if ( ${Antlr4_GeneratorType} STREQUAL "PARSER")
|
||||
set(Antlr4_LexerBaseName "")
|
||||
set(Antlr4_ParserBaseName "${Antlr4_InputFileBaseName}")
|
||||
else()
|
||||
if ( ${Antlr4_GeneratorType} STREQUAL "BOTH")
|
||||
set(Antlr4_LexerBaseName "${Antlr4_InputFileBaseName}Lexer")
|
||||
set(Antlr4_ParserBaseName "${Antlr4_InputFileBaseName}Parser")
|
||||
else()
|
||||
message(FATAL_ERROR "The third parameter must be LEXER, PARSER or BOTH")
|
||||
endif ()
|
||||
endif ()
|
||||
endif ()
|
||||
|
||||
# Prepare list of generated targets
|
||||
list( APPEND Antlr4_GeneratedTargets "${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}.tokens" )
|
||||
list( APPEND Antlr4_GeneratedTargets "${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}.interp" )
|
||||
list( APPEND DependentTargets "${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}.tokens" )
|
||||
|
||||
if ( NOT ${Antlr4_LexerBaseName} STREQUAL "" )
|
||||
list( APPEND Antlr4_GeneratedTargets "${Antlr4_GeneratedSrcDir}/${Antlr4_LexerBaseName}.h" )
|
||||
list( APPEND Antlr4_GeneratedTargets "${Antlr4_GeneratedSrcDir}/${Antlr4_LexerBaseName}.cpp" )
|
||||
endif ()
|
||||
|
||||
if ( NOT ${Antlr4_ParserBaseName} STREQUAL "" )
|
||||
list( APPEND Antlr4_GeneratedTargets "${Antlr4_GeneratedSrcDir}/${Antlr4_ParserBaseName}.h" )
|
||||
list( APPEND Antlr4_GeneratedTargets "${Antlr4_GeneratedSrcDir}/${Antlr4_ParserBaseName}.cpp" )
|
||||
endif ()
|
||||
|
||||
# process optional arguments ...
|
||||
|
||||
if ( ( ARGC GREATER_EQUAL 4 ) AND ARGV3 )
|
||||
set(Antlr4_BuildListenerOption "-listener")
|
||||
|
||||
list( APPEND Antlr4_GeneratedTargets "${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}BaseListener.h" )
|
||||
list( APPEND Antlr4_GeneratedTargets "${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}BaseListener.cpp" )
|
||||
list( APPEND Antlr4_GeneratedTargets "${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}Listener.h" )
|
||||
list( APPEND Antlr4_GeneratedTargets "${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}Listener.cpp" )
|
||||
|
||||
list( APPEND Antlr4_GeneratorStatusMessage ", Listener Include- and Sourcefiles" )
|
||||
else()
|
||||
set(Antlr4_BuildListenerOption "-no-listener")
|
||||
endif ()
|
||||
|
||||
if ( ( ARGC GREATER_EQUAL 5 ) AND ARGV4 )
|
||||
set(Antlr4_BuildVisitorOption "-visitor")
|
||||
|
||||
list( APPEND Antlr4_GeneratedTargets "${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}BaseVisitor.h" )
|
||||
list( APPEND Antlr4_GeneratedTargets "${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}BaseVisitor.cpp" )
|
||||
list( APPEND Antlr4_GeneratedTargets "${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}Visitor.h" )
|
||||
list( APPEND Antlr4_GeneratedTargets "${Antlr4_GeneratedSrcDir}/${Antlr4_InputFileBaseName}Visitor.cpp" )
|
||||
|
||||
list( APPEND Antlr4_GeneratorStatusMessage ", Visitor Include- and Sourcefiles" )
|
||||
else()
|
||||
set(Antlr4_BuildVisitorOption "-no-visitor")
|
||||
endif ()
|
||||
|
||||
if ( (ARGC GREATER_EQUAL 6 ) AND (NOT ${ARGV5} STREQUAL "") )
|
||||
set(Antlr4_NamespaceOption "-package;${ARGV5}")
|
||||
|
||||
list( APPEND Antlr4_GeneratorStatusMessage " in Namespace ${ARGV5}" )
|
||||
else()
|
||||
set(Antlr4_NamespaceOption "")
|
||||
endif ()
|
||||
|
||||
if ( (ARGC GREATER_EQUAL 7 ) AND (NOT ${ARGV6} STREQUAL "") )
|
||||
set(Antlr4_AdditionalDependencies ${ARGV6})
|
||||
else()
|
||||
set(Antlr4_AdditionalDependencies "")
|
||||
endif ()
|
||||
|
||||
if ( (ARGC GREATER_EQUAL 8 ) AND (NOT ${ARGV7} STREQUAL "") )
|
||||
set(Antlr4_LibOption "-lib;${ARGV7}")
|
||||
|
||||
list( APPEND Antlr4_GeneratorStatusMessage " using Library ${ARGV7}" )
|
||||
else()
|
||||
set(Antlr4_LibOption "")
|
||||
endif ()
|
||||
|
||||
if(NOT Java_FOUND)
|
||||
message(FATAL_ERROR "Java is required to process grammar or lexer files! - Use 'FIND_PACKAGE(Java COMPONENTS Runtime REQUIRED)'")
|
||||
endif()
|
||||
|
||||
if(NOT EXISTS "${ANTLR4_JAR_LOCATION}")
|
||||
message(FATAL_ERROR "Unable to find antlr tool. ANTLR4_JAR_LOCATION:${ANTLR4_JAR_LOCATION}")
|
||||
endif()
|
||||
|
||||
# The call to generate the files
|
||||
add_custom_command(
|
||||
OUTPUT ${Antlr4_GeneratedTargets}
|
||||
# Remove target directory
|
||||
COMMAND
|
||||
${CMAKE_COMMAND} -E remove_directory ${Antlr4_GeneratedSrcDir}
|
||||
# Create target directory
|
||||
COMMAND
|
||||
${CMAKE_COMMAND} -E make_directory ${Antlr4_GeneratedSrcDir}
|
||||
COMMAND
|
||||
# Generate files
|
||||
"${Java_JAVA_EXECUTABLE}" -jar "${ANTLR4_JAR_LOCATION}" -Werror -Dlanguage=Cpp ${Antlr4_BuildListenerOption} ${Antlr4_BuildVisitorOption} ${Antlr4_LibOption} ${ANTLR4_GENERATED_OPTIONS} -o "${Antlr4_GeneratedSrcDir}" ${Antlr4_NamespaceOption} "${Antlr4_InputFile}"
|
||||
WORKING_DIRECTORY "${CMAKE_BINARY_DIR}"
|
||||
MAIN_DEPENDENCY "${Antlr4_InputFile}"
|
||||
DEPENDS ${Antlr4_AdditionalDependencies}
|
||||
)
|
||||
|
||||
# set output variables in parent scope
|
||||
set( ANTLR4_INCLUDE_DIR_${Antlr4_ProjectTarget} ${Antlr4_GeneratedSrcDir} PARENT_SCOPE)
|
||||
set( ANTLR4_SRC_FILES_${Antlr4_ProjectTarget} ${Antlr4_GeneratedTargets} PARENT_SCOPE)
|
||||
set( ANTLR4_TOKEN_FILES_${Antlr4_ProjectTarget} ${DependentTargets} PARENT_SCOPE)
|
||||
set( ANTLR4_TOKEN_DIRECTORY_${Antlr4_ProjectTarget} ${Antlr4_GeneratedSrcDir} PARENT_SCOPE)
|
||||
|
||||
# export generated cpp files into list
|
||||
foreach(generated_file ${Antlr4_GeneratedTargets})
|
||||
|
||||
if (NOT CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
|
||||
set_source_files_properties(
|
||||
${generated_file}
|
||||
PROPERTIES
|
||||
COMPILE_FLAGS -Wno-overloaded-virtual
|
||||
)
|
||||
endif ()
|
||||
|
||||
if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
|
||||
set_source_files_properties(
|
||||
${generated_file}
|
||||
PROPERTIES
|
||||
COMPILE_FLAGS -wd4251
|
||||
)
|
||||
endif ()
|
||||
|
||||
endforeach(generated_file)
|
||||
|
||||
message(STATUS "Antlr4 ${Antlr4_ProjectTarget} - Building " ${Antlr4_GeneratorStatusMessage} )
|
||||
|
||||
endfunction()
|
||||
13
antlr/antlr4-runtime-4.12.0/cmake/antlr4-runtime.cmake.in
Normal file
13
antlr/antlr4-runtime-4.12.0/cmake/antlr4-runtime.cmake.in
Normal file
@ -0,0 +1,13 @@
|
||||
set(ANTLR_VERSION @ANTLR_VERSION@)
|
||||
|
||||
@PACKAGE_INIT@
|
||||
|
||||
set_and_check(ANTLR4_INCLUDE_DIR "@PACKAGE_ANTLR4_INCLUDE_DIR@")
|
||||
set_and_check(ANTLR4_LIB_DIR "@PACKAGE_ANTLR4_LIB_DIR@")
|
||||
|
||||
include(CMakeFindDependencyMacro)
|
||||
find_dependency(Threads)
|
||||
|
||||
include(${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake)
|
||||
|
||||
check_required_components(antlr)
|
||||
80
antlr/antlr4-runtime-4.12.0/demo/CMakeLists.txt
Normal file
80
antlr/antlr4-runtime-4.12.0/demo/CMakeLists.txt
Normal file
@ -0,0 +1,80 @@
|
||||
# -*- mode:cmake -*-
|
||||
if(NOT UNIX)
|
||||
message(WARNING "Unsupported operating system")
|
||||
endif()
|
||||
|
||||
set(antlr4-demo-GENERATED_SRC
|
||||
${PROJECT_SOURCE_DIR}/demo/generated/TLexer.cpp
|
||||
${PROJECT_SOURCE_DIR}/demo/generated/TParser.cpp
|
||||
${PROJECT_SOURCE_DIR}/demo/generated/TParserBaseListener.cpp
|
||||
${PROJECT_SOURCE_DIR}/demo/generated/TParserBaseVisitor.cpp
|
||||
${PROJECT_SOURCE_DIR}/demo/generated/TParserListener.cpp
|
||||
${PROJECT_SOURCE_DIR}/demo/generated/TParserVisitor.cpp
|
||||
)
|
||||
|
||||
foreach(src_file ${antlr4-demo-GENERATED_SRC})
|
||||
set_source_files_properties(
|
||||
${src_file}
|
||||
PROPERTIES
|
||||
GENERATED TRUE
|
||||
)
|
||||
endforeach(src_file ${antlr4-demo-GENERATED_SRC})
|
||||
|
||||
add_custom_target(GenerateParser DEPENDS ${antlr4-demo-GENERATED_SRC})
|
||||
add_custom_command(OUTPUT ${antlr4-demo-GENERATED_SRC}
|
||||
COMMAND
|
||||
${CMAKE_COMMAND} -E make_directory ${PROJECT_SOURCE_DIR}/demo/generated/
|
||||
COMMAND
|
||||
"${Java_JAVA_EXECUTABLE}" -jar ${ANTLR_JAR_LOCATION} -Werror -Dlanguage=Cpp -listener -visitor -o ${PROJECT_SOURCE_DIR}/demo/generated/ -package antlrcpptest ${PROJECT_SOURCE_DIR}/demo/TLexer.g4 ${PROJECT_SOURCE_DIR}/demo/TParser.g4
|
||||
WORKING_DIRECTORY "${CMAKE_BINARY_DIR}"
|
||||
DEPENDS ${PROJECT_SOURCE_DIR}/demo/TLexer.g4 ${PROJECT_SOURCE_DIR}/demo/TParser.g4
|
||||
)
|
||||
|
||||
include_directories(
|
||||
${PROJECT_SOURCE_DIR}/runtime/src
|
||||
${PROJECT_SOURCE_DIR}/runtime/src/misc
|
||||
${PROJECT_SOURCE_DIR}/runtime/src/atn
|
||||
${PROJECT_SOURCE_DIR}/runtime/src/dfa
|
||||
${PROJECT_SOURCE_DIR}/runtime/src/tree
|
||||
${PROJECT_SOURCE_DIR}/runtime/src/support
|
||||
${PROJECT_SOURCE_DIR}/demo/generated
|
||||
)
|
||||
|
||||
#file(GLOB antlr4-demo_SRC "${PROJECT_SOURCE_DIR}/demo/generated/*")
|
||||
set(antlr4-demo_SRC
|
||||
${PROJECT_SOURCE_DIR}/demo/Linux/main.cpp
|
||||
${antlr4-demo-GENERATED_SRC}
|
||||
)
|
||||
|
||||
if(NOT CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
|
||||
set (flags_1 "-Wno-overloaded-virtual")
|
||||
else()
|
||||
set (flags_1 "-MP /wd4251")
|
||||
endif()
|
||||
|
||||
foreach(src_file ${antlr4-demo_SRC})
|
||||
set_source_files_properties(
|
||||
${src_file}
|
||||
PROPERTIES
|
||||
COMPILE_FLAGS "${COMPILE_FLAGS} ${flags_1}"
|
||||
)
|
||||
endforeach(src_file ${antlr4-demo_SRC})
|
||||
|
||||
add_executable(antlr4-demo
|
||||
${antlr4-demo_SRC}
|
||||
)
|
||||
#add_precompiled_header(antlr4-demo ${PROJECT_SOURCE_DIR}/runtime/src/antlrcpp-Prefix.h)
|
||||
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
|
||||
target_compile_options(antlr4-demo PRIVATE "/MT$<$<CONFIG:Debug>:d>")
|
||||
endif()
|
||||
|
||||
add_dependencies(antlr4-demo GenerateParser)
|
||||
|
||||
target_link_libraries(antlr4-demo antlr4_static)
|
||||
|
||||
install(TARGETS antlr4-demo
|
||||
DESTINATION "share"
|
||||
COMPONENT dev
|
||||
)
|
||||
|
||||
38
antlr/antlr4-runtime-4.12.0/demo/Linux/main.cpp
Normal file
38
antlr/antlr4-runtime-4.12.0/demo/Linux/main.cpp
Normal file
@ -0,0 +1,38 @@
|
||||
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
|
||||
* Use of this file is governed by the BSD 3-clause license that
|
||||
* can be found in the LICENSE.txt file in the project root.
|
||||
*/
|
||||
|
||||
//
|
||||
// main.cpp
|
||||
// antlr4-cpp-demo
|
||||
//
|
||||
// Created by Mike Lischke on 13.03.16.
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include "antlr4-runtime.h"
|
||||
#include "TLexer.h"
|
||||
#include "TParser.h"
|
||||
|
||||
using namespace antlrcpptest;
|
||||
using namespace antlr4;
|
||||
|
||||
int main(int , const char **) {
|
||||
ANTLRInputStream input(u8"🍴 = 🍐 + \"😎\";(((x * π))) * µ + ∰; a + (x * (y ? 0 : 1) + z);");
|
||||
TLexer lexer(&input);
|
||||
CommonTokenStream tokens(&lexer);
|
||||
|
||||
tokens.fill();
|
||||
for (auto token : tokens.getTokens()) {
|
||||
std::cout << token->toString() << std::endl;
|
||||
}
|
||||
|
||||
TParser parser(&tokens);
|
||||
tree::ParseTree* tree = parser.main();
|
||||
|
||||
std::cout << tree->toStringTree(&parser) << std::endl << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@ -0,0 +1,38 @@
|
||||
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
|
||||
* Use of this file is governed by the BSD 3-clause license that
|
||||
* can be found in the LICENSE.txt file in the project root.
|
||||
*/
|
||||
|
||||
//
|
||||
// main.cpp
|
||||
// antlr4-cpp-demo
|
||||
//
|
||||
// Created by Mike Lischke on 13.03.16.
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include "antlr4-runtime.h"
|
||||
#include "TLexer.h"
|
||||
#include "TParser.h"
|
||||
|
||||
using namespace antlrcpptest;
|
||||
using namespace antlr4;
|
||||
|
||||
int main(int , const char **) {
|
||||
ANTLRInputStream input(u8"🍴 = 🍐 + \"😎\";(((x * π))) * µ + ∰; a + (x * (y ? 0 : 1) + z);");
|
||||
TLexer lexer(&input);
|
||||
CommonTokenStream tokens(&lexer);
|
||||
|
||||
tokens.fill();
|
||||
for (auto token : tokens.getTokens()) {
|
||||
std::cout << token->toString() << std::endl;
|
||||
}
|
||||
|
||||
TParser parser(&tokens);
|
||||
tree::ParseTree *tree = parser.main();
|
||||
|
||||
std::cout << tree->toStringTree(&parser) << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>BNDL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@ -0,0 +1,172 @@
|
||||
/*
|
||||
* [The "BSD license"]
|
||||
* Copyright (c) 2016 Mike Lischke
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#import <XCTest/XCTest.h>
|
||||
|
||||
#include "ANTLRInputStream.h"
|
||||
#include "Exceptions.h"
|
||||
#include "Interval.h"
|
||||
#include "UnbufferedTokenStream.h"
|
||||
#include "StringUtils.h"
|
||||
|
||||
using namespace antlrcpp;
|
||||
using namespace antlr4;
|
||||
using namespace antlr4::misc;
|
||||
|
||||
@interface InputHandlingTests : XCTestCase
|
||||
|
||||
@end
|
||||
|
||||
@implementation InputHandlingTests
|
||||
|
||||
- (void)setUp {
|
||||
[super setUp];
|
||||
// Put setup code here. This method is called before the invocation of each test method in the class.
|
||||
}
|
||||
|
||||
- (void)tearDown {
|
||||
// Put teardown code here. This method is called after the invocation of each test method in the class.
|
||||
[super tearDown];
|
||||
}
|
||||
|
||||
- (void)testANTLRInputStreamCreation {
|
||||
ANTLRInputStream stream1;
|
||||
XCTAssert(stream1.toString().empty());
|
||||
XCTAssertEqual(stream1.index(), 0U);
|
||||
|
||||
ANTLRInputStream stream2("To be or not to be");
|
||||
XCTAssert(stream2.toString() == "To be or not to be");
|
||||
XCTAssertEqual(stream2.index(), 0U);
|
||||
XCTAssertEqual(stream2.size(), 18U);
|
||||
|
||||
char data[] = "Lorem ipsum dolor sit amet";
|
||||
ANTLRInputStream stream3(data, sizeof(data) / sizeof(data[0]));
|
||||
XCTAssert(stream3.toString() == std::string("Lorem ipsum dolor sit amet\0", 27));
|
||||
XCTAssertEqual(stream3.index(), 0U);
|
||||
XCTAssertEqual(stream3.size(), 27U);
|
||||
|
||||
std::stringstream input("Lorem ipsum dolor sit amet");
|
||||
ANTLRInputStream stream4(input);
|
||||
std::string content = stream4.toString();
|
||||
XCTAssertEqual(content, "Lorem ipsum dolor sit amet"); // Now as utf-8 string.
|
||||
XCTAssertEqual(stream4.index(), 0U);
|
||||
XCTAssertEqual(stream4.size(), 26U);
|
||||
|
||||
std::string longString(33333, 'a');
|
||||
input.str(longString);
|
||||
stream4.load(input);
|
||||
XCTAssertEqual(stream4.index(), 0U);
|
||||
XCTAssertEqual(stream4.size(), 33333U);
|
||||
|
||||
input.clear();
|
||||
stream4.load(input);
|
||||
XCTAssertEqual(stream4.size(), 0U);
|
||||
}
|
||||
|
||||
- (void)testANTLRInputStreamUse {
|
||||
std::string text(u8"🚧Lorem ipsum dolor sit amet🕶");
|
||||
std::u32string wtext = utf8_to_utf32(text.c_str(), text.c_str() + text.size()); // Convert to UTF-32.
|
||||
ANTLRInputStream stream(text);
|
||||
XCTAssertEqual(stream.index(), 0U);
|
||||
XCTAssertEqual(stream.size(), wtext.size());
|
||||
|
||||
for (size_t i = 0; i < stream.size(); ++i) {
|
||||
stream.consume();
|
||||
XCTAssertEqual(stream.index(), i + 1);
|
||||
}
|
||||
|
||||
try {
|
||||
stream.consume();
|
||||
XCTFail();
|
||||
} catch (IllegalStateException &e) {
|
||||
// Expected.
|
||||
std::string message = e.what();
|
||||
XCTAssertEqual(message, "cannot consume EOF");
|
||||
}
|
||||
|
||||
XCTAssertEqual(stream.index(), wtext.size());
|
||||
stream.reset();
|
||||
XCTAssertEqual(stream.index(), 0U);
|
||||
|
||||
XCTAssertEqual(stream.LA(0), 0ULL);
|
||||
for (size_t i = 1; i < wtext.size(); ++i) {
|
||||
XCTAssertEqual(stream.LA(static_cast<ssize_t>(i)), wtext[i - 1]); // LA(1) means: current char.
|
||||
XCTAssertEqual(stream.LT(static_cast<ssize_t>(i)), wtext[i - 1]); // LT is mapped to LA.
|
||||
XCTAssertEqual(stream.index(), 0U); // No consumption when looking ahead.
|
||||
}
|
||||
|
||||
stream.seek(wtext.size() - 1);
|
||||
XCTAssertEqual(stream.index(), wtext.size() - 1);
|
||||
|
||||
stream.seek(wtext.size() / 2);
|
||||
XCTAssertEqual(stream.index(), wtext.size() / 2);
|
||||
|
||||
stream.seek(wtext.size() - 1);
|
||||
for (ssize_t i = 1; i < static_cast<ssize_t>(wtext.size()) - 1; ++i) {
|
||||
XCTAssertEqual(stream.LA(-i), wtext[wtext.size() - i - 1]); // LA(-1) means: previous char.
|
||||
XCTAssertEqual(stream.LT(-i), wtext[wtext.size() - i - 1]); // LT is mapped to LA.
|
||||
XCTAssertEqual(stream.index(), wtext.size() - 1); // No consumption when looking ahead.
|
||||
}
|
||||
|
||||
XCTAssertEqual(stream.LA(-10000), IntStream::EOF);
|
||||
|
||||
// Mark and release do nothing.
|
||||
stream.reset();
|
||||
XCTAssertEqual(stream.index(), 0U);
|
||||
ssize_t marker = stream.mark();
|
||||
XCTAssertEqual(marker, -1);
|
||||
stream.seek(10);
|
||||
XCTAssertEqual(stream.index(), 10U);
|
||||
XCTAssertEqual(stream.mark(), -1);
|
||||
|
||||
stream.release(marker);
|
||||
XCTAssertEqual(stream.index(), 10U);
|
||||
|
||||
misc::Interval interval1(2, 10UL); // From - to, inclusive.
|
||||
std::string output = stream.getText(interval1);
|
||||
std::string sub = utf32_to_utf8(wtext.substr(2, 9));
|
||||
XCTAssertEqual(output, sub);
|
||||
|
||||
misc::Interval interval2(200, 10UL); // Start beyond bounds.
|
||||
output = stream.getText(interval2);
|
||||
XCTAssert(output.empty());
|
||||
|
||||
misc::Interval interval3(0, 200UL); // End beyond bounds.
|
||||
output = stream.getText(interval3);
|
||||
XCTAssertEqual(output, text);
|
||||
|
||||
stream.name = "unit tests"; // Quite useless test, as "name" is a public field.
|
||||
XCTAssertEqual(stream.getSourceName(), "unit tests");
|
||||
}
|
||||
|
||||
- (void)testUnbufferedTokenSteam {
|
||||
//UnbufferedTokenStream stream;
|
||||
}
|
||||
|
||||
@end
|
||||
@ -0,0 +1,388 @@
|
||||
/*
|
||||
* [The "BSD license"]
|
||||
* Copyright (c) 2016 Mike Lischke
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#import <XCTest/XCTest.h>
|
||||
|
||||
#include "antlr4-runtime.h"
|
||||
|
||||
using namespace antlr4;
|
||||
using namespace antlr4::misc;
|
||||
using namespace antlrcpp;
|
||||
|
||||
@interface MiscClassTests : XCTestCase
|
||||
|
||||
@end
|
||||
|
||||
@implementation MiscClassTests
|
||||
|
||||
- (void)setUp {
|
||||
[super setUp];
|
||||
// Put setup code here. This method is called before the invocation of each test method in the class.
|
||||
}
|
||||
|
||||
- (void)tearDown {
|
||||
// Put teardown code here. This method is called after the invocation of each test method in the class.
|
||||
[super tearDown];
|
||||
}
|
||||
|
||||
- (void)testCPPUtils {
|
||||
|
||||
class A { public: virtual ~A() {}; };
|
||||
class B : public A { public: virtual ~B() {}; };
|
||||
class C : public A { public: virtual ~C() {}; };
|
||||
class D : public C { public: virtual ~D() {}; };
|
||||
|
||||
{
|
||||
A *a = new A(); B *b = new B(); C *c = new C(); D *d = new D();
|
||||
XCTAssert(is<A*>(b));
|
||||
XCTAssertFalse(is<B*>(a));
|
||||
XCTAssert(is<A*>(c));
|
||||
XCTAssertFalse(is<B*>(c));
|
||||
XCTAssert(is<A*>(d));
|
||||
XCTAssert(is<C*>(d));
|
||||
XCTAssertFalse(is<B*>(d));
|
||||
delete a; delete b; delete c; delete d;
|
||||
}
|
||||
{
|
||||
Ref<A> a(new A());
|
||||
Ref<B> b(new B());
|
||||
Ref<C> c(new C());
|
||||
Ref<D> d(new D());
|
||||
XCTAssert(is<A>(b));
|
||||
XCTAssertFalse(is<B>(a));
|
||||
XCTAssert(is<A>(c));
|
||||
XCTAssertFalse(is<B>(c));
|
||||
XCTAssert(is<A>(d));
|
||||
XCTAssert(is<C>(d));
|
||||
XCTAssertFalse(is<B>(d));
|
||||
}
|
||||
}
|
||||
|
||||
- (void)testMurmurHash {
|
||||
XCTAssertEqual(MurmurHash::initialize(), 0U);
|
||||
XCTAssertEqual(MurmurHash::initialize(31), 31U);
|
||||
|
||||
// In absence of real test vectors (64bit) for murmurhash I instead check if I can find duplicate hash values
|
||||
// in a deterministic and a random sequence of 100K values each.
|
||||
std::set<size_t> hashs;
|
||||
for (size_t i = 0; i < 100000; ++i) {
|
||||
std::vector<size_t> data = { i, static_cast<size_t>(i * M_PI), arc4random() };
|
||||
size_t hash = 0;
|
||||
for (auto value : data)
|
||||
hash = MurmurHash::update(hash, value);
|
||||
hash = MurmurHash::finish(hash, data.size());
|
||||
hashs.insert(hash);
|
||||
}
|
||||
XCTAssertEqual(hashs.size(), 100000U, @"At least one duplicate hash found.");
|
||||
|
||||
hashs.clear();
|
||||
for (size_t i = 0; i < 100000; ++i) {
|
||||
std::vector<size_t> data = { i, static_cast<size_t>(i * M_PI) };
|
||||
size_t hash = 0;
|
||||
for (auto value : data)
|
||||
hash = MurmurHash::update(hash, value);
|
||||
hash = MurmurHash::finish(hash, data.size());
|
||||
hashs.insert(hash);
|
||||
}
|
||||
XCTAssertEqual(hashs.size(), 100000U, @"At least one duplicate hash found.");
|
||||
|
||||
// Another test with fixed input but varying seeds.
|
||||
// Note: the higher the seed the less LSDs are in the result (for small input data).
|
||||
hashs.clear();
|
||||
std::vector<size_t> data = { L'µ', 'a', '@', '1' };
|
||||
for (size_t i = 0; i < 100000; ++i) {
|
||||
size_t hash = i;
|
||||
for (auto value : data)
|
||||
hash = MurmurHash::update(hash, value);
|
||||
hash = MurmurHash::finish(hash, data.size());
|
||||
hashs.insert(hash);
|
||||
}
|
||||
XCTAssertEqual(hashs.size(), 100000U, @"At least one duplicate hash found.");
|
||||
}
|
||||
|
||||
- (void)testInterval {
|
||||
// The Interval class contains no error handling (checks for invalid intervals), hence some of the results
|
||||
// look strange as we test of course such intervals as well.
|
||||
XCTAssertEqual(Interval().length(), 0UL);
|
||||
XCTAssertEqual(Interval(0, 0UL).length(), 1UL); // Remember: it's an inclusive interval.
|
||||
XCTAssertEqual(Interval(100, 100UL).length(), 1UL);
|
||||
XCTAssertEqual(Interval(-1L, -1).length(), 1UL); // Unwanted behavior: negative ranges.
|
||||
XCTAssertEqual(Interval(-1L, -2).length(), 0UL);
|
||||
XCTAssertEqual(Interval(100, 50UL).length(), 0UL);
|
||||
|
||||
XCTAssert(Interval() == Interval(-1L, -2));
|
||||
XCTAssert(Interval(0, 0UL) == Interval(0, 0UL));
|
||||
XCTAssertFalse(Interval(0, 1UL) == Interval(1, 2UL));
|
||||
|
||||
XCTAssertEqual(Interval().hashCode(), 22070U);
|
||||
XCTAssertEqual(Interval(0, 0UL).hashCode(), 22103U);
|
||||
XCTAssertEqual(Interval(10, 2000UL).hashCode(), 24413U);
|
||||
|
||||
// Results for the interval test functions in this order:
|
||||
// startsBeforeDisjoint
|
||||
// startsBeforeNonDisjoint
|
||||
// startsAfter
|
||||
// startsAfterDisjoint
|
||||
// startsAfterNonDisjoint
|
||||
// disjoint
|
||||
// adjacent
|
||||
// properlyContains
|
||||
|
||||
typedef std::vector<bool> TestResults;
|
||||
struct TestEntry { size_t runningNumber; Interval interval1, interval2; TestResults results; };
|
||||
std::vector<TestEntry> testData = {
|
||||
// Extreme cases + invalid intervals.
|
||||
{ 0, Interval(), Interval(10, 20UL), { true, false, false, false, false, true, false, false } },
|
||||
{ 1, Interval(1, 1UL), Interval(1, 1UL), { false, true, false, false, false, false, false, true } },
|
||||
{ 2, Interval(10000, 10000UL), Interval(10000, 10000UL), { false, true, false, false, false, false, false, true } },
|
||||
{ 3, Interval(100, 10UL), Interval(100, 10UL), { false, false, false, true, false, true, false, true } },
|
||||
{ 4, Interval(100, 10UL), Interval(10, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 5, Interval(10, 100UL), Interval(100, 10UL), { false, true, false, false, false, false, false, true } },
|
||||
|
||||
// First starts before second. End varies.
|
||||
{ 20, Interval(10, 12UL), Interval(12, 100UL), { false, true, false, false, false, false, false, false } },
|
||||
{ 21, Interval(10, 12UL), Interval(13, 100UL), { true, false, false, false, false, true, true, false } },
|
||||
{ 22, Interval(10, 12UL), Interval(14, 100UL), { true, false, false, false, false, true, false, false } },
|
||||
{ 23, Interval(10, 13UL), Interval(12, 100UL), { false, true, false, false, false, false, false, false } },
|
||||
{ 24, Interval(10, 14UL), Interval(12, 100UL), { false, true, false, false, false, false, false, false } },
|
||||
{ 25, Interval(10, 99UL), Interval(12, 100UL), { false, true, false, false, false, false, false, false } },
|
||||
{ 26, Interval(10, 100UL), Interval(12, 100UL), { false, true, false, false, false, false, false, true } },
|
||||
{ 27, Interval(10, 101UL), Interval(12, 100UL), { false, true, false, false, false, false, false, true } },
|
||||
{ 28, Interval(10, 1000UL), Interval(12, 100UL), { false, true, false, false, false, false, false, true } },
|
||||
|
||||
// First and second start equal. End varies.
|
||||
{ 30, Interval(12, 12UL), Interval(12, 100UL), { false, true, false, false, false, false, false, false } },
|
||||
{ 31, Interval(12, 12UL), Interval(13, 100UL), { true, false, false, false, false, true, true, false } },
|
||||
{ 32, Interval(12, 12UL), Interval(14, 100UL), { true, false, false, false, false, true, false, false } },
|
||||
{ 33, Interval(12, 13UL), Interval(12, 100UL), { false, true, false, false, false, false, false, false } },
|
||||
{ 34, Interval(12, 14UL), Interval(12, 100UL), { false, true, false, false, false, false, false, false } },
|
||||
{ 35, Interval(12, 99UL), Interval(12, 100UL), { false, true, false, false, false, false, false, false } },
|
||||
{ 36, Interval(12, 100UL), Interval(12, 100UL), { false, true, false, false, false, false, false, true } },
|
||||
{ 37, Interval(12, 101UL), Interval(12, 100UL), { false, true, false, false, false, false, false, true } },
|
||||
{ 38, Interval(12, 1000UL), Interval(12, 100UL), { false, true, false, false, false, false, false, true } },
|
||||
|
||||
// First starts after second. End varies.
|
||||
{ 40, Interval(15, 12UL), Interval(12, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 41, Interval(15, 12UL), Interval(13, 100UL), { false, false, true, false, true, false, true, false } },
|
||||
{ 42, Interval(15, 12UL), Interval(14, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 43, Interval(15, 13UL), Interval(12, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 44, Interval(15, 14UL), Interval(12, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 45, Interval(15, 99UL), Interval(12, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 46, Interval(15, 100UL), Interval(12, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 47, Interval(15, 101UL), Interval(12, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 48, Interval(15, 1000UL), Interval(12, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
|
||||
// First ends before second. Start varies.
|
||||
{ 50, Interval(10, 90UL), Interval(20, 100UL), { false, true, false, false, false, false, false, false } },
|
||||
{ 51, Interval(19, 90UL), Interval(20, 100UL), { false, true, false, false, false, false, false, false } },
|
||||
{ 52, Interval(20, 90UL), Interval(20, 100UL), { false, true, false, false, false, false, false, false } },
|
||||
{ 53, Interval(21, 90UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 54, Interval(98, 90UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 55, Interval(99, 90UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 56, Interval(100, 90UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 57, Interval(101, 90UL), Interval(20, 100UL), { false, false, true, true, false, true, true, false } },
|
||||
{ 58, Interval(1000, 90UL), Interval(20, 100UL), { false, false, true, true, false, true, false, false } },
|
||||
|
||||
// First and second end equal. Start varies.
|
||||
{ 60, Interval(10, 100UL), Interval(20, 100UL), { false, true, false, false, false, false, false, true } },
|
||||
{ 61, Interval(19, 100UL), Interval(20, 100UL), { false, true, false, false, false, false, false, true } },
|
||||
{ 62, Interval(20, 100UL), Interval(20, 100UL), { false, true, false, false, false, false, false, true } },
|
||||
{ 63, Interval(21, 100UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 64, Interval(98, 100UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 65, Interval(99, 100UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 66, Interval(100, 100UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 67, Interval(101, 100UL), Interval(20, 100UL), { false, false, true, true, false, true, true, false } },
|
||||
{ 68, Interval(1000, 100UL), Interval(20, 100UL), { false, false, true, true, false, true, false, false } },
|
||||
|
||||
// First ends after second. Start varies.
|
||||
{ 70, Interval(10, 1000UL), Interval(20, 100UL), { false, true, false, false, false, false, false, true } },
|
||||
{ 71, Interval(19, 1000UL), Interval(20, 100UL), { false, true, false, false, false, false, false, true } },
|
||||
{ 72, Interval(20, 1000UL), Interval(20, 100UL), { false, true, false, false, false, false, false, true } },
|
||||
{ 73, Interval(21, 1000UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 74, Interval(98, 1000UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 75, Interval(99, 1000UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 76, Interval(100, 1000UL), Interval(20, 100UL), { false, false, true, false, true, false, false, false } },
|
||||
{ 77, Interval(101, 1000UL), Interval(20, 100UL), { false, false, true, true, false, true, true, false } },
|
||||
{ 78, Interval(1000, 1000UL), Interval(20, 100UL), { false, false, true, true, false, true, false, false } },
|
||||
|
||||
// It's possible to add more tests with borders that touch each other (e.g. first starts before/on/after second
|
||||
// and first ends directly before/after second. However, such cases are not handled differently in the Interval
|
||||
// class
|
||||
// (only adjacent intervals, where first ends directly before second starts and vice versa. So I ommitted them here.
|
||||
};
|
||||
|
||||
for (auto &entry : testData) {
|
||||
XCTAssert(entry.interval1.startsBeforeDisjoint(entry.interval2) == entry.results[0], @"entry: %zu",
|
||||
entry.runningNumber);
|
||||
XCTAssert(entry.interval1.startsBeforeNonDisjoint(entry.interval2) == entry.results[1], @"entry: %zu",
|
||||
entry.runningNumber);
|
||||
XCTAssert(entry.interval1.startsAfter(entry.interval2) == entry.results[2], @"entry: %zu", entry.runningNumber);
|
||||
XCTAssert(entry.interval1.startsAfterDisjoint(entry.interval2) == entry.results[3], @"entry: %zu",
|
||||
entry.runningNumber);
|
||||
XCTAssert(entry.interval1.startsAfterNonDisjoint(entry.interval2) == entry.results[4], @"entry: %zu",
|
||||
entry.runningNumber);
|
||||
XCTAssert(entry.interval1.disjoint(entry.interval2) == entry.results[5], @"entry: %zu", entry.runningNumber);
|
||||
XCTAssert(entry.interval1.adjacent(entry.interval2) == entry.results[6], @"entry: %zu", entry.runningNumber);
|
||||
XCTAssert(entry.interval1.properlyContains(entry.interval2) == entry.results[7], @"entry: %zu",
|
||||
entry.runningNumber);
|
||||
}
|
||||
|
||||
XCTAssert(Interval().Union(Interval(10, 100UL)) == Interval(-1L, 100));
|
||||
XCTAssert(Interval(10, 10UL).Union(Interval(10, 100UL)) == Interval(10, 100UL));
|
||||
XCTAssert(Interval(10, 11UL).Union(Interval(10, 100UL)) == Interval(10, 100UL));
|
||||
XCTAssert(Interval(10, 1000UL).Union(Interval(10, 100UL)) == Interval(10, 1000UL));
|
||||
XCTAssert(Interval(1000, 30UL).Union(Interval(10, 100UL)) == Interval(10, 100UL));
|
||||
XCTAssert(Interval(1000, 2000UL).Union(Interval(10, 100UL)) == Interval(10, 2000UL));
|
||||
XCTAssert(Interval(500, 2000UL).Union(Interval(10, 1000UL)) == Interval(10, 2000UL));
|
||||
|
||||
XCTAssert(Interval().intersection(Interval(10, 100UL)) == Interval(10, -2L));
|
||||
XCTAssert(Interval(10, 10UL).intersection(Interval(10, 100UL)) == Interval(10, 10UL));
|
||||
XCTAssert(Interval(10, 11UL).intersection(Interval(10, 100UL)) == Interval(10, 11UL));
|
||||
XCTAssert(Interval(10, 1000UL).intersection(Interval(10, 100UL)) == Interval(10, 100UL));
|
||||
XCTAssert(Interval(1000, 30UL).intersection(Interval(10, 100UL)) == Interval(1000, 30UL));
|
||||
XCTAssert(Interval(1000, 2000UL).intersection(Interval(10, 100UL)) == Interval(1000, 100UL));
|
||||
XCTAssert(Interval(500, 2000UL).intersection(Interval(10, 1000UL)) == Interval(500, 1000UL));
|
||||
|
||||
XCTAssert(Interval().toString() == "-1..-2");
|
||||
XCTAssert(Interval(10, 10UL).toString() == "10..10");
|
||||
XCTAssert(Interval(1000, 2000UL).toString() == "1000..2000");
|
||||
XCTAssert(Interval(500UL, INT_MAX).toString() == "500.." + std::to_string(INT_MAX));
|
||||
}
|
||||
|
||||
- (void)testIntervalSet {
|
||||
XCTAssertFalse(IntervalSet().isReadOnly());
|
||||
XCTAssert(IntervalSet().isEmpty());
|
||||
|
||||
IntervalSet set1;
|
||||
set1.setReadOnly(true);
|
||||
XCTAssert(set1.isReadOnly());
|
||||
|
||||
XCTAssert(IntervalSet() == IntervalSet::EMPTY_SET);
|
||||
|
||||
std::vector<Interval> intervals = { Interval(), Interval(10, 20UL), Interval(20, 100UL), Interval(1000, 2000UL) };
|
||||
IntervalSet set2(intervals);
|
||||
XCTAssertFalse(set2.isEmpty());
|
||||
XCTAssertFalse(set2.contains(9UL));
|
||||
XCTAssert(set2.contains(10UL));
|
||||
XCTAssert(set2.contains(20UL));
|
||||
XCTAssertTrue(set2.contains(22UL));
|
||||
XCTAssert(set2.contains(1111UL));
|
||||
XCTAssertFalse(set2.contains(10000UL));
|
||||
XCTAssertEqual(set2.getSingleElement(), Token::INVALID_TYPE);
|
||||
XCTAssertEqual(set2.getMinElement(), -1);
|
||||
XCTAssertEqual(set2.getMaxElement(), 2000);
|
||||
|
||||
IntervalSet set3(set2);
|
||||
XCTAssertFalse(set3.isEmpty());
|
||||
XCTAssertFalse(set3.contains(9UL));
|
||||
XCTAssert(set3.contains(10UL));
|
||||
XCTAssert(set3.contains(20UL));
|
||||
XCTAssertTrue(set3.contains(22UL));
|
||||
XCTAssert(set3.contains(1111UL));
|
||||
XCTAssertFalse(set3.contains(10000UL));
|
||||
XCTAssertEqual(set3.getSingleElement(), Token::INVALID_TYPE);
|
||||
XCTAssertEqual(set3.getMinElement(), 10);
|
||||
XCTAssertEqual(set3.getMaxElement(), 2000);
|
||||
|
||||
set3.add(Interval(100, 1000UL));
|
||||
XCTAssertEqual(set3.getMinElement(), 10);
|
||||
set3.add(Interval(9, 1000UL));
|
||||
XCTAssertEqual(set3.getMinElement(), 9);
|
||||
set3.add(Interval(1, 1UL));
|
||||
XCTAssertEqual(set3.getMinElement(), 1);
|
||||
|
||||
IntervalSet set4;
|
||||
set4.add(10);
|
||||
XCTAssertEqual(set4.getSingleElement(), 10);
|
||||
XCTAssertEqual(set4.getMinElement(), 10);
|
||||
XCTAssertEqual(set4.getMaxElement(), 10);
|
||||
|
||||
set4.clear();
|
||||
XCTAssert(set4.isEmpty());
|
||||
set4.add(Interval(10, 10UL));
|
||||
XCTAssertEqual(set4.getSingleElement(), 10);
|
||||
XCTAssertEqual(set4.getMinElement(), 10);
|
||||
XCTAssertEqual(set4.getMaxElement(), 10);
|
||||
set4.setReadOnly(true);
|
||||
try {
|
||||
set4.clear();
|
||||
XCTFail(@"Expected exception");
|
||||
} catch (IllegalStateException &e) {
|
||||
}
|
||||
|
||||
try {
|
||||
set4.setReadOnly(false);
|
||||
XCTFail(@"Expected exception");
|
||||
} catch (IllegalStateException &e) {
|
||||
}
|
||||
|
||||
try {
|
||||
set4 = IntervalSet::of(12345);
|
||||
XCTFail(@"Expected exception");
|
||||
} catch (IllegalStateException &e) {
|
||||
}
|
||||
|
||||
IntervalSet set5 = IntervalSet::of(12345);
|
||||
XCTAssertEqual(set5.getSingleElement(), 12345);
|
||||
XCTAssertEqual(set5.getMinElement(), 12345);
|
||||
XCTAssertEqual(set5.getMaxElement(), 12345);
|
||||
|
||||
IntervalSet set6(10, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50);
|
||||
XCTAssertEqual(set6.getMinElement(), 5);
|
||||
XCTAssertEqual(set6.getMaxElement(), 50);
|
||||
XCTAssertEqual(set6.size(), 10U);
|
||||
set6.add(12, 18);
|
||||
XCTAssertEqual(set6.size(), 16U); // (15, 15) replaced by (12, 18)
|
||||
set6.add(9, 33);
|
||||
XCTAssertEqual(set6.size(), 30U); // (10, 10), (12, 18), (20, 20), (25, 25) and (30, 30) replaced by (9, 33)
|
||||
|
||||
XCTAssert(IntervalSet(3, 1, 2, 10).Or(IntervalSet(3, 1, 2, 5)) == IntervalSet(4, 1, 2, 5, 10));
|
||||
XCTAssert(IntervalSet({ Interval(2, 10UL) }).Or(IntervalSet({ Interval(5, 8UL) })) == IntervalSet({ Interval(2, 10UL) }));
|
||||
|
||||
XCTAssert(IntervalSet::of(1, 10).complement(IntervalSet::of(7, 55)) == IntervalSet::of(11, 55));
|
||||
XCTAssert(IntervalSet::of(1, 10).complement(IntervalSet::of(20, 55)) == IntervalSet::of(20, 55));
|
||||
XCTAssert(IntervalSet::of(1, 10).complement(IntervalSet::of(5, 6)) == IntervalSet::EMPTY_SET);
|
||||
XCTAssert(IntervalSet::of(15, 20).complement(IntervalSet::of(7, 55)) ==
|
||||
IntervalSet({ Interval(7, 14UL), Interval(21, 55UL) }));
|
||||
XCTAssert(IntervalSet({ Interval(1, 10UL), Interval(30, 35UL) }).complement(IntervalSet::of(7, 55)) ==
|
||||
IntervalSet({ Interval(11, 29UL), Interval(36, 55UL) }));
|
||||
|
||||
XCTAssert(IntervalSet::of(1, 10).And(IntervalSet::of(7, 55)) == IntervalSet::of(7, 10));
|
||||
XCTAssert(IntervalSet::of(1, 10).And(IntervalSet::of(20, 55)) == IntervalSet::EMPTY_SET);
|
||||
XCTAssert(IntervalSet::of(1, 10).And(IntervalSet::of(5, 6)) == IntervalSet::of(5, 6));
|
||||
XCTAssert(IntervalSet::of(15, 20).And(IntervalSet::of(7, 55)) == IntervalSet::of(15, 20));
|
||||
|
||||
XCTAssert(IntervalSet::of(1, 10).subtract(IntervalSet::of(7, 55)) == IntervalSet::of(1, 6));
|
||||
XCTAssert(IntervalSet::of(1, 10).subtract(IntervalSet::of(20, 55)) == IntervalSet::of(1, 10));
|
||||
XCTAssert(IntervalSet::of(1, 10).subtract(IntervalSet::of(5, 6)) ==
|
||||
IntervalSet({ Interval(1, 4UL), Interval(7, 10UL) }));
|
||||
XCTAssert(IntervalSet::of(15, 20).subtract(IntervalSet::of(7, 55)) == IntervalSet::EMPTY_SET);
|
||||
}
|
||||
|
||||
@end
|
||||
@ -0,0 +1,57 @@
|
||||
/*
|
||||
* [The "BSD license"]
|
||||
* Copyright (c) 2015 Dan McLaughlin
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions
|
||||
* are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright
|
||||
* notice, this list of conditions and the following disclaimer.
|
||||
* 2. Redistributions in binary form must reproduce the above copyright
|
||||
* notice, this list of conditions and the following disclaimer in the
|
||||
* documentation and/or other materials provided with the distribution.
|
||||
* 3. The name of the author may not be used to endorse or promote products
|
||||
* derived from this software without specific prior written permission.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#import <XCTest/XCTest.h>
|
||||
|
||||
#include "ParserATNSimulator.h"
|
||||
#include "DFA.h"
|
||||
#include "ATN.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
using namespace antlr4;
|
||||
|
||||
@interface antlrcpp_Tests : XCTestCase
|
||||
|
||||
@end
|
||||
|
||||
@implementation antlrcpp_Tests
|
||||
|
||||
- (void)setUp {
|
||||
[super setUp];
|
||||
// Put setup code here. This method is called before the invocation of each test method in the class.
|
||||
}
|
||||
|
||||
- (void)tearDown {
|
||||
// Put teardown code here. This method is called after the invocation of each test method in the class.
|
||||
[super tearDown];
|
||||
}
|
||||
|
||||
@end
|
||||
@ -0,0 +1,585 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 46;
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
2707D9C22764C11300D99A45 /* libantlr4-runtime.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 2707D9BC2764C04C00D99A45 /* libantlr4-runtime.dylib */; };
|
||||
270925B11CDB455B00522D32 /* TLexer.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27A23EA11CC2A8D60036D8A3 /* TLexer.cpp */; };
|
||||
2747A7131CA6C46C0030247B /* InputHandlingTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = 2747A7121CA6C46C0030247B /* InputHandlingTests.mm */; };
|
||||
274FC6D91CA96B6C008D4374 /* MiscClassTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = 274FC6D81CA96B6C008D4374 /* MiscClassTests.mm */; };
|
||||
27C66A6A1C9591280021E494 /* main.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27C66A691C9591280021E494 /* main.cpp */; };
|
||||
27C6E1801C972FFC0079AF06 /* TParser.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27C6E1741C972FFC0079AF06 /* TParser.cpp */; };
|
||||
27C6E1811C972FFC0079AF06 /* TParserBaseListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27C6E1771C972FFC0079AF06 /* TParserBaseListener.cpp */; };
|
||||
27C6E1821C972FFC0079AF06 /* TParserBaseVisitor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27C6E1791C972FFC0079AF06 /* TParserBaseVisitor.cpp */; };
|
||||
27C6E1831C972FFC0079AF06 /* TParserListener.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27C6E17B1C972FFC0079AF06 /* TParserListener.cpp */; };
|
||||
27C6E1841C972FFC0079AF06 /* TParserVisitor.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 27C6E17D1C972FFC0079AF06 /* TParserVisitor.cpp */; };
|
||||
37F1356D1B4AC02800E0CACF /* antlrcpp_Tests.mm in Sources */ = {isa = PBXBuildFile; fileRef = 37F1356C1B4AC02800E0CACF /* antlrcpp_Tests.mm */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
2707D9BB2764C04C00D99A45 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 2707D9B52764C04C00D99A45 /* antlrcpp.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 37D727AA1867AF1E007B6D10;
|
||||
remoteInfo = antlr4;
|
||||
};
|
||||
2707D9BD2764C04C00D99A45 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 2707D9B52764C04C00D99A45 /* antlrcpp.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 37C147171B4D5A04008EDDDB;
|
||||
remoteInfo = antlr4_static;
|
||||
};
|
||||
2707D9BF2764C04C00D99A45 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 2707D9B52764C04C00D99A45 /* antlrcpp.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 270C67F01CDB4F1E00116E17;
|
||||
remoteInfo = antlr4_ios;
|
||||
};
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
27C66A651C9591280021E494 /* CopyFiles */ = {
|
||||
isa = PBXCopyFilesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
dstPath = /usr/share/man/man1/;
|
||||
dstSubfolderSpec = 0;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 1;
|
||||
};
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
2707D9B52764C04C00D99A45 /* antlrcpp.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = antlrcpp.xcodeproj; path = ../../runtime/antlrcpp.xcodeproj; sourceTree = "<group>"; };
|
||||
2747A7121CA6C46C0030247B /* InputHandlingTests.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = InputHandlingTests.mm; sourceTree = "<group>"; wrapsLines = 0; };
|
||||
274FC6D81CA96B6C008D4374 /* MiscClassTests.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MiscClassTests.mm; sourceTree = "<group>"; wrapsLines = 0; };
|
||||
27874F1D1CCB7A0700AF1C53 /* CoreFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreFoundation.framework; path = System/Library/Frameworks/CoreFoundation.framework; sourceTree = SDKROOT; };
|
||||
27A23EA11CC2A8D60036D8A3 /* TLexer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TLexer.cpp; path = ../generated/TLexer.cpp; sourceTree = "<group>"; wrapsLines = 0; };
|
||||
27A23EA21CC2A8D60036D8A3 /* TLexer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TLexer.h; path = ../generated/TLexer.h; sourceTree = "<group>"; };
|
||||
27C66A671C9591280021E494 /* antlr4-cpp-demo */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "antlr4-cpp-demo"; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
27C66A691C9591280021E494 /* main.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = main.cpp; sourceTree = "<group>"; wrapsLines = 0; };
|
||||
27C66A731C9592400021E494 /* TLexer.g4 */ = {isa = PBXFileReference; lastKnownFileType = text; name = TLexer.g4; path = ../../TLexer.g4; sourceTree = "<group>"; };
|
||||
27C66A741C9592400021E494 /* TParser.g4 */ = {isa = PBXFileReference; lastKnownFileType = text; name = TParser.g4; path = ../../TParser.g4; sourceTree = "<group>"; };
|
||||
27C6E1741C972FFC0079AF06 /* TParser.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TParser.cpp; path = ../generated/TParser.cpp; sourceTree = "<group>"; wrapsLines = 0; };
|
||||
27C6E1751C972FFC0079AF06 /* TParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TParser.h; path = ../generated/TParser.h; sourceTree = "<group>"; wrapsLines = 0; };
|
||||
27C6E1771C972FFC0079AF06 /* TParserBaseListener.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TParserBaseListener.cpp; path = ../generated/TParserBaseListener.cpp; sourceTree = "<group>"; };
|
||||
27C6E1781C972FFC0079AF06 /* TParserBaseListener.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TParserBaseListener.h; path = ../generated/TParserBaseListener.h; sourceTree = "<group>"; };
|
||||
27C6E1791C972FFC0079AF06 /* TParserBaseVisitor.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TParserBaseVisitor.cpp; path = ../generated/TParserBaseVisitor.cpp; sourceTree = "<group>"; };
|
||||
27C6E17B1C972FFC0079AF06 /* TParserListener.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TParserListener.cpp; path = ../generated/TParserListener.cpp; sourceTree = "<group>"; };
|
||||
27C6E17C1C972FFC0079AF06 /* TParserListener.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TParserListener.h; path = ../generated/TParserListener.h; sourceTree = "<group>"; };
|
||||
27C6E17D1C972FFC0079AF06 /* TParserVisitor.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = TParserVisitor.cpp; path = ../generated/TParserVisitor.cpp; sourceTree = "<group>"; };
|
||||
27C6E1851C97322F0079AF06 /* TParserBaseVisitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TParserBaseVisitor.h; path = ../generated/TParserBaseVisitor.h; sourceTree = "<group>"; wrapsLines = 0; };
|
||||
27C6E1861C97322F0079AF06 /* TParserVisitor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TParserVisitor.h; path = ../generated/TParserVisitor.h; sourceTree = "<group>"; };
|
||||
37F135681B4AC02800E0CACF /* antlrcpp Tests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "antlrcpp Tests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
37F1356B1B4AC02800E0CACF /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
37F1356C1B4AC02800E0CACF /* antlrcpp_Tests.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = antlrcpp_Tests.mm; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
27C66A641C9591280021E494 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
2707D9C22764C11300D99A45 /* libantlr4-runtime.dylib in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
37F135651B4AC02800E0CACF /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
2707D9B62764C04C00D99A45 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
2707D9BC2764C04C00D99A45 /* libantlr4-runtime.dylib */,
|
||||
2707D9BE2764C04C00D99A45 /* libantlr4-runtime.a */,
|
||||
2707D9C02764C04C00D99A45 /* antlr4_ios.framework */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
2707D9C12764C11300D99A45 /* Frameworks */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
);
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
27874F221CCBB34200AF1C53 /* Linked Frameworks */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
27874F1D1CCB7A0700AF1C53 /* CoreFoundation.framework */,
|
||||
);
|
||||
name = "Linked Frameworks";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
27C66A5C1C958EB50021E494 /* generated */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
27A23EA11CC2A8D60036D8A3 /* TLexer.cpp */,
|
||||
27A23EA21CC2A8D60036D8A3 /* TLexer.h */,
|
||||
27C6E1741C972FFC0079AF06 /* TParser.cpp */,
|
||||
27C6E1751C972FFC0079AF06 /* TParser.h */,
|
||||
27C6E1771C972FFC0079AF06 /* TParserBaseListener.cpp */,
|
||||
27C6E1781C972FFC0079AF06 /* TParserBaseListener.h */,
|
||||
27C6E1791C972FFC0079AF06 /* TParserBaseVisitor.cpp */,
|
||||
27C6E1851C97322F0079AF06 /* TParserBaseVisitor.h */,
|
||||
27C6E17B1C972FFC0079AF06 /* TParserListener.cpp */,
|
||||
27C6E17C1C972FFC0079AF06 /* TParserListener.h */,
|
||||
27C6E17D1C972FFC0079AF06 /* TParserVisitor.cpp */,
|
||||
27C6E1861C97322F0079AF06 /* TParserVisitor.h */,
|
||||
);
|
||||
name = generated;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
27C66A681C9591280021E494 /* antlr4-cpp-demo */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
27C66A691C9591280021E494 /* main.cpp */,
|
||||
27C66A731C9592400021E494 /* TLexer.g4 */,
|
||||
27C66A741C9592400021E494 /* TParser.g4 */,
|
||||
);
|
||||
path = "antlr4-cpp-demo";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
37D727A11867AF1E007B6D10 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
2707D9B52764C04C00D99A45 /* antlrcpp.xcodeproj */,
|
||||
27C66A681C9591280021E494 /* antlr4-cpp-demo */,
|
||||
37F135691B4AC02800E0CACF /* antlrcpp Tests */,
|
||||
27C66A5C1C958EB50021E494 /* generated */,
|
||||
27874F221CCBB34200AF1C53 /* Linked Frameworks */,
|
||||
37D727AB1867AF1E007B6D10 /* Products */,
|
||||
2707D9C12764C11300D99A45 /* Frameworks */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
37D727AB1867AF1E007B6D10 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
37F135681B4AC02800E0CACF /* antlrcpp Tests.xctest */,
|
||||
27C66A671C9591280021E494 /* antlr4-cpp-demo */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
37F135691B4AC02800E0CACF /* antlrcpp Tests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
37F1356A1B4AC02800E0CACF /* Supporting Files */,
|
||||
37F1356C1B4AC02800E0CACF /* antlrcpp_Tests.mm */,
|
||||
2747A7121CA6C46C0030247B /* InputHandlingTests.mm */,
|
||||
274FC6D81CA96B6C008D4374 /* MiscClassTests.mm */,
|
||||
);
|
||||
path = "antlrcpp Tests";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
37F1356A1B4AC02800E0CACF /* Supporting Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
37F1356B1B4AC02800E0CACF /* Info.plist */,
|
||||
);
|
||||
name = "Supporting Files";
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
27C66A661C9591280021E494 /* antlr4-cpp-demo */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 27C66A6B1C9591280021E494 /* Build configuration list for PBXNativeTarget "antlr4-cpp-demo" */;
|
||||
buildPhases = (
|
||||
27C66A721C9591EF0021E494 /* Generate Parser */,
|
||||
27C66A631C9591280021E494 /* Sources */,
|
||||
27C66A641C9591280021E494 /* Frameworks */,
|
||||
27C66A651C9591280021E494 /* CopyFiles */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = "antlr4-cpp-demo";
|
||||
productName = "antlr4-cpp-demo";
|
||||
productReference = 27C66A671C9591280021E494 /* antlr4-cpp-demo */;
|
||||
productType = "com.apple.product-type.tool";
|
||||
};
|
||||
37F135671B4AC02800E0CACF /* antlrcpp Tests */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 37F135731B4AC02800E0CACF /* Build configuration list for PBXNativeTarget "antlrcpp Tests" */;
|
||||
buildPhases = (
|
||||
37F135641B4AC02800E0CACF /* Sources */,
|
||||
37F135651B4AC02800E0CACF /* Frameworks */,
|
||||
37F135661B4AC02800E0CACF /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = "antlrcpp Tests";
|
||||
productName = "antlrcpp Tests";
|
||||
productReference = 37F135681B4AC02800E0CACF /* antlrcpp Tests.xctest */;
|
||||
productType = "com.apple.product-type.bundle.unit-test";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
37D727A21867AF1E007B6D10 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastUpgradeCheck = 1010;
|
||||
ORGANIZATIONNAME = "ANTLR4 Project";
|
||||
TargetAttributes = {
|
||||
27C66A661C9591280021E494 = {
|
||||
CreatedOnToolsVersion = 7.2.1;
|
||||
};
|
||||
37F135671B4AC02800E0CACF = {
|
||||
CreatedOnToolsVersion = 6.3.2;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = 37D727A51867AF1E007B6D10 /* Build configuration list for PBXProject "antlrcpp-demo" */;
|
||||
compatibilityVersion = "Xcode 3.2";
|
||||
developmentRegion = English;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
English,
|
||||
en,
|
||||
);
|
||||
mainGroup = 37D727A11867AF1E007B6D10;
|
||||
productRefGroup = 37D727AB1867AF1E007B6D10 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectReferences = (
|
||||
{
|
||||
ProductGroup = 2707D9B62764C04C00D99A45 /* Products */;
|
||||
ProjectRef = 2707D9B52764C04C00D99A45 /* antlrcpp.xcodeproj */;
|
||||
},
|
||||
);
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
37F135671B4AC02800E0CACF /* antlrcpp Tests */,
|
||||
27C66A661C9591280021E494 /* antlr4-cpp-demo */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXReferenceProxy section */
|
||||
2707D9BC2764C04C00D99A45 /* libantlr4-runtime.dylib */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = "compiled.mach-o.dylib";
|
||||
path = "libantlr4-runtime.dylib";
|
||||
remoteRef = 2707D9BB2764C04C00D99A45 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
2707D9BE2764C04C00D99A45 /* libantlr4-runtime.a */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = archive.ar;
|
||||
path = "libantlr4-runtime.a";
|
||||
remoteRef = 2707D9BD2764C04C00D99A45 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
2707D9C02764C04C00D99A45 /* antlr4_ios.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = antlr4_ios.framework;
|
||||
remoteRef = 2707D9BF2764C04C00D99A45 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
/* End PBXReferenceProxy section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
37F135661B4AC02800E0CACF /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXShellScriptBuildPhase section */
|
||||
27C66A721C9591EF0021E494 /* Generate Parser */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
inputPaths = (
|
||||
);
|
||||
name = "Generate Parser";
|
||||
outputPaths = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "pushd ..\nif [ TParser.g4 -nt generated/TParser.cpp -o TLexer.g4 -nt generated/TLexer.cpp ]; then\n./generate.sh;\nfi\npopd\n";
|
||||
showEnvVarsInLog = 0;
|
||||
};
|
||||
/* End PBXShellScriptBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
27C66A631C9591280021E494 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
27C66A6A1C9591280021E494 /* main.cpp in Sources */,
|
||||
27C6E1821C972FFC0079AF06 /* TParserBaseVisitor.cpp in Sources */,
|
||||
270925B11CDB455B00522D32 /* TLexer.cpp in Sources */,
|
||||
27C6E1831C972FFC0079AF06 /* TParserListener.cpp in Sources */,
|
||||
27C6E1811C972FFC0079AF06 /* TParserBaseListener.cpp in Sources */,
|
||||
27C6E1841C972FFC0079AF06 /* TParserVisitor.cpp in Sources */,
|
||||
27C6E1801C972FFC0079AF06 /* TParser.cpp in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
37F135641B4AC02800E0CACF /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
37F1356D1B4AC02800E0CACF /* antlrcpp_Tests.mm in Sources */,
|
||||
2747A7131CA6C46C0030247B /* InputHandlingTests.mm in Sources */,
|
||||
274FC6D91CA96B6C008D4374 /* MiscClassTests.mm in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
27C66A6C1C9591280021E494 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CODE_SIGN_IDENTITY = "-";
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
MTL_ENABLE_DEBUG_INFO = YES;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
27C66A6D1C9591280021E494 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CODE_SIGN_IDENTITY = "-";
|
||||
COPY_PHASE_STRIP = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
37D727B51867AF1E007B6D10 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "c++17";
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu99;
|
||||
GCC_DYNAMIC_NO_PIC = NO;
|
||||
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_OPTIMIZATION_LEVEL = 0;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = (
|
||||
"DEBUG=1",
|
||||
"$(inherited)",
|
||||
);
|
||||
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||
GCC_WARN_SIGN_COMPARE = YES;
|
||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_PARAMETER = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
HEADER_SEARCH_PATHS = (
|
||||
../../runtime/src/tree/pattern,
|
||||
../../runtime/src/tree,
|
||||
../../runtime/src/support,
|
||||
../../runtime/src/misc,
|
||||
../../runtime/src/dfa,
|
||||
../../runtime/src/atn,
|
||||
../../runtime/src,
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 11.1;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = macosx;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
37D727B61867AF1E007B6D10 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||
CLANG_CXX_LANGUAGE_STANDARD = "c++17";
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_EMPTY_BODY = YES;
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = YES;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu99;
|
||||
GCC_ENABLE_OBJC_EXCEPTIONS = YES;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
|
||||
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
|
||||
GCC_WARN_SIGN_COMPARE = YES;
|
||||
GCC_WARN_UNDECLARED_SELECTOR = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_PARAMETER = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
HEADER_SEARCH_PATHS = (
|
||||
../../runtime/src/tree/pattern,
|
||||
../../runtime/src/tree,
|
||||
../../runtime/src/support,
|
||||
../../runtime/src/misc,
|
||||
../../runtime/src/dfa,
|
||||
../../runtime/src/atn,
|
||||
../../runtime/src,
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 11.1;
|
||||
SDKROOT = macosx;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
37F135711B4AC02800E0CACF /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
FRAMEWORK_SEARCH_PATHS = (
|
||||
"$(DEVELOPER_FRAMEWORKS_DIR)",
|
||||
"$(inherited)",
|
||||
);
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_PREPROCESSOR_DEFINITIONS = (
|
||||
"DEBUG=1",
|
||||
"$(inherited)",
|
||||
);
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
INFOPLIST_FILE = "antlrcpp Tests/Info.plist";
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks";
|
||||
MTL_ENABLE_DEBUG_INFO = YES;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = "com.antlr.$(PRODUCT_NAME:rfc1034identifier)";
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
37F135721B4AC02800E0CACF /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
FRAMEWORK_SEARCH_PATHS = (
|
||||
"$(DEVELOPER_FRAMEWORKS_DIR)",
|
||||
"$(inherited)",
|
||||
);
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
INFOPLIST_FILE = "antlrcpp Tests/Info.plist";
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks @loader_path/../Frameworks";
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = "com.antlr.$(PRODUCT_NAME:rfc1034identifier)";
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
27C66A6B1C9591280021E494 /* Build configuration list for PBXNativeTarget "antlr4-cpp-demo" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
27C66A6C1C9591280021E494 /* Debug */,
|
||||
27C66A6D1C9591280021E494 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
37D727A51867AF1E007B6D10 /* Build configuration list for PBXProject "antlrcpp-demo" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
37D727B51867AF1E007B6D10 /* Debug */,
|
||||
37D727B61867AF1E007B6D10 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
37F135731B4AC02800E0CACF /* Build configuration list for PBXNativeTarget "antlrcpp Tests" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
37F135711B4AC02800E0CACF /* Debug */,
|
||||
37F135721B4AC02800E0CACF /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
};
|
||||
rootObject = 37D727A21867AF1E007B6D10 /* Project object */;
|
||||
}
|
||||
@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "self:">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>IDEDidComputeMac32BitWarning</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@ -0,0 +1,102 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1010"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "27C66A661C9591280021E494"
|
||||
BuildableName = "antlr4-cpp-demo"
|
||||
BlueprintName = "antlr4-cpp-demo"
|
||||
ReferencedContainer = "container:antlrcpp-demo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
codeCoverageEnabled = "YES"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "37F135671B4AC02800E0CACF"
|
||||
BuildableName = "antlrcpp Tests.xctest"
|
||||
BlueprintName = "antlrcpp Tests"
|
||||
ReferencedContainer = "container:antlrcpp-demo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "27C66A661C9591280021E494"
|
||||
BuildableName = "antlr4-cpp-demo"
|
||||
BlueprintName = "antlr4-cpp-demo"
|
||||
ReferencedContainer = "container:antlrcpp-demo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "27C66A661C9591280021E494"
|
||||
BuildableName = "antlr4-cpp-demo"
|
||||
BlueprintName = "antlr4-cpp-demo"
|
||||
ReferencedContainer = "container:antlrcpp-demo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "27C66A661C9591280021E494"
|
||||
BuildableName = "antlr4-cpp-demo"
|
||||
BlueprintName = "antlr4-cpp-demo"
|
||||
ReferencedContainer = "container:antlrcpp-demo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@ -0,0 +1,56 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1010"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "37F135671B4AC02800E0CACF"
|
||||
BuildableName = "antlrcpp Tests.xctest"
|
||||
BlueprintName = "antlrcpp Tests"
|
||||
ReferencedContainer = "container:antlrcpp-demo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
43
antlr/antlr4-runtime-4.12.0/demo/Mac/build.sh
Executable file
43
antlr/antlr4-runtime-4.12.0/demo/Mac/build.sh
Executable file
@ -0,0 +1,43 @@
|
||||
#!/bin/sh
|
||||
# [The "BSD license"]
|
||||
# Copyright (c) 2013 Terence Parr
|
||||
# Copyright (c) 2013 Dan McLaughlin
|
||||
# All rights reserved.
|
||||
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions
|
||||
# are met:
|
||||
|
||||
# 1. Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
# 2. Redistributions in binary form must reproduce the above copyright
|
||||
# notice, this list of conditions and the following disclaimer in the
|
||||
# documentation and/or other materials provided with the distribution.
|
||||
# 3. The name of the author may not be used to endorse or promote products
|
||||
# derived from this software without specific prior written permission.
|
||||
|
||||
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
|
||||
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
|
||||
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
|
||||
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
CURRENT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
|
||||
ANTLRCPP_XCODEPROJ="${CURRENT_DIR}/antlrcpp.xcodeproj"
|
||||
|
||||
# OS X
|
||||
xcrun xcodebuild -project ${ANTLRCPP_XCODEPROJ} -target antlrcpp -configuration Release $@
|
||||
xcrun xcodebuild -project ${ANTLRCPP_XCODEPROJ} -target antlrcpp -configuration Debug $@
|
||||
|
||||
# iOS
|
||||
#xcrun xcodebuild -project ${ANTLRCPP_XCODEPROJ} -target antlrcpp_iphone -configuration Release -sdk iphoneos $@
|
||||
#xcrun xcodebuild -project ${ANTLRCPP_XCODEPROJ} -target antlrcpp_iphone -configuration Debug -sdk iphoneos $@
|
||||
#xcrun xcodebuild -project ${ANTLRCPP_XCODEPROJ} -target antlrcpp_iphone_sim -configuration Release -sdk iphonesimulator $@
|
||||
#xcrun xcodebuild -project ${ANTLRCPP_XCODEPROJ} -target antlrcpp_iphone_sim -configuration Debug -sdk iphonesimulator $@
|
||||
|
||||
13
antlr/antlr4-runtime-4.12.0/demo/README.md
Normal file
13
antlr/antlr4-runtime-4.12.0/demo/README.md
Normal file
@ -0,0 +1,13 @@
|
||||
## Demo application for the ANTLR 4 C++ target
|
||||
|
||||
This demo app shows how to build the ANTLR runtime both as dynamic and static library and how to use a parser generated from a simple demo grammar.
|
||||
|
||||
A few steps are necessary to get this to work:
|
||||
|
||||
- Download the current ANTLR jar and place it in this folder.
|
||||
- Open the generation script for your platform (generate.cmd for Windows, generate.sh for *nix/OSX) and update the LOCATION var to the actual name of the jar you downloaded.
|
||||
- Run the generation script. This will generate a test parser + lexer, along with listener + visitor classes in a subfolder named "generated". This is where the demo application looks for these files.
|
||||
- Open the project in the folder that matches your system.
|
||||
- Compile and run.
|
||||
|
||||
Compilation is done as described in the [runtime/cpp/readme.md](../README.md) file.
|
||||
86
antlr/antlr4-runtime-4.12.0/demo/TLexer.g4
Normal file
86
antlr/antlr4-runtime-4.12.0/demo/TLexer.g4
Normal file
@ -0,0 +1,86 @@
|
||||
lexer grammar TLexer;
|
||||
|
||||
// These are all supported lexer sections:
|
||||
|
||||
// Lexer file header. Appears at the top of h + cpp files. Use e.g. for copyrights.
|
||||
@lexer::header {/* lexer header section */}
|
||||
|
||||
// Appears before any #include in h + cpp files.
|
||||
@lexer::preinclude {/* lexer precinclude section */}
|
||||
|
||||
// Follows directly after the standard #includes in h + cpp files.
|
||||
@lexer::postinclude {
|
||||
/* lexer postinclude section */
|
||||
#ifndef _WIN32
|
||||
#pragma GCC diagnostic ignored "-Wunused-parameter"
|
||||
#endif
|
||||
}
|
||||
|
||||
// Directly preceds the lexer class declaration in the h file (e.g. for additional types etc.).
|
||||
@lexer::context {/* lexer context section */}
|
||||
|
||||
// Appears in the public part of the lexer in the h file.
|
||||
@lexer::members {/* public lexer declarations section */
|
||||
bool canTestFoo() { return true; }
|
||||
bool isItFoo() { return true; }
|
||||
bool isItBar() { return true; }
|
||||
|
||||
void myFooLexerAction() { /* do something*/ };
|
||||
void myBarLexerAction() { /* do something*/ };
|
||||
}
|
||||
|
||||
// Appears in the private part of the lexer in the h file.
|
||||
@lexer::declarations {/* private lexer declarations/members section */}
|
||||
|
||||
// Appears in line with the other class member definitions in the cpp file.
|
||||
@lexer::definitions {/* lexer definitions section */}
|
||||
|
||||
channels { CommentsChannel, DirectiveChannel }
|
||||
|
||||
tokens {
|
||||
DUMMY
|
||||
}
|
||||
|
||||
Return: 'return';
|
||||
Continue: 'continue';
|
||||
|
||||
INT: Digit+;
|
||||
Digit: [0-9];
|
||||
|
||||
ID: LETTER (LETTER | '0'..'9')*;
|
||||
fragment LETTER : [a-zA-Z\u0080-\u{10FFFF}];
|
||||
|
||||
LessThan: '<';
|
||||
GreaterThan: '>';
|
||||
Equal: '=';
|
||||
And: 'and';
|
||||
|
||||
Colon: ':';
|
||||
Semicolon: ';';
|
||||
Plus: '+';
|
||||
Minus: '-';
|
||||
Star: '*';
|
||||
OpenPar: '(';
|
||||
ClosePar: ')';
|
||||
OpenCurly: '{' -> pushMode(Mode1);
|
||||
CloseCurly: '}' -> popMode;
|
||||
QuestionMark: '?';
|
||||
Comma: ',' -> skip;
|
||||
Dollar: '$' -> more, mode(Mode1);
|
||||
Ampersand: '&' -> type(DUMMY);
|
||||
|
||||
String: '"' .*? '"';
|
||||
Foo: {canTestFoo()}? 'foo' {isItFoo()}? { myFooLexerAction(); };
|
||||
Bar: 'bar' {isItBar()}? { myBarLexerAction(); };
|
||||
Any: Foo Dot Bar? DotDot Baz;
|
||||
|
||||
Comment : '#' ~[\r\n]* '\r'? '\n' -> channel(CommentsChannel);
|
||||
WS: [ \t\r\n]+ -> channel(99);
|
||||
|
||||
fragment Baz: 'Baz';
|
||||
|
||||
mode Mode1;
|
||||
Dot: '.';
|
||||
|
||||
mode Mode2;
|
||||
DotDot: '..';
|
||||
119
antlr/antlr4-runtime-4.12.0/demo/TParser.g4
Normal file
119
antlr/antlr4-runtime-4.12.0/demo/TParser.g4
Normal file
@ -0,0 +1,119 @@
|
||||
parser grammar TParser;
|
||||
|
||||
options {
|
||||
tokenVocab = TLexer;
|
||||
}
|
||||
|
||||
// These are all supported parser sections:
|
||||
|
||||
// Parser file header. Appears at the top in all parser related files. Use e.g. for copyrights.
|
||||
@parser::header {/* parser/listener/visitor header section */}
|
||||
|
||||
// Appears before any #include in h + cpp files.
|
||||
@parser::preinclude {/* parser precinclude section */}
|
||||
|
||||
// Follows directly after the standard #includes in h + cpp files.
|
||||
@parser::postinclude {
|
||||
/* parser postinclude section */
|
||||
#ifndef _WIN32
|
||||
#pragma GCC diagnostic ignored "-Wunused-parameter"
|
||||
#endif
|
||||
}
|
||||
|
||||
// Directly preceeds the parser class declaration in the h file (e.g. for additional types etc.).
|
||||
@parser::context {/* parser context section */}
|
||||
|
||||
// Appears in the private part of the parser in the h file.
|
||||
// The function bodies could also appear in the definitions section, but I want to maximize
|
||||
// Java compatibility, so we can also create a Java parser from this grammar.
|
||||
// Still, some tweaking is necessary after the Java file generation (e.g. bool -> boolean).
|
||||
@parser::members {
|
||||
/* public parser declarations/members section */
|
||||
bool myAction() { return true; }
|
||||
bool doesItBlend() { return true; }
|
||||
void cleanUp() {}
|
||||
void doInit() {}
|
||||
void doAfter() {}
|
||||
}
|
||||
|
||||
// Appears in the public part of the parser in the h file.
|
||||
@parser::declarations {/* private parser declarations section */}
|
||||
|
||||
// Appears in line with the other class member definitions in the cpp file.
|
||||
@parser::definitions {/* parser definitions section */}
|
||||
|
||||
// Additionally there are similar sections for (base)listener and (base)visitor files.
|
||||
@parser::listenerpreinclude {/* listener preinclude section */}
|
||||
@parser::listenerpostinclude {/* listener postinclude section */}
|
||||
@parser::listenerdeclarations {/* listener public declarations/members section */}
|
||||
@parser::listenermembers {/* listener private declarations/members section */}
|
||||
@parser::listenerdefinitions {/* listener definitions section */}
|
||||
|
||||
@parser::baselistenerpreinclude {/* base listener preinclude section */}
|
||||
@parser::baselistenerpostinclude {/* base listener postinclude section */}
|
||||
@parser::baselistenerdeclarations {/* base listener public declarations/members section */}
|
||||
@parser::baselistenermembers {/* base listener private declarations/members section */}
|
||||
@parser::baselistenerdefinitions {/* base listener definitions section */}
|
||||
|
||||
@parser::visitorpreinclude {/* visitor preinclude section */}
|
||||
@parser::visitorpostinclude {/* visitor postinclude section */}
|
||||
@parser::visitordeclarations {/* visitor public declarations/members section */}
|
||||
@parser::visitormembers {/* visitor private declarations/members section */}
|
||||
@parser::visitordefinitions {/* visitor definitions section */}
|
||||
|
||||
@parser::basevisitorpreinclude {/* base visitor preinclude section */}
|
||||
@parser::basevisitorpostinclude {/* base visitor postinclude section */}
|
||||
@parser::basevisitordeclarations {/* base visitor public declarations/members section */}
|
||||
@parser::basevisitormembers {/* base visitor private declarations/members section */}
|
||||
@parser::basevisitordefinitions {/* base visitor definitions section */}
|
||||
|
||||
// Actual grammar start.
|
||||
main: stat+ EOF;
|
||||
divide : ID (and_ GreaterThan)? {doesItBlend()}?;
|
||||
and_ @init{ doInit(); } @after { doAfter(); } : And ;
|
||||
|
||||
conquer:
|
||||
divide+
|
||||
| {doesItBlend()}? and_ { myAction(); }
|
||||
| ID (LessThan* divide)?? { $ID.text; }
|
||||
;
|
||||
|
||||
// Unused rule to demonstrate some of the special features.
|
||||
unused[double input = 111] returns [double calculated] locals [int _a, double _b, int _c] @init{ doInit(); } @after { doAfter(); } :
|
||||
stat
|
||||
;
|
||||
catch [...] {
|
||||
// Replaces the standard exception handling.
|
||||
}
|
||||
finally {
|
||||
cleanUp();
|
||||
}
|
||||
|
||||
unused2:
|
||||
(unused[1] .)+ (Colon | Semicolon | Plus)? ~Semicolon
|
||||
;
|
||||
|
||||
stat: expr Equal expr Semicolon
|
||||
| expr Semicolon
|
||||
;
|
||||
|
||||
expr: expr Star expr
|
||||
| expr Plus expr
|
||||
| OpenPar expr ClosePar
|
||||
| <assoc = right> expr QuestionMark expr Colon expr
|
||||
| <assoc = right> expr Equal expr
|
||||
| identifier = id
|
||||
| flowControl
|
||||
| INT
|
||||
| String
|
||||
;
|
||||
|
||||
flowControl:
|
||||
Return expr # Return
|
||||
| Continue # Continue
|
||||
;
|
||||
|
||||
id: ID;
|
||||
array : OpenCurly el += INT (Comma el += INT)* CloseCurly;
|
||||
idarray : OpenCurly element += id (Comma element += id)* CloseCurly;
|
||||
any: t = .;
|
||||
@ -0,0 +1,365 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug DLL|Win32">
|
||||
<Configuration>Debug DLL</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug DLL|x64">
|
||||
<Configuration>Debug DLL</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug Static|Win32">
|
||||
<Configuration>Debug Static</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug Static|x64">
|
||||
<Configuration>Debug Static</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release DLL|Win32">
|
||||
<Configuration>Release DLL</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release DLL|x64">
|
||||
<Configuration>Release DLL</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release Static|Win32">
|
||||
<Configuration>Release Static</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release Static|x64">
|
||||
<Configuration>Release Static</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectGuid>{24EC5104-7402-4C76-B66B-27ADBE062D68}</ProjectGuid>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
<RootNamespace>antlr4cppdemo</RootNamespace>
|
||||
<ProjectName>antlr4cpp-demo</ProjectName>
|
||||
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Static|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug DLL|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Static|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug DLL|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Static|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release DLL|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Static|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release DLL|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug Static|Win32'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug DLL|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug Static|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug DLL|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release Static|Win32'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release DLL|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release Static|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release DLL|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Static|Win32'">
|
||||
<LinkIncremental>true</LinkIncremental>
|
||||
<OutDir>$(SolutionDir)bin\vs-2022\$(PlatformTarget)\$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)obj\$(PlatformTarget)\$(Configuration)\$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug DLL|Win32'">
|
||||
<LinkIncremental>true</LinkIncremental>
|
||||
<OutDir>$(SolutionDir)bin\vs-2022\$(PlatformTarget)\$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)obj\$(PlatformTarget)\$(Configuration)\$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Static|x64'">
|
||||
<LinkIncremental>true</LinkIncremental>
|
||||
<OutDir>$(SolutionDir)bin\vs-2022\$(PlatformTarget)\$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)obj\$(PlatformTarget)\$(Configuration)\$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug DLL|x64'">
|
||||
<LinkIncremental>true</LinkIncremental>
|
||||
<OutDir>$(SolutionDir)bin\vs-2022\$(PlatformTarget)\$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)obj\$(PlatformTarget)\$(Configuration)\$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Static|Win32'">
|
||||
<LinkIncremental>false</LinkIncremental>
|
||||
<OutDir>$(SolutionDir)bin\vs-2022\$(PlatformTarget)\$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)obj\$(PlatformTarget)\$(Configuration)\$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release DLL|Win32'">
|
||||
<LinkIncremental>false</LinkIncremental>
|
||||
<OutDir>$(SolutionDir)bin\vs-2022\$(PlatformTarget)\$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)obj\$(PlatformTarget)\$(Configuration)\$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Static|x64'">
|
||||
<LinkIncremental>false</LinkIncremental>
|
||||
<OutDir>$(SolutionDir)bin\vs-2022\$(PlatformTarget)\$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)obj\$(PlatformTarget)\$(Configuration)\$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release DLL|x64'">
|
||||
<LinkIncremental>false</LinkIncremental>
|
||||
<OutDir>$(SolutionDir)bin\vs-2022\$(PlatformTarget)\$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)obj\$(PlatformTarget)\$(Configuration)\$(ProjectName)\</IntDir>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug Static|Win32'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>ANTLR4CPP_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<AdditionalIncludeDirectories>$(SolutionDir)..\generated;$(SolutionDir)..\..\runtime\src;$(SolutionDir)..\..\runtime\src\atn;$(SolutionDir)..\..\runtime\src\dfa;$(SolutionDir)..\..\runtime\src\misc;$(SolutionDir)..\..\runtime\src\support;$(SolutionDir)..\..\runtime\src\tree;$(SolutionDir)..\..\runtime\src\tree\xpath;$(SolutionDir)..\..\runtime\src\tree\pattern;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<ForcedIncludeFiles>
|
||||
</ForcedIncludeFiles>
|
||||
<DisableSpecificWarnings>4251</DisableSpecificWarnings>
|
||||
<MultiProcessorCompilation>true</MultiProcessorCompilation>
|
||||
<MinimalRebuild>false</MinimalRebuild>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug DLL|Win32'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<AdditionalIncludeDirectories>$(SolutionDir)..\generated;$(SolutionDir)..\..\runtime\src;$(SolutionDir)..\..\runtime\src\atn;$(SolutionDir)..\..\runtime\src\dfa;$(SolutionDir)..\..\runtime\src\misc;$(SolutionDir)..\..\runtime\src\support;$(SolutionDir)..\..\runtime\src\tree;$(SolutionDir)..\..\runtime\src\tree\xpath;$(SolutionDir)..\..\runtime\src\tree\pattern;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<ForcedIncludeFiles>
|
||||
</ForcedIncludeFiles>
|
||||
<DisableSpecificWarnings>4251</DisableSpecificWarnings>
|
||||
<MultiProcessorCompilation>true</MultiProcessorCompilation>
|
||||
<MinimalRebuild>false</MinimalRebuild>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug Static|x64'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>ANTLR4CPP_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<AdditionalIncludeDirectories>$(SolutionDir)..\generated;$(SolutionDir)..\..\runtime\src;$(SolutionDir)..\..\runtime\src\atn;$(SolutionDir)..\..\runtime\src\dfa;$(SolutionDir)..\..\runtime\src\misc;$(SolutionDir)..\..\runtime\src\support;$(SolutionDir)..\..\runtime\src\tree;$(SolutionDir)..\..\runtime\src\tree\xpath;$(SolutionDir)..\..\runtime\src\tree\pattern;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<ForcedIncludeFiles>
|
||||
</ForcedIncludeFiles>
|
||||
<DisableSpecificWarnings>4251</DisableSpecificWarnings>
|
||||
<MultiProcessorCompilation>true</MultiProcessorCompilation>
|
||||
<MinimalRebuild>false</MinimalRebuild>
|
||||
<LanguageStandard>stdcpp17</LanguageStandard>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug DLL|x64'">
|
||||
<ClCompile>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<AdditionalIncludeDirectories>$(SolutionDir)..\generated;$(SolutionDir)..\..\runtime\src;$(SolutionDir)..\..\runtime\src\atn;$(SolutionDir)..\..\runtime\src\dfa;$(SolutionDir)..\..\runtime\src\misc;$(SolutionDir)..\..\runtime\src\support;$(SolutionDir)..\..\runtime\src\tree;$(SolutionDir)..\..\runtime\src\tree\xpath;$(SolutionDir)..\..\runtime\src\tree\pattern;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<ForcedIncludeFiles>
|
||||
</ForcedIncludeFiles>
|
||||
<DisableSpecificWarnings>4251</DisableSpecificWarnings>
|
||||
<MultiProcessorCompilation>true</MultiProcessorCompilation>
|
||||
<MinimalRebuild>false</MinimalRebuild>
|
||||
<LanguageStandard>stdcpp17</LanguageStandard>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Static|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<PreprocessorDefinitions>ANTLR4CPP_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<AdditionalIncludeDirectories>$(SolutionDir)..\generated;$(SolutionDir)..\..\runtime\src;$(SolutionDir)..\..\runtime\src\atn;$(SolutionDir)..\..\runtime\src\dfa;$(SolutionDir)..\..\runtime\src\misc;$(SolutionDir)..\..\runtime\src\support;$(SolutionDir)..\..\runtime\src\tree;$(SolutionDir)..\..\runtime\src\tree\xpath;$(SolutionDir)..\..\runtime\src\tree\pattern;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<ForcedIncludeFiles>
|
||||
</ForcedIncludeFiles>
|
||||
<DisableSpecificWarnings>4251</DisableSpecificWarnings>
|
||||
<MultiProcessorCompilation>true</MultiProcessorCompilation>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release DLL|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<PreprocessorDefinitions>%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<AdditionalIncludeDirectories>$(SolutionDir)..\generated;$(SolutionDir)..\..\runtime\src;$(SolutionDir)..\..\runtime\src\atn;$(SolutionDir)..\..\runtime\src\dfa;$(SolutionDir)..\..\runtime\src\misc;$(SolutionDir)..\..\runtime\src\support;$(SolutionDir)..\..\runtime\src\tree;$(SolutionDir)..\..\runtime\src\tree\xpath;$(SolutionDir)..\..\runtime\src\tree\pattern;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<ForcedIncludeFiles>
|
||||
</ForcedIncludeFiles>
|
||||
<DisableSpecificWarnings>4251</DisableSpecificWarnings>
|
||||
<MultiProcessorCompilation>true</MultiProcessorCompilation>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Static|x64'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<PreprocessorDefinitions>ANTLR4CPP_STATIC;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<AdditionalIncludeDirectories>$(SolutionDir)..\generated;$(SolutionDir)..\..\runtime\src;$(SolutionDir)..\..\runtime\src\atn;$(SolutionDir)..\..\runtime\src\dfa;$(SolutionDir)..\..\runtime\src\misc;$(SolutionDir)..\..\runtime\src\support;$(SolutionDir)..\..\runtime\src\tree;$(SolutionDir)..\..\runtime\src\tree\xpath;$(SolutionDir)..\..\runtime\src\tree\pattern;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<ForcedIncludeFiles>
|
||||
</ForcedIncludeFiles>
|
||||
<DisableSpecificWarnings>4251</DisableSpecificWarnings>
|
||||
<MultiProcessorCompilation>true</MultiProcessorCompilation>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release DLL|x64'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<Optimization>MaxSpeed</Optimization>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<PreprocessorDefinitions>%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<AdditionalIncludeDirectories>$(SolutionDir)..\generated;$(SolutionDir)..\..\runtime\src;$(SolutionDir)..\..\runtime\src\atn;$(SolutionDir)..\..\runtime\src\dfa;$(SolutionDir)..\..\runtime\src\misc;$(SolutionDir)..\..\runtime\src\support;$(SolutionDir)..\..\runtime\src\tree;$(SolutionDir)..\..\runtime\src\tree\xpath;$(SolutionDir)..\..\runtime\src\tree\pattern;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<ForcedIncludeFiles>
|
||||
</ForcedIncludeFiles>
|
||||
<DisableSpecificWarnings>4251</DisableSpecificWarnings>
|
||||
<MultiProcessorCompilation>true</MultiProcessorCompilation>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="..\..\generated\TLexer.cpp" />
|
||||
<ClCompile Include="..\..\generated\TParser.cpp" />
|
||||
<ClCompile Include="..\..\generated\TParserBaseListener.cpp" />
|
||||
<ClCompile Include="..\..\generated\TParserBaseVisitor.cpp" />
|
||||
<ClCompile Include="..\..\generated\TParserListener.cpp" />
|
||||
<ClCompile Include="..\..\generated\TParserVisitor.cpp" />
|
||||
<ClCompile Include="main.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\..\generated\TLexer.h" />
|
||||
<ClInclude Include="..\..\generated\TParser.h" />
|
||||
<ClInclude Include="..\..\generated\TParserBaseListener.h" />
|
||||
<ClInclude Include="..\..\generated\TParserBaseVisitor.h" />
|
||||
<ClInclude Include="..\..\generated\TParserListener.h" />
|
||||
<ClInclude Include="..\..\generated\TParserVisitor.h" />
|
||||
<ClInclude Include="main.h" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\runtime\antlr4cpp-vs2022.vcxproj">
|
||||
<Project>{a9762991-1b57-4dce-90c0-ee42b96947be}</Project>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
||||
@ -0,0 +1,66 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup>
|
||||
<Filter Include="Source Files">
|
||||
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
|
||||
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
|
||||
</Filter>
|
||||
<Filter Include="Header Files">
|
||||
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
|
||||
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
|
||||
</Filter>
|
||||
<Filter Include="Resource Files">
|
||||
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
|
||||
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
|
||||
</Filter>
|
||||
<Filter Include="generated">
|
||||
<UniqueIdentifier>{ef397b7b-1192-4d44-93ed-fadaec7622e8}</UniqueIdentifier>
|
||||
</Filter>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="main.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="..\..\generated\TParser.cpp">
|
||||
<Filter>generated</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="..\..\generated\TParserBaseListener.cpp">
|
||||
<Filter>generated</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="..\..\generated\TParserBaseVisitor.cpp">
|
||||
<Filter>generated</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="..\..\generated\TParserListener.cpp">
|
||||
<Filter>generated</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="..\..\generated\TParserVisitor.cpp">
|
||||
<Filter>generated</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="..\..\generated\TLexer.cpp">
|
||||
<Filter>generated</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\..\generated\TLexer.h">
|
||||
<Filter>generated</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="..\..\generated\TParser.h">
|
||||
<Filter>generated</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="..\..\generated\TParserBaseListener.h">
|
||||
<Filter>generated</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="..\..\generated\TParserBaseVisitor.h">
|
||||
<Filter>generated</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="..\..\generated\TParserListener.h">
|
||||
<Filter>generated</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="..\..\generated\TParserVisitor.h">
|
||||
<Filter>generated</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="main.h">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@ -0,0 +1,39 @@
|
||||
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
|
||||
* Use of this file is governed by the BSD 3-clause license that
|
||||
* can be found in the LICENSE.txt file in the project root.
|
||||
*/
|
||||
|
||||
//
|
||||
// main.cpp
|
||||
// antlr4-cpp-demo
|
||||
//
|
||||
// Created by Mike Lischke on 13.03.16.
|
||||
//
|
||||
|
||||
#include <iostream>
|
||||
|
||||
#include "antlr4-runtime.h"
|
||||
#include "TLexer.h"
|
||||
#include "TParser.h"
|
||||
|
||||
#include <Windows.h>
|
||||
|
||||
#pragma execution_character_set("utf-8")
|
||||
|
||||
using namespace antlrcpptest;
|
||||
using namespace antlr4;
|
||||
|
||||
int main(int argc, const char * argv[]) {
|
||||
|
||||
ANTLRInputStream input("a = b + \"c\";(((x * d))) * e + f; a + (x * (y ? 0 : 1) + z);");
|
||||
TLexer lexer(&input);
|
||||
CommonTokenStream tokens(&lexer);
|
||||
|
||||
TParser parser(&tokens);
|
||||
tree::ParseTree *tree = parser.main();
|
||||
|
||||
auto s = tree->toStringTree(&parser);
|
||||
std::cout << "Parse Tree: " << s << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@ -0,0 +1,61 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.0.32014.148
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "antlr4cpp-vs2022", "..\..\runtime\antlr4cpp-vs2022.vcxproj", "{52618D4B-6EC4-49AD-8B83-52686244E8F3}"
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "antlr4cpp-demo", "antlr4-cpp-demo\antlr4-cpp-demo-vs2022.vcxproj", "{24EC5104-7402-4C76-B66B-27ADBE062D68}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug DLL|x64 = Debug DLL|x64
|
||||
Debug DLL|x86 = Debug DLL|x86
|
||||
Debug Static|x64 = Debug Static|x64
|
||||
Debug Static|x86 = Debug Static|x86
|
||||
Release DLL|x64 = Release DLL|x64
|
||||
Release DLL|x86 = Release DLL|x86
|
||||
Release Static|x64 = Release Static|x64
|
||||
Release Static|x86 = Release Static|x86
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Debug DLL|x64.ActiveCfg = Debug DLL|x64
|
||||
{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Debug DLL|x64.Build.0 = Debug DLL|x64
|
||||
{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Debug DLL|x86.ActiveCfg = Debug DLL|Win32
|
||||
{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Debug DLL|x86.Build.0 = Debug DLL|Win32
|
||||
{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Debug Static|x64.ActiveCfg = Debug Static|x64
|
||||
{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Debug Static|x64.Build.0 = Debug Static|x64
|
||||
{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Debug Static|x86.ActiveCfg = Debug Static|Win32
|
||||
{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Debug Static|x86.Build.0 = Debug Static|Win32
|
||||
{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Release DLL|x64.ActiveCfg = Release DLL|x64
|
||||
{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Release DLL|x64.Build.0 = Release DLL|x64
|
||||
{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Release DLL|x86.ActiveCfg = Release DLL|Win32
|
||||
{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Release DLL|x86.Build.0 = Release DLL|Win32
|
||||
{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Release Static|x64.ActiveCfg = Release Static|x64
|
||||
{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Release Static|x64.Build.0 = Release Static|x64
|
||||
{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Release Static|x86.ActiveCfg = Release Static|Win32
|
||||
{52618D4B-6EC4-49AD-8B83-52686244E8F3}.Release Static|x86.Build.0 = Release Static|Win32
|
||||
{24EC5104-7402-4C76-B66B-27ADBE062D68}.Debug DLL|x64.ActiveCfg = Debug DLL|x64
|
||||
{24EC5104-7402-4C76-B66B-27ADBE062D68}.Debug DLL|x64.Build.0 = Debug DLL|x64
|
||||
{24EC5104-7402-4C76-B66B-27ADBE062D68}.Debug DLL|x86.ActiveCfg = Debug DLL|Win32
|
||||
{24EC5104-7402-4C76-B66B-27ADBE062D68}.Debug DLL|x86.Build.0 = Debug DLL|Win32
|
||||
{24EC5104-7402-4C76-B66B-27ADBE062D68}.Debug Static|x64.ActiveCfg = Debug Static|x64
|
||||
{24EC5104-7402-4C76-B66B-27ADBE062D68}.Debug Static|x64.Build.0 = Debug Static|x64
|
||||
{24EC5104-7402-4C76-B66B-27ADBE062D68}.Debug Static|x86.ActiveCfg = Debug Static|Win32
|
||||
{24EC5104-7402-4C76-B66B-27ADBE062D68}.Debug Static|x86.Build.0 = Debug Static|Win32
|
||||
{24EC5104-7402-4C76-B66B-27ADBE062D68}.Release DLL|x64.ActiveCfg = Release DLL|x64
|
||||
{24EC5104-7402-4C76-B66B-27ADBE062D68}.Release DLL|x64.Build.0 = Release DLL|x64
|
||||
{24EC5104-7402-4C76-B66B-27ADBE062D68}.Release DLL|x86.ActiveCfg = Release DLL|Win32
|
||||
{24EC5104-7402-4C76-B66B-27ADBE062D68}.Release DLL|x86.Build.0 = Release DLL|Win32
|
||||
{24EC5104-7402-4C76-B66B-27ADBE062D68}.Release Static|x64.ActiveCfg = Release Static|x64
|
||||
{24EC5104-7402-4C76-B66B-27ADBE062D68}.Release Static|x64.Build.0 = Release Static|x64
|
||||
{24EC5104-7402-4C76-B66B-27ADBE062D68}.Release Static|x86.ActiveCfg = Release Static|Win32
|
||||
{24EC5104-7402-4C76-B66B-27ADBE062D68}.Release Static|x86.Build.0 = Release Static|Win32
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {93CE9298-807C-4EAD-B1E6-7109DD1A78FA}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
13
antlr/antlr4-runtime-4.12.0/demo/generate.cmd
Normal file
13
antlr/antlr4-runtime-4.12.0/demo/generate.cmd
Normal file
@ -0,0 +1,13 @@
|
||||
@echo off
|
||||
:: Created 2016, Mike Lischke (public domain)
|
||||
|
||||
:: This script is used to generate source files from the test grammars in the same folder. The generated files are placed
|
||||
:: into a subfolder "generated" which the demo project uses to compile a demo binary.
|
||||
|
||||
:: Download the ANLTR jar and place it in the same folder as this script (or adjust the LOCATION var accordingly).
|
||||
|
||||
set LOCATION=antlr-4.12.0-complete.jar
|
||||
java -jar %LOCATION% -Dlanguage=Cpp -listener -visitor -o generated/ -package antlrcpptest TLexer.g4 TParser.g4
|
||||
::java -jar %LOCATION% -Dlanguage=Cpp -listener -visitor -o generated/ -package antlrcpptest -XdbgST TLexer.g4 TParser.g4
|
||||
::java -jar %LOCATION% -Dlanguage=Java -listener -visitor -o generated/ -package antlrcpptest TLexer.g4 TParser.g4
|
||||
|
||||
28
antlr/antlr4-runtime-4.12.0/demo/generate.sh
Executable file
28
antlr/antlr4-runtime-4.12.0/demo/generate.sh
Executable file
@ -0,0 +1,28 @@
|
||||
#!/bin/bash
|
||||
set -o errexit
|
||||
|
||||
# Created 2016, Mike Lischke (public domain)
|
||||
|
||||
# This script is used to generate source files from the test grammars in the same folder. The generated files are placed
|
||||
# into a subfolder "generated" which the demo project uses to compile a demo binary.
|
||||
|
||||
# There are 2 ways of running the ANTLR generator here.
|
||||
|
||||
# 1) Running from jar. Use the given jar (or replace it by another one you built or downloaded) for generation.
|
||||
#LOCATION=antlr4-4.5.4-SNAPSHOT.jar
|
||||
#java -jar $LOCATION -Dlanguage=Cpp -listener -visitor -o generated/ -package antlrcpptest TLexer.g4 TParser.g4
|
||||
#java -jar $LOCATION -Dlanguage=Cpp -listener -visitor -o generated/ -package antlrcpptest -XdbgST TLexer.g4 TParser.g4
|
||||
#java -jar $LOCATION -Dlanguage=Java -listener -visitor -o generated/ -package antlrcpptest TLexer.g4 TParser.g4
|
||||
|
||||
# 2) Running from class path. This requires that you have both antlr3 and antlr4 compiled. In this scenario no installation
|
||||
# is needed. You just compile the java class files (using "mvn compile" in both the antlr4 and the antlr3 root folders).
|
||||
# The script then runs the generation using these class files, by specifying them on the classpath.
|
||||
# Also the string template jar is needed. Adjust CLASSPATH if you have stored the jar in a different folder as this script assumes.
|
||||
# Furthermore is assumed that the antlr3 folder is located side-by-side with the antlr4 folder. Adjust CLASSPATH if not.
|
||||
# This approach is especially useful if you are working on a target stg file, as it doesn't require to regenerate the
|
||||
# antlr jar over and over again.
|
||||
CLASSPATH=../../../tool/resources/:ST-4.0.8.jar:../../../tool/target/classes:../../../runtime/Java/target/classes:../../../../antlr3/runtime/Java/target/classes
|
||||
|
||||
java -cp $CLASSPATH org.antlr.v4.Tool -Dlanguage=Cpp -listener -visitor -o generated/ -package antlrcpptest TLexer.g4 TParser.g4
|
||||
#java -cp $CLASSPATH org.antlr.v4.Tool -Dlanguage=Cpp -listener -visitor -o generated/ -package antlrcpptest -XdbgST TLexer.g4 TParser.g4
|
||||
#java -cp $CLASSPATH org.antlr.v4.Tool -Dlanguage=Java -listener -visitor -o generated/ TLexer.g4 TParser.g4
|
||||
28
antlr/antlr4-runtime-4.12.0/deploy-macos.sh
Executable file
28
antlr/antlr4-runtime-4.12.0/deploy-macos.sh
Executable file
@ -0,0 +1,28 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Clean left overs from previous builds if there are any
|
||||
rm -rf antlr4-runtime build lib
|
||||
rm -f antlr4-cpp-runtime-macos.zip
|
||||
|
||||
# Binaries
|
||||
cmake . -D CMAKE_OSX_ARCHITECTURES="arm64; x86_64" -DCMAKE_BUILD_TYPE=Release &> /dev/null
|
||||
make -j 8
|
||||
|
||||
rm -rf lib
|
||||
mkdir lib
|
||||
cp runtime/libantlr4-runtime.dylib lib
|
||||
cp runtime/libantlr4-runtime.a lib
|
||||
|
||||
# Headers
|
||||
rm -f -R antlr4-runtime
|
||||
pushd runtime/src
|
||||
find . -name '*.h' | cpio -pdm ../../antlr4-runtime
|
||||
popd
|
||||
|
||||
# Zip up and clean up
|
||||
zip -r antlr4-cpp-runtime-macos.zip antlr4-runtime lib
|
||||
|
||||
rm -f -R antlr4-runtime build lib
|
||||
|
||||
# Deploy
|
||||
#cp antlr4-cpp-runtime-macos.zip ~/antlr/sites/website-antlr4/download
|
||||
15
antlr/antlr4-runtime-4.12.0/deploy-source.sh
Executable file
15
antlr/antlr4-runtime-4.12.0/deploy-source.sh
Executable file
@ -0,0 +1,15 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Zip it
|
||||
rm -f antlr4-cpp-runtime-source.zip
|
||||
zip -r antlr4-cpp-runtime-source.zip "README.md" "cmake" "demo" "runtime" "CMakeLists.txt" "deploy-macos.sh" "deploy-source.sh" "deploy-windows.cmd" "VERSION" \
|
||||
-X -x "*.DS_Store*" "antlrcpp.xcodeproj/xcuserdata/*" "*Build*" "*DerivedData*" "*.jar" "demo/generated/*" "*.vscode*" "runtime/build/*" \
|
||||
"runtime/*.dylib" "*.a" "runtime/thirdparty/*" "runtime/CMakeFiles/*"
|
||||
|
||||
# Add the license file from the ANTLR root as well.
|
||||
pushd ../../
|
||||
zip runtime/cpp/antlr4-cpp-runtime-source.zip LICENSE.txt
|
||||
popd
|
||||
|
||||
# Deploy
|
||||
#cp antlr4-cpp-runtime-source.zip ~/antlr/sites/website-antlr4/download
|
||||
81
antlr/antlr4-runtime-4.12.0/deploy-windows.cmd
Normal file
81
antlr/antlr4-runtime-4.12.0/deploy-windows.cmd
Normal file
@ -0,0 +1,81 @@
|
||||
@echo off
|
||||
setlocal
|
||||
|
||||
if [%1] == [] goto Usage
|
||||
|
||||
rem Clean left overs from previous builds if there are any
|
||||
if exist bin rmdir /S /Q runtime\bin
|
||||
if exist obj rmdir /S /Q runtime\obj
|
||||
if exist lib rmdir /S /Q lib
|
||||
if exist antlr4-runtime rmdir /S /Q antlr4-runtime
|
||||
if exist antlr4-cpp-runtime-vs2019.zip erase antlr4-cpp-runtime-vs2019.zip
|
||||
if exist antlr4-cpp-runtime-vs2022.zip erase antlr4-cpp-runtime-vs2022.zip
|
||||
|
||||
rem Headers
|
||||
echo Copying header files ...
|
||||
xcopy runtime\src\*.h antlr4-runtime\ /s /q
|
||||
|
||||
rem Binaries
|
||||
rem VS 2019 disabled by default. Change the X to a C to enable it.
|
||||
if exist "X:\Program Files (x86)\Microsoft Visual Studio\2019\%1\Common7\Tools\VsDevCmd.bat" (
|
||||
echo.
|
||||
|
||||
call "C:\Program Files (x86)\Microsoft Visual Studio\2019\%1\Common7\Tools\VsDevCmd.bat"
|
||||
|
||||
pushd runtime
|
||||
msbuild antlr4cpp-vs2019.vcxproj /p:configuration="Release DLL" /p:platform=Win32
|
||||
msbuild antlr4cpp-vs2019.vcxproj /p:configuration="Release DLL" /p:platform=x64
|
||||
popd
|
||||
|
||||
7z a antlr4-cpp-runtime-vs2019.zip antlr4-runtime
|
||||
xcopy runtime\bin\*.dll lib\ /s
|
||||
xcopy runtime\bin\*.lib lib\ /s
|
||||
7z a antlr4-cpp-runtime-vs2019.zip lib
|
||||
|
||||
rmdir /S /Q lib
|
||||
rmdir /S /Q runtime\bin
|
||||
rmdir /S /Q runtime\obj
|
||||
|
||||
rem if exist antlr4-cpp-runtime-vs2019.zip copy antlr4-cpp-runtime-vs2019.zip ~/antlr/sites/website-antlr4/download
|
||||
)
|
||||
|
||||
set VCTargetsPath=C:\Program Files\Microsoft Visual Studio\2022\%1\MSBuild\Microsoft\VC\v170\
|
||||
if exist "C:\Program Files\Microsoft Visual Studio\2022\%1\Common7\Tools\VsDevCmd.bat" (
|
||||
echo.
|
||||
|
||||
call "C:\Program Files\Microsoft Visual Studio\2022\%1\Common7\Tools\VsDevCmd.bat"
|
||||
|
||||
pushd runtime
|
||||
msbuild antlr4cpp-vs2022.vcxproj /p:configuration="Release DLL" /p:platform=Win32
|
||||
msbuild antlr4cpp-vs2022.vcxproj /p:configuration="Release DLL" /p:platform=x64
|
||||
popd
|
||||
|
||||
7z a antlr4-cpp-runtime-vs2022.zip antlr4-runtime
|
||||
xcopy runtime\bin\*.dll lib\ /s
|
||||
xcopy runtime\bin\*.lib lib\ /s
|
||||
7z a antlr4-cpp-runtime-vs2022.zip lib
|
||||
|
||||
rmdir /S /Q lib
|
||||
rmdir /S /Q runtime\bin
|
||||
rmdir /S /Q runtime\obj
|
||||
|
||||
rem if exist antlr4-cpp-runtime-vs2022.zip copy antlr4-cpp-runtime-vs2022.zip ~/antlr/sites/website-antlr4/download
|
||||
)
|
||||
|
||||
rmdir /S /Q antlr4-runtime
|
||||
echo.
|
||||
echo === Build done ===
|
||||
|
||||
goto end
|
||||
|
||||
:Usage
|
||||
|
||||
echo This script builds Visual Studio 2019 and/or 2022 libraries of the ANTLR4 runtime.
|
||||
echo You have to specify the type of your VS installation (Community, Professional etc.) to construct
|
||||
echo the correct build tools path.
|
||||
echo.
|
||||
echo Example:
|
||||
echo %0 Professional
|
||||
echo.
|
||||
|
||||
:end
|
||||
587
antlr/antlr4-runtime-4.12.0/runtime/CMakeCache.txt
Normal file
587
antlr/antlr4-runtime-4.12.0/runtime/CMakeCache.txt
Normal file
@ -0,0 +1,587 @@
|
||||
# This is the CMakeCache file.
|
||||
# For build in directory: /Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime
|
||||
# It was generated by CMake: /Applications/CLion.app/Contents/bin/cmake/mac/bin/cmake
|
||||
# You can edit this file to change values found and used by cmake.
|
||||
# If you do not want to change any of the values, simply exit the editor.
|
||||
# If you do want to change a value, simply edit, save, and exit the editor.
|
||||
# The syntax for the file is as follows:
|
||||
# KEY:TYPE=VALUE
|
||||
# KEY is the name of a variable in the cache.
|
||||
# TYPE is a hint to GUIs for the type of VALUE, DO NOT EDIT TYPE!.
|
||||
# VALUE is the current value for the KEY.
|
||||
|
||||
########################
|
||||
# EXTERNAL cache entries
|
||||
########################
|
||||
|
||||
//Build C++ tests.
|
||||
ANTLR_BUILD_CPP_TESTS:BOOL=ON
|
||||
|
||||
//Builds the googlemock subproject
|
||||
BUILD_GMOCK:BOOL=ON
|
||||
|
||||
//Path to a program.
|
||||
CMAKE_ADDR2LINE:FILEPATH=CMAKE_ADDR2LINE-NOTFOUND
|
||||
|
||||
//Path to a program.
|
||||
CMAKE_AR:FILEPATH=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ar
|
||||
|
||||
//For backwards compatibility, what version of CMake commands and
|
||||
// syntax should this version of CMake try to support.
|
||||
CMAKE_BACKWARDS_COMPATIBILITY:STRING=2.4
|
||||
|
||||
//Choose the type of build, options are: None Debug Release RelWithDebInfo
|
||||
// MinSizeRel ...
|
||||
CMAKE_BUILD_TYPE:STRING=Debug
|
||||
|
||||
//Enable/Disable color output during build.
|
||||
CMAKE_COLOR_MAKEFILE:BOOL=ON
|
||||
|
||||
//CXX compiler
|
||||
CMAKE_CXX_COMPILER:STRING=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++
|
||||
|
||||
//Flags used by the CXX compiler during all build types.
|
||||
CMAKE_CXX_FLAGS:STRING=
|
||||
|
||||
//Flags used by the CXX compiler during DEBUG builds.
|
||||
CMAKE_CXX_FLAGS_DEBUG:STRING=-g
|
||||
|
||||
//Flags used by the CXX compiler during MINSIZEREL builds.
|
||||
CMAKE_CXX_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG
|
||||
|
||||
//Flags used by the CXX compiler during RELEASE builds.
|
||||
CMAKE_CXX_FLAGS_RELEASE:STRING=-O3 -DNDEBUG
|
||||
|
||||
//Flags used by the CXX compiler during RELWITHDEBINFO builds.
|
||||
CMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG
|
||||
|
||||
//C compiler
|
||||
CMAKE_C_COMPILER:STRING=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
|
||||
|
||||
//Flags used by the C compiler during all build types.
|
||||
CMAKE_C_FLAGS:STRING=
|
||||
|
||||
//Flags used by the C compiler during DEBUG builds.
|
||||
CMAKE_C_FLAGS_DEBUG:STRING=-g
|
||||
|
||||
//Flags used by the C compiler during MINSIZEREL builds.
|
||||
CMAKE_C_FLAGS_MINSIZEREL:STRING=-Os -DNDEBUG
|
||||
|
||||
//Flags used by the C compiler during RELEASE builds.
|
||||
CMAKE_C_FLAGS_RELEASE:STRING=-O3 -DNDEBUG
|
||||
|
||||
//Flags used by the C compiler during RELWITHDEBINFO builds.
|
||||
CMAKE_C_FLAGS_RELWITHDEBINFO:STRING=-O2 -g -DNDEBUG
|
||||
|
||||
//Path to a program.
|
||||
CMAKE_DLLTOOL:FILEPATH=CMAKE_DLLTOOL-NOTFOUND
|
||||
|
||||
//Flags used by the linker during all build types.
|
||||
CMAKE_EXE_LINKER_FLAGS:STRING=
|
||||
|
||||
//Flags used by the linker during DEBUG builds.
|
||||
CMAKE_EXE_LINKER_FLAGS_DEBUG:STRING=
|
||||
|
||||
//Flags used by the linker during MINSIZEREL builds.
|
||||
CMAKE_EXE_LINKER_FLAGS_MINSIZEREL:STRING=
|
||||
|
||||
//Flags used by the linker during RELEASE builds.
|
||||
CMAKE_EXE_LINKER_FLAGS_RELEASE:STRING=
|
||||
|
||||
//Flags used by the linker during RELWITHDEBINFO builds.
|
||||
CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO:STRING=
|
||||
|
||||
//Enable/Disable output of compile commands during generation.
|
||||
CMAKE_EXPORT_COMPILE_COMMANDS:BOOL=
|
||||
|
||||
//Value Computed by CMake.
|
||||
CMAKE_FIND_PACKAGE_REDIRECTS_DIR:STATIC=/Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime/CMakeFiles/pkgRedirects
|
||||
|
||||
//User executables (bin)
|
||||
CMAKE_INSTALL_BINDIR:PATH=bin
|
||||
|
||||
//Read-only architecture-independent data (DATAROOTDIR)
|
||||
CMAKE_INSTALL_DATADIR:PATH=
|
||||
|
||||
//Read-only architecture-independent data root (share)
|
||||
CMAKE_INSTALL_DATAROOTDIR:PATH=share
|
||||
|
||||
//Documentation root (DATAROOTDIR/doc/PROJECT_NAME)
|
||||
CMAKE_INSTALL_DOCDIR:PATH=
|
||||
|
||||
//C header files (include)
|
||||
CMAKE_INSTALL_INCLUDEDIR:PATH=include
|
||||
|
||||
//Info documentation (DATAROOTDIR/info)
|
||||
CMAKE_INSTALL_INFODIR:PATH=
|
||||
|
||||
//Object code libraries (lib)
|
||||
CMAKE_INSTALL_LIBDIR:PATH=lib
|
||||
|
||||
//Program executables (libexec)
|
||||
CMAKE_INSTALL_LIBEXECDIR:PATH=libexec
|
||||
|
||||
//Locale-dependent data (DATAROOTDIR/locale)
|
||||
CMAKE_INSTALL_LOCALEDIR:PATH=
|
||||
|
||||
//Modifiable single-machine data (var)
|
||||
CMAKE_INSTALL_LOCALSTATEDIR:PATH=var
|
||||
|
||||
//Man documentation (DATAROOTDIR/man)
|
||||
CMAKE_INSTALL_MANDIR:PATH=
|
||||
|
||||
//Path to a program.
|
||||
CMAKE_INSTALL_NAME_TOOL:FILEPATH=/usr/bin/install_name_tool
|
||||
|
||||
//C header files for non-gcc (/usr/include)
|
||||
CMAKE_INSTALL_OLDINCLUDEDIR:PATH=/usr/include
|
||||
|
||||
//Install path prefix, prepended onto install directories.
|
||||
CMAKE_INSTALL_PREFIX:PATH=/usr/local
|
||||
|
||||
//Run-time variable data (LOCALSTATEDIR/run)
|
||||
CMAKE_INSTALL_RUNSTATEDIR:PATH=
|
||||
|
||||
//System admin executables (sbin)
|
||||
CMAKE_INSTALL_SBINDIR:PATH=sbin
|
||||
|
||||
//Modifiable architecture-independent data (com)
|
||||
CMAKE_INSTALL_SHAREDSTATEDIR:PATH=com
|
||||
|
||||
//Read-only single-machine data (etc)
|
||||
CMAKE_INSTALL_SYSCONFDIR:PATH=etc
|
||||
|
||||
//Path to a program.
|
||||
CMAKE_LINKER:FILEPATH=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ld
|
||||
|
||||
//Path to a program.
|
||||
CMAKE_MAKE_PROGRAM:FILEPATH=/usr/bin/make
|
||||
|
||||
//Flags used by the linker during the creation of modules during
|
||||
// all build types.
|
||||
CMAKE_MODULE_LINKER_FLAGS:STRING=
|
||||
|
||||
//Flags used by the linker during the creation of modules during
|
||||
// DEBUG builds.
|
||||
CMAKE_MODULE_LINKER_FLAGS_DEBUG:STRING=
|
||||
|
||||
//Flags used by the linker during the creation of modules during
|
||||
// MINSIZEREL builds.
|
||||
CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL:STRING=
|
||||
|
||||
//Flags used by the linker during the creation of modules during
|
||||
// RELEASE builds.
|
||||
CMAKE_MODULE_LINKER_FLAGS_RELEASE:STRING=
|
||||
|
||||
//Flags used by the linker during the creation of modules during
|
||||
// RELWITHDEBINFO builds.
|
||||
CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO:STRING=
|
||||
|
||||
//Path to a program.
|
||||
CMAKE_NM:FILEPATH=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/nm
|
||||
|
||||
//Path to a program.
|
||||
CMAKE_OBJCOPY:FILEPATH=CMAKE_OBJCOPY-NOTFOUND
|
||||
|
||||
//Path to a program.
|
||||
CMAKE_OBJDUMP:FILEPATH=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/objdump
|
||||
|
||||
//Build architectures for OSX
|
||||
CMAKE_OSX_ARCHITECTURES:STRING=arm64; x86_64
|
||||
|
||||
//Minimum OS X version to target for deployment (at runtime); newer
|
||||
// APIs weak linked. Set to empty string for default value.
|
||||
CMAKE_OSX_DEPLOYMENT_TARGET:STRING=
|
||||
|
||||
//The product will be built against the headers and libraries located
|
||||
// inside the indicated SDK.
|
||||
CMAKE_OSX_SYSROOT:PATH=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk
|
||||
|
||||
//Value Computed by CMake
|
||||
CMAKE_PROJECT_DESCRIPTION:STATIC=
|
||||
|
||||
//Value Computed by CMake
|
||||
CMAKE_PROJECT_HOMEPAGE_URL:STATIC=
|
||||
|
||||
//Value Computed by CMake
|
||||
CMAKE_PROJECT_NAME:STATIC=Project
|
||||
|
||||
//Value Computed by CMake
|
||||
CMAKE_PROJECT_VERSION:STATIC=1.11.0
|
||||
|
||||
//Value Computed by CMake
|
||||
CMAKE_PROJECT_VERSION_MAJOR:STATIC=1
|
||||
|
||||
//Value Computed by CMake
|
||||
CMAKE_PROJECT_VERSION_MINOR:STATIC=11
|
||||
|
||||
//Value Computed by CMake
|
||||
CMAKE_PROJECT_VERSION_PATCH:STATIC=0
|
||||
|
||||
//Value Computed by CMake
|
||||
CMAKE_PROJECT_VERSION_TWEAK:STATIC=
|
||||
|
||||
//Path to a program.
|
||||
CMAKE_RANLIB:FILEPATH=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ranlib
|
||||
|
||||
//Path to a program.
|
||||
CMAKE_READELF:FILEPATH=CMAKE_READELF-NOTFOUND
|
||||
|
||||
//Flags used by the linker during the creation of shared libraries
|
||||
// during all build types.
|
||||
CMAKE_SHARED_LINKER_FLAGS:STRING=
|
||||
|
||||
//Flags used by the linker during the creation of shared libraries
|
||||
// during DEBUG builds.
|
||||
CMAKE_SHARED_LINKER_FLAGS_DEBUG:STRING=
|
||||
|
||||
//Flags used by the linker during the creation of shared libraries
|
||||
// during MINSIZEREL builds.
|
||||
CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL:STRING=
|
||||
|
||||
//Flags used by the linker during the creation of shared libraries
|
||||
// during RELEASE builds.
|
||||
CMAKE_SHARED_LINKER_FLAGS_RELEASE:STRING=
|
||||
|
||||
//Flags used by the linker during the creation of shared libraries
|
||||
// during RELWITHDEBINFO builds.
|
||||
CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO:STRING=
|
||||
|
||||
//If set, runtime paths are not added when installing shared libraries,
|
||||
// but are added when building.
|
||||
CMAKE_SKIP_INSTALL_RPATH:BOOL=NO
|
||||
|
||||
//If set, runtime paths are not added when using shared libraries.
|
||||
CMAKE_SKIP_RPATH:BOOL=NO
|
||||
|
||||
//Flags used by the linker during the creation of static libraries
|
||||
// during all build types.
|
||||
CMAKE_STATIC_LINKER_FLAGS:STRING=
|
||||
|
||||
//Flags used by the linker during the creation of static libraries
|
||||
// during DEBUG builds.
|
||||
CMAKE_STATIC_LINKER_FLAGS_DEBUG:STRING=
|
||||
|
||||
//Flags used by the linker during the creation of static libraries
|
||||
// during MINSIZEREL builds.
|
||||
CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL:STRING=
|
||||
|
||||
//Flags used by the linker during the creation of static libraries
|
||||
// during RELEASE builds.
|
||||
CMAKE_STATIC_LINKER_FLAGS_RELEASE:STRING=
|
||||
|
||||
//Flags used by the linker during the creation of static libraries
|
||||
// during RELWITHDEBINFO builds.
|
||||
CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO:STRING=
|
||||
|
||||
//Path to a program.
|
||||
CMAKE_STRIP:FILEPATH=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/strip
|
||||
|
||||
//If this value is on, makefiles will be generated without the
|
||||
// .SILENT directive, and all commands will be echoed to the console
|
||||
// during the make. This is useful for debugging only. With Visual
|
||||
// Studio IDE projects all commands are done without /nologo.
|
||||
CMAKE_VERBOSE_MAKEFILE:BOOL=FALSE
|
||||
|
||||
//Single output directory for building all executables.
|
||||
EXECUTABLE_OUTPUT_PATH:PATH=
|
||||
|
||||
//Directory under which to collect all populated content
|
||||
FETCHCONTENT_BASE_DIR:PATH=/Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime/_deps
|
||||
|
||||
//Disables all attempts to download or update content and assumes
|
||||
// source dirs already exist
|
||||
FETCHCONTENT_FULLY_DISCONNECTED:BOOL=OFF
|
||||
|
||||
//Enables QUIET option for all content population
|
||||
FETCHCONTENT_QUIET:BOOL=ON
|
||||
|
||||
//When not empty, overrides where to find pre-populated content
|
||||
// for googletest
|
||||
FETCHCONTENT_SOURCE_DIR_GOOGLETEST:PATH=
|
||||
|
||||
//Enables UPDATE_DISCONNECTED behavior for all content population
|
||||
FETCHCONTENT_UPDATES_DISCONNECTED:BOOL=OFF
|
||||
|
||||
//Enables UPDATE_DISCONNECTED behavior just for population of googletest
|
||||
FETCHCONTENT_UPDATES_DISCONNECTED_GOOGLETEST:BOOL=OFF
|
||||
|
||||
//Enable installation of googletest. (Projects embedding googletest
|
||||
// may want to turn this OFF.)
|
||||
INSTALL_GTEST:BOOL=ON
|
||||
|
||||
//Single output directory for building all libraries.
|
||||
LIBRARY_OUTPUT_PATH:PATH=
|
||||
|
||||
//Value Computed by CMake
|
||||
Project_BINARY_DIR:STATIC=/Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime
|
||||
|
||||
//Value Computed by CMake
|
||||
Project_IS_TOP_LEVEL:STATIC=ON
|
||||
|
||||
//Value Computed by CMake
|
||||
Project_SOURCE_DIR:STATIC=/Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime
|
||||
|
||||
//Trace ATN simulation
|
||||
TRACE_ATN:BOOL=OFF
|
||||
|
||||
//Value Computed by CMake
|
||||
gmock_BINARY_DIR:STATIC=/Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime/_deps/googletest-build/googlemock
|
||||
|
||||
//Value Computed by CMake
|
||||
gmock_IS_TOP_LEVEL:STATIC=OFF
|
||||
|
||||
//Dependencies for the target
|
||||
gmock_LIB_DEPENDS:STATIC=general;gtest;
|
||||
|
||||
//Value Computed by CMake
|
||||
gmock_SOURCE_DIR:STATIC=/Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime/_deps/googletest-src/googlemock
|
||||
|
||||
//Build all of Google Mock's own tests.
|
||||
gmock_build_tests:BOOL=OFF
|
||||
|
||||
//Dependencies for the target
|
||||
gmock_main_LIB_DEPENDS:STATIC=general;gmock;
|
||||
|
||||
//Value Computed by CMake
|
||||
googletest-distribution_BINARY_DIR:STATIC=/Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime/_deps/googletest-build
|
||||
|
||||
//Value Computed by CMake
|
||||
googletest-distribution_IS_TOP_LEVEL:STATIC=OFF
|
||||
|
||||
//Value Computed by CMake
|
||||
googletest-distribution_SOURCE_DIR:STATIC=/Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime/_deps/googletest-src
|
||||
|
||||
//Value Computed by CMake
|
||||
gtest_BINARY_DIR:STATIC=/Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime/_deps/googletest-build/googletest
|
||||
|
||||
//Value Computed by CMake
|
||||
gtest_IS_TOP_LEVEL:STATIC=OFF
|
||||
|
||||
//Value Computed by CMake
|
||||
gtest_SOURCE_DIR:STATIC=/Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime/_deps/googletest-src/googletest
|
||||
|
||||
//Build gtest's sample programs.
|
||||
gtest_build_samples:BOOL=OFF
|
||||
|
||||
//Build all of gtest's own tests.
|
||||
gtest_build_tests:BOOL=OFF
|
||||
|
||||
//Disable uses of pthreads in gtest.
|
||||
gtest_disable_pthreads:BOOL=OFF
|
||||
|
||||
//Use shared (DLL) run-time lib even when Google Test is built
|
||||
// as static lib.
|
||||
gtest_force_shared_crt:BOOL=OFF
|
||||
|
||||
//Build gtest with internal symbols hidden in shared libraries.
|
||||
gtest_hide_internal_symbols:BOOL=OFF
|
||||
|
||||
//Dependencies for the target
|
||||
gtest_main_LIB_DEPENDS:STATIC=general;gtest;
|
||||
|
||||
|
||||
########################
|
||||
# INTERNAL cache entries
|
||||
########################
|
||||
|
||||
//ADVANCED property for variable: CMAKE_ADDR2LINE
|
||||
CMAKE_ADDR2LINE-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_AR
|
||||
CMAKE_AR-ADVANCED:INTERNAL=1
|
||||
//This is the directory where this CMakeCache.txt was created
|
||||
CMAKE_CACHEFILE_DIR:INTERNAL=/Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime
|
||||
//Major version of cmake used to create the current loaded cache
|
||||
CMAKE_CACHE_MAJOR_VERSION:INTERNAL=3
|
||||
//Minor version of cmake used to create the current loaded cache
|
||||
CMAKE_CACHE_MINOR_VERSION:INTERNAL=22
|
||||
//Patch version of cmake used to create the current loaded cache
|
||||
CMAKE_CACHE_PATCH_VERSION:INTERNAL=3
|
||||
//ADVANCED property for variable: CMAKE_COLOR_MAKEFILE
|
||||
CMAKE_COLOR_MAKEFILE-ADVANCED:INTERNAL=1
|
||||
//Path to CMake executable.
|
||||
CMAKE_COMMAND:INTERNAL=/Applications/CLion.app/Contents/bin/cmake/mac/bin/cmake
|
||||
//Path to cpack program executable.
|
||||
CMAKE_CPACK_COMMAND:INTERNAL=/Applications/CLion.app/Contents/bin/cmake/mac/bin/cpack
|
||||
//Path to ctest program executable.
|
||||
CMAKE_CTEST_COMMAND:INTERNAL=/Applications/CLion.app/Contents/bin/cmake/mac/bin/ctest
|
||||
//ADVANCED property for variable: CMAKE_CXX_COMPILER
|
||||
CMAKE_CXX_COMPILER-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_CXX_FLAGS
|
||||
CMAKE_CXX_FLAGS-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_CXX_FLAGS_DEBUG
|
||||
CMAKE_CXX_FLAGS_DEBUG-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_CXX_FLAGS_MINSIZEREL
|
||||
CMAKE_CXX_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELEASE
|
||||
CMAKE_CXX_FLAGS_RELEASE-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELWITHDEBINFO
|
||||
CMAKE_CXX_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_C_COMPILER
|
||||
CMAKE_C_COMPILER-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_C_FLAGS
|
||||
CMAKE_C_FLAGS-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_C_FLAGS_DEBUG
|
||||
CMAKE_C_FLAGS_DEBUG-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_C_FLAGS_MINSIZEREL
|
||||
CMAKE_C_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_C_FLAGS_RELEASE
|
||||
CMAKE_C_FLAGS_RELEASE-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_C_FLAGS_RELWITHDEBINFO
|
||||
CMAKE_C_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_DLLTOOL
|
||||
CMAKE_DLLTOOL-ADVANCED:INTERNAL=1
|
||||
//Path to cache edit program executable.
|
||||
CMAKE_EDIT_COMMAND:INTERNAL=/opt/homebrew/Cellar/cmake/3.24.1/bin/ccmake
|
||||
//Executable file format
|
||||
CMAKE_EXECUTABLE_FORMAT:INTERNAL=MACHO
|
||||
//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS
|
||||
CMAKE_EXE_LINKER_FLAGS-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_DEBUG
|
||||
CMAKE_EXE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_MINSIZEREL
|
||||
CMAKE_EXE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELEASE
|
||||
CMAKE_EXE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO
|
||||
CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_EXPORT_COMPILE_COMMANDS
|
||||
CMAKE_EXPORT_COMPILE_COMMANDS-ADVANCED:INTERNAL=1
|
||||
//Name of external makefile project generator.
|
||||
CMAKE_EXTRA_GENERATOR:INTERNAL=
|
||||
//Name of generator.
|
||||
CMAKE_GENERATOR:INTERNAL=Unix Makefiles
|
||||
//Generator instance identifier.
|
||||
CMAKE_GENERATOR_INSTANCE:INTERNAL=
|
||||
//Name of generator platform.
|
||||
CMAKE_GENERATOR_PLATFORM:INTERNAL=
|
||||
//Name of generator toolset.
|
||||
CMAKE_GENERATOR_TOOLSET:INTERNAL=
|
||||
//Test CMAKE_HAVE_LIBC_PTHREAD
|
||||
CMAKE_HAVE_LIBC_PTHREAD:INTERNAL=1
|
||||
//Have include pthread.h
|
||||
CMAKE_HAVE_PTHREAD_H:INTERNAL=1
|
||||
//Source directory with the top level CMakeLists.txt file for this
|
||||
// project
|
||||
CMAKE_HOME_DIRECTORY:INTERNAL=/Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime
|
||||
//ADVANCED property for variable: CMAKE_INSTALL_BINDIR
|
||||
CMAKE_INSTALL_BINDIR-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_INSTALL_DATADIR
|
||||
CMAKE_INSTALL_DATADIR-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_INSTALL_DATAROOTDIR
|
||||
CMAKE_INSTALL_DATAROOTDIR-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_INSTALL_DOCDIR
|
||||
CMAKE_INSTALL_DOCDIR-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_INSTALL_INCLUDEDIR
|
||||
CMAKE_INSTALL_INCLUDEDIR-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_INSTALL_INFODIR
|
||||
CMAKE_INSTALL_INFODIR-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_INSTALL_LIBDIR
|
||||
CMAKE_INSTALL_LIBDIR-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_INSTALL_LIBEXECDIR
|
||||
CMAKE_INSTALL_LIBEXECDIR-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_INSTALL_LOCALEDIR
|
||||
CMAKE_INSTALL_LOCALEDIR-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_INSTALL_LOCALSTATEDIR
|
||||
CMAKE_INSTALL_LOCALSTATEDIR-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_INSTALL_MANDIR
|
||||
CMAKE_INSTALL_MANDIR-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_INSTALL_NAME_TOOL
|
||||
CMAKE_INSTALL_NAME_TOOL-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_INSTALL_OLDINCLUDEDIR
|
||||
CMAKE_INSTALL_OLDINCLUDEDIR-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_INSTALL_RUNSTATEDIR
|
||||
CMAKE_INSTALL_RUNSTATEDIR-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_INSTALL_SBINDIR
|
||||
CMAKE_INSTALL_SBINDIR-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_INSTALL_SHAREDSTATEDIR
|
||||
CMAKE_INSTALL_SHAREDSTATEDIR-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_INSTALL_SYSCONFDIR
|
||||
CMAKE_INSTALL_SYSCONFDIR-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_LINKER
|
||||
CMAKE_LINKER-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_MAKE_PROGRAM
|
||||
CMAKE_MAKE_PROGRAM-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS
|
||||
CMAKE_MODULE_LINKER_FLAGS-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_DEBUG
|
||||
CMAKE_MODULE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL
|
||||
CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELEASE
|
||||
CMAKE_MODULE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO
|
||||
CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_NM
|
||||
CMAKE_NM-ADVANCED:INTERNAL=1
|
||||
//number of local generators
|
||||
CMAKE_NUMBER_OF_MAKEFILES:INTERNAL=4
|
||||
//ADVANCED property for variable: CMAKE_OBJCOPY
|
||||
CMAKE_OBJCOPY-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_OBJDUMP
|
||||
CMAKE_OBJDUMP-ADVANCED:INTERNAL=1
|
||||
//Platform information initialized
|
||||
CMAKE_PLATFORM_INFO_INITIALIZED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_RANLIB
|
||||
CMAKE_RANLIB-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_READELF
|
||||
CMAKE_READELF-ADVANCED:INTERNAL=1
|
||||
//Path to CMake installation.
|
||||
CMAKE_ROOT:INTERNAL=/Applications/CLion.app/Contents/bin/cmake/mac/share/cmake-3.22
|
||||
//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS
|
||||
CMAKE_SHARED_LINKER_FLAGS-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_DEBUG
|
||||
CMAKE_SHARED_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL
|
||||
CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELEASE
|
||||
CMAKE_SHARED_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO
|
||||
CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_SKIP_INSTALL_RPATH
|
||||
CMAKE_SKIP_INSTALL_RPATH-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_SKIP_RPATH
|
||||
CMAKE_SKIP_RPATH-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS
|
||||
CMAKE_STATIC_LINKER_FLAGS-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_DEBUG
|
||||
CMAKE_STATIC_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL
|
||||
CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELEASE
|
||||
CMAKE_STATIC_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO
|
||||
CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: CMAKE_STRIP
|
||||
CMAKE_STRIP-ADVANCED:INTERNAL=1
|
||||
//uname command
|
||||
CMAKE_UNAME:INTERNAL=/usr/bin/uname
|
||||
//ADVANCED property for variable: CMAKE_VERBOSE_MAKEFILE
|
||||
CMAKE_VERBOSE_MAKEFILE-ADVANCED:INTERNAL=1
|
||||
//Details about finding Python
|
||||
FIND_PACKAGE_MESSAGE_DETAILS_Python:INTERNAL=[/opt/homebrew/Frameworks/Python.framework/Versions/3.10/bin/python3.10][cfound components: Interpreter ][v3.10.6()]
|
||||
//Details about finding Threads
|
||||
FIND_PACKAGE_MESSAGE_DETAILS_Threads:INTERNAL=[TRUE][v()]
|
||||
//CMAKE_INSTALL_PREFIX during last run
|
||||
_GNUInstallDirs_LAST_CMAKE_INSTALL_PREFIX:INTERNAL=/usr/local
|
||||
//Path to a program.
|
||||
_Python_EXECUTABLE:INTERNAL=/opt/homebrew/Frameworks/Python.framework/Versions/3.10/bin/python3.10
|
||||
//Python Properties
|
||||
_Python_INTERPRETER_PROPERTIES:INTERNAL=Python;3;10;6;64;;cpython-310-darwin;/opt/homebrew/opt/python@3.10/Frameworks/Python.framework/Versions/3.10/lib/python3.10;/opt/homebrew/opt/python@3.10/Frameworks/Python.framework/Versions/3.10/lib/python3.10;/opt/homebrew/opt/python@3.10/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages;/opt/homebrew/opt/python@3.10/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages
|
||||
_Python_INTERPRETER_SIGNATURE:INTERNAL=d861879f6de0f60676098025cfcd84c2
|
||||
cmake_package_name:INTERNAL=GTest
|
||||
generated_dir:INTERNAL=/Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime/_deps/googletest-build/googletest/generated
|
||||
//ADVANCED property for variable: gmock_build_tests
|
||||
gmock_build_tests-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: gtest_build_samples
|
||||
gtest_build_samples-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: gtest_build_tests
|
||||
gtest_build_tests-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: gtest_disable_pthreads
|
||||
gtest_disable_pthreads-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: gtest_force_shared_crt
|
||||
gtest_force_shared_crt-ADVANCED:INTERNAL=1
|
||||
//ADVANCED property for variable: gtest_hide_internal_symbols
|
||||
gtest_hide_internal_symbols-ADVANCED:INTERNAL=1
|
||||
targets_export_name:INTERNAL=GTestTargets
|
||||
|
||||
189
antlr/antlr4-runtime-4.12.0/runtime/CMakeLists.txt
Normal file
189
antlr/antlr4-runtime-4.12.0/runtime/CMakeLists.txt
Normal file
@ -0,0 +1,189 @@
|
||||
option(ANTLR_BUILD_CPP_TESTS "Build C++ tests." ON)
|
||||
option(TRACE_ATN "Trace ATN simulation" OFF)
|
||||
option(ANTLR_BUILD_SHARED "Build the shared library of the ANTLR runtime" ON)
|
||||
option(ANTLR_BUILD_STATIC "Build the static library of the ANTLR runtime" ON)
|
||||
|
||||
if (NOT ANTLR_BUILD_SHARED AND NOT ANTLR_BUILD_STATIC)
|
||||
message(FATAL_ERROR "Options ANTLR_BUILD_SHARED and ANTLR_BUILD_STATIC can't both be OFF")
|
||||
endif()
|
||||
|
||||
include_directories(
|
||||
${PROJECT_SOURCE_DIR}/runtime/src
|
||||
${PROJECT_SOURCE_DIR}/runtime/src/atn
|
||||
${PROJECT_SOURCE_DIR}/runtime/src/dfa
|
||||
${PROJECT_SOURCE_DIR}/runtime/src/internal
|
||||
${PROJECT_SOURCE_DIR}/runtime/src/misc
|
||||
${PROJECT_SOURCE_DIR}/runtime/src/support
|
||||
${PROJECT_SOURCE_DIR}/runtime/src/tree
|
||||
${PROJECT_SOURCE_DIR}/runtime/src/tree/pattern
|
||||
${PROJECT_SOURCE_DIR}/runtime/src/tree/xpath
|
||||
)
|
||||
|
||||
|
||||
file(GLOB libantlrcpp_SRC
|
||||
"${PROJECT_SOURCE_DIR}/runtime/src/*.cpp"
|
||||
"${PROJECT_SOURCE_DIR}/runtime/src/atn/*.cpp"
|
||||
"${PROJECT_SOURCE_DIR}/runtime/src/dfa/*.cpp"
|
||||
"${PROJECT_SOURCE_DIR}/runtime/src/internal/*.cpp"
|
||||
"${PROJECT_SOURCE_DIR}/runtime/src/misc/*.cpp"
|
||||
"${PROJECT_SOURCE_DIR}/runtime/src/support/*.cpp"
|
||||
"${PROJECT_SOURCE_DIR}/runtime/src/tree/*.cpp"
|
||||
"${PROJECT_SOURCE_DIR}/runtime/src/tree/pattern/*.cpp"
|
||||
"${PROJECT_SOURCE_DIR}/runtime/src/tree/xpath/*.cpp"
|
||||
)
|
||||
|
||||
if (ANTLR_BUILD_SHARED)
|
||||
add_library(antlr4_shared SHARED ${libantlrcpp_SRC})
|
||||
endif()
|
||||
if (ANTLR_BUILD_STATIC)
|
||||
add_library(antlr4_static STATIC ${libantlrcpp_SRC})
|
||||
endif()
|
||||
|
||||
# Make sure to link against threads (pthreads) library in order to be able to
|
||||
# make use of std::call_once in the code without producing runtime errors
|
||||
# (see also https://github.com/antlr/antlr4/issues/3708 and/or https://stackoverflow.com/q/51584960).
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
if (TARGET antlr4_shared)
|
||||
target_link_libraries(antlr4_shared Threads::Threads)
|
||||
endif()
|
||||
if (TARGET antlr4_static)
|
||||
target_link_libraries(antlr4_static Threads::Threads)
|
||||
endif()
|
||||
|
||||
IF(TRACE_ATN)
|
||||
ADD_DEFINITIONS(-DTRACE_ATN_SIM=1)
|
||||
ENDIF(TRACE_ATN)
|
||||
|
||||
if (ANTLR_BUILD_CPP_TESTS)
|
||||
include(FetchContent)
|
||||
|
||||
FetchContent_Declare(
|
||||
googletest
|
||||
URL https://github.com/google/googletest/archive/e2239ee6043f73722e7aa812a459f54a28552929.zip
|
||||
)
|
||||
|
||||
if(WITH_STATIC_CRT)
|
||||
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
|
||||
endif()
|
||||
|
||||
FetchContent_MakeAvailable(googletest)
|
||||
|
||||
file(GLOB libantlrcpp_TESTS
|
||||
"${PROJECT_SOURCE_DIR}/runtime/tests/*.cpp"
|
||||
)
|
||||
|
||||
add_executable(
|
||||
antlr4_tests
|
||||
${libantlrcpp_TESTS}
|
||||
)
|
||||
|
||||
target_link_libraries(
|
||||
antlr4_tests
|
||||
$<IF:$<TARGET_EXISTS:antlr4_static>,antlr4_static,antlr4_shared>
|
||||
gtest_main
|
||||
)
|
||||
|
||||
include(GoogleTest)
|
||||
|
||||
gtest_discover_tests(antlr4_tests)
|
||||
endif()
|
||||
|
||||
if(APPLE)
|
||||
if (TARGET antlr4_shared)
|
||||
target_link_libraries(antlr4_shared ${COREFOUNDATION_LIBRARY})
|
||||
endif()
|
||||
if (TARGET antlr4_static)
|
||||
target_link_libraries(antlr4_static ${COREFOUNDATION_LIBRARY})
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
|
||||
set(disabled_compile_warnings "/wd4251")
|
||||
else()
|
||||
set(disabled_compile_warnings "-Wno-overloaded-virtual")
|
||||
endif()
|
||||
|
||||
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
|
||||
set(disabled_compile_warnings "${disabled_compile_warnings} -Wno-dollar-in-identifier-extension -Wno-four-char-constants")
|
||||
elseif(CMAKE_CXX_COMPILER_ID MATCHES "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES "Intel")
|
||||
set(disabled_compile_warnings "${disabled_compile_warnings} -Wno-multichar")
|
||||
endif()
|
||||
|
||||
set(extra_share_compile_flags "")
|
||||
set(extra_static_compile_flags "")
|
||||
set(static_lib_suffix "")
|
||||
|
||||
if (WIN32)
|
||||
set(static_lib_suffix "-static")
|
||||
if (TARGET antlr4_shared)
|
||||
target_compile_definitions(antlr4_shared PUBLIC ANTLR4CPP_EXPORTS)
|
||||
endif()
|
||||
if (TARGET antlr4_static)
|
||||
target_compile_definitions(antlr4_static PUBLIC ANTLR4CPP_STATIC)
|
||||
endif()
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
|
||||
set(extra_share_compile_flags "-MP /wd4251")
|
||||
set(extra_static_compile_flags "-MP")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if (TARGET antlr4_shared)
|
||||
set_target_properties(antlr4_shared
|
||||
PROPERTIES VERSION ${ANTLR_VERSION}
|
||||
SOVERSION ${ANTLR_VERSION}
|
||||
OUTPUT_NAME antlr4-runtime
|
||||
COMPILE_FLAGS "${disabled_compile_warnings} ${extra_share_compile_flags}")
|
||||
endif()
|
||||
|
||||
if (TARGET antlr4_static)
|
||||
set_target_properties(antlr4_static
|
||||
PROPERTIES VERSION ${ANTLR_VERSION}
|
||||
SOVERSION ${ANTLR_VERSION}
|
||||
OUTPUT_NAME "antlr4-runtime${static_lib_suffix}"
|
||||
COMPILE_PDB_NAME "antlr4-runtime${static_lib_suffix}"
|
||||
COMPILE_FLAGS "${disabled_compile_warnings} ${extra_static_compile_flags}")
|
||||
endif()
|
||||
|
||||
if (ANTLR_BUILD_CPP_TESTS)
|
||||
# Copy the generated binaries to dist folder (required by test suite)
|
||||
if (TARGET antlr4_shared)
|
||||
add_custom_command(
|
||||
TARGET antlr4_shared
|
||||
POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_HOME_DIRECTORY}/dist
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_FILE:antlr4_shared> ${CMAKE_HOME_DIRECTORY}/dist
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_LINKER_FILE:antlr4_shared> ${CMAKE_HOME_DIRECTORY}/dist)
|
||||
endif()
|
||||
|
||||
if (TARGET antlr4_static)
|
||||
add_custom_command(
|
||||
TARGET antlr4_static
|
||||
POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory ${CMAKE_HOME_DIRECTORY}/dist
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_FILE:antlr4_static> ${CMAKE_HOME_DIRECTORY}/dist)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if (TARGET antlr4_shared)
|
||||
install(TARGETS antlr4_shared
|
||||
EXPORT antlr4-targets
|
||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
|
||||
endif()
|
||||
|
||||
if (TARGET antlr4_static)
|
||||
install(TARGETS antlr4_static
|
||||
EXPORT antlr4-targets
|
||||
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
|
||||
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
|
||||
endif()
|
||||
|
||||
install(DIRECTORY "${PROJECT_SOURCE_DIR}/runtime/src/"
|
||||
DESTINATION "include/antlr4-runtime"
|
||||
COMPONENT dev
|
||||
FILES_MATCHING PATTERN "*.h"
|
||||
)
|
||||
8
antlr/antlr4-runtime-4.12.0/runtime/CTestTestfile.cmake
Normal file
8
antlr/antlr4-runtime-4.12.0/runtime/CTestTestfile.cmake
Normal file
@ -0,0 +1,8 @@
|
||||
# CMake generated Testfile for
|
||||
# Source directory: /Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime
|
||||
# Build directory: /Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime
|
||||
#
|
||||
# This file includes the relevant testing commands required for
|
||||
# testing this directory and lists subdirectories to be tested as well.
|
||||
include("/Users/parrt/antlr/code/antlr4/runtime/Cpp/runtime/antlr4_tests[1]_include.cmake")
|
||||
subdirs("../_deps/googletest-build")
|
||||
4374
antlr/antlr4-runtime-4.12.0/runtime/Makefile
Normal file
4374
antlr/antlr4-runtime-4.12.0/runtime/Makefile
Normal file
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,33 @@
|
||||
|
||||
####### Expanded from @PACKAGE_INIT@ by configure_package_config_file() #######
|
||||
####### Any changes to this file will be overwritten by the next CMake run ####
|
||||
####### The input file was Config.cmake.in ########
|
||||
|
||||
get_filename_component(PACKAGE_PREFIX_DIR "${CMAKE_CURRENT_LIST_DIR}/../../../" ABSOLUTE)
|
||||
|
||||
macro(set_and_check _var _file)
|
||||
set(${_var} "${_file}")
|
||||
if(NOT EXISTS "${_file}")
|
||||
message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist !")
|
||||
endif()
|
||||
endmacro()
|
||||
|
||||
macro(check_required_components _NAME)
|
||||
foreach(comp ${${_NAME}_FIND_COMPONENTS})
|
||||
if(NOT ${_NAME}_${comp}_FOUND)
|
||||
if(${_NAME}_FIND_REQUIRED_${comp})
|
||||
set(${_NAME}_FOUND FALSE)
|
||||
endif()
|
||||
endif()
|
||||
endforeach()
|
||||
endmacro()
|
||||
|
||||
####################################################################################
|
||||
include(CMakeFindDependencyMacro)
|
||||
if (ON)
|
||||
set(THREADS_PREFER_PTHREAD_FLAG )
|
||||
find_dependency(Threads)
|
||||
endif()
|
||||
|
||||
include("${CMAKE_CURRENT_LIST_DIR}/GTestTargets.cmake")
|
||||
check_required_components("")
|
||||
@ -0,0 +1,48 @@
|
||||
# This is a basic version file for the Config-mode of find_package().
|
||||
# It is used by write_basic_package_version_file() as input file for configure_file()
|
||||
# to create a version-file which can be installed along a config.cmake file.
|
||||
#
|
||||
# The created file sets PACKAGE_VERSION_EXACT if the current version string and
|
||||
# the requested version string are exactly the same and it sets
|
||||
# PACKAGE_VERSION_COMPATIBLE if the current version is >= requested version.
|
||||
# The variable CVF_VERSION must be set before calling configure_file().
|
||||
|
||||
set(PACKAGE_VERSION "1.11.0")
|
||||
|
||||
if (PACKAGE_FIND_VERSION_RANGE)
|
||||
# Package version must be in the requested version range
|
||||
if ((PACKAGE_FIND_VERSION_RANGE_MIN STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION_MIN)
|
||||
OR ((PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_GREATER PACKAGE_FIND_VERSION_MAX)
|
||||
OR (PACKAGE_FIND_VERSION_RANGE_MAX STREQUAL "EXCLUDE" AND PACKAGE_VERSION VERSION_GREATER_EQUAL PACKAGE_FIND_VERSION_MAX)))
|
||||
set(PACKAGE_VERSION_COMPATIBLE FALSE)
|
||||
else()
|
||||
set(PACKAGE_VERSION_COMPATIBLE TRUE)
|
||||
endif()
|
||||
else()
|
||||
if(PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION)
|
||||
set(PACKAGE_VERSION_COMPATIBLE FALSE)
|
||||
else()
|
||||
set(PACKAGE_VERSION_COMPATIBLE TRUE)
|
||||
if(PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION)
|
||||
set(PACKAGE_VERSION_EXACT TRUE)
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
|
||||
# if the installed project requested no architecture check, don't perform the check
|
||||
if("FALSE")
|
||||
return()
|
||||
endif()
|
||||
|
||||
# if the installed or the using project don't have CMAKE_SIZEOF_VOID_P set, ignore it:
|
||||
if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "" OR "8" STREQUAL "")
|
||||
return()
|
||||
endif()
|
||||
|
||||
# check that the installed version has the same 32/64bit-ness as the one which is currently searching:
|
||||
if(NOT CMAKE_SIZEOF_VOID_P STREQUAL "8")
|
||||
math(EXPR installedBits "8 * 8")
|
||||
set(PACKAGE_VERSION "${PACKAGE_VERSION} (${installedBits}bit)")
|
||||
set(PACKAGE_VERSION_UNSUITABLE TRUE)
|
||||
endif()
|
||||
@ -0,0 +1,10 @@
|
||||
libdir=/usr/local/lib
|
||||
includedir=/usr/local/include
|
||||
|
||||
Name: gmock
|
||||
Description: GoogleMock (without main() function)
|
||||
Version: 1.11.0
|
||||
URL: https://github.com/google/googletest
|
||||
Requires: gtest = 1.11.0
|
||||
Libs: -L${libdir} -lgmock
|
||||
Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1
|
||||
@ -0,0 +1,10 @@
|
||||
libdir=/usr/local/lib
|
||||
includedir=/usr/local/include
|
||||
|
||||
Name: gmock_main
|
||||
Description: GoogleMock (with main() function)
|
||||
Version: 1.11.0
|
||||
URL: https://github.com/google/googletest
|
||||
Requires: gmock = 1.11.0
|
||||
Libs: -L${libdir} -lgmock_main
|
||||
Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1
|
||||
@ -0,0 +1,9 @@
|
||||
libdir=/usr/local/lib
|
||||
includedir=/usr/local/include
|
||||
|
||||
Name: gtest
|
||||
Description: GoogleTest (without main() function)
|
||||
Version: 1.11.0
|
||||
URL: https://github.com/google/googletest
|
||||
Libs: -L${libdir} -lgtest
|
||||
Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1
|
||||
@ -0,0 +1,10 @@
|
||||
libdir=/usr/local/lib
|
||||
includedir=/usr/local/include
|
||||
|
||||
Name: gtest_main
|
||||
Description: GoogleTest (with main() function)
|
||||
Version: 1.11.0
|
||||
URL: https://github.com/google/googletest
|
||||
Requires: gtest = 1.11.0
|
||||
Libs: -L${libdir} -lgtest_main
|
||||
Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1
|
||||
@ -0,0 +1,4 @@
|
||||
# Run manually to reformat a file:
|
||||
# clang-format -i --style=file <file>
|
||||
Language: Cpp
|
||||
BasedOnStyle: Google
|
||||
43
antlr/antlr4-runtime-4.12.0/runtime/_deps/googletest-src/.github/ISSUE_TEMPLATE/00-bug_report.md
vendored
Normal file
43
antlr/antlr4-runtime-4.12.0/runtime/_deps/googletest-src/.github/ISSUE_TEMPLATE/00-bug_report.md
vendored
Normal file
@ -0,0 +1,43 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: 'bug'
|
||||
assignees: ''
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
|
||||
Include a clear and concise description of what the problem is, including what
|
||||
you expected to happen, and what actually happened.
|
||||
|
||||
**Steps to reproduce the bug**
|
||||
|
||||
It's important that we are able to reproduce the problem that you are
|
||||
experiencing. Please provide all code and relevant steps to reproduce the
|
||||
problem, including your `BUILD`/`CMakeLists.txt` file and build commands. Links
|
||||
to a GitHub branch or [godbolt.org](https://godbolt.org/) that demonstrate the
|
||||
problem are also helpful.
|
||||
|
||||
**Does the bug persist in the most recent commit?**
|
||||
|
||||
We recommend using the latest commit in the master branch in your projects.
|
||||
|
||||
**What operating system and version are you using?**
|
||||
|
||||
If you are using a Linux distribution please include the name and version of the
|
||||
distribution as well.
|
||||
|
||||
**What compiler and version are you using?**
|
||||
|
||||
Please include the output of `gcc -v` or `clang -v`, or the equivalent for your
|
||||
compiler.
|
||||
|
||||
**What build system are you using?**
|
||||
|
||||
Please include the output of `bazel --version` or `cmake --version`, or the
|
||||
equivalent for your build system.
|
||||
|
||||
**Additional context**
|
||||
|
||||
Add any other context about the problem here.
|
||||
@ -0,0 +1,24 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Propose a new feature
|
||||
title: ''
|
||||
labels: 'enhancement'
|
||||
assignees: ''
|
||||
---
|
||||
|
||||
**Does the feature exist in the most recent commit?**
|
||||
|
||||
We recommend using the latest commit from GitHub in your projects.
|
||||
|
||||
**Why do we need this feature?**
|
||||
|
||||
Ideally, explain why a combination of existing features cannot be used instead.
|
||||
|
||||
**Describe the proposal**
|
||||
|
||||
Include a detailed description of the feature, with usage examples.
|
||||
|
||||
**Is the feature specific to an operating system, compiler, or build system version?**
|
||||
|
||||
If it is, please specify which versions.
|
||||
|
||||
1
antlr/antlr4-runtime-4.12.0/runtime/_deps/googletest-src/.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
1
antlr/antlr4-runtime-4.12.0/runtime/_deps/googletest-src/.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@ -0,0 +1 @@
|
||||
blank_issues_enabled: false
|
||||
84
antlr/antlr4-runtime-4.12.0/runtime/_deps/googletest-src/.gitignore
vendored
Normal file
84
antlr/antlr4-runtime-4.12.0/runtime/_deps/googletest-src/.gitignore
vendored
Normal file
@ -0,0 +1,84 @@
|
||||
# Ignore CI build directory
|
||||
build/
|
||||
xcuserdata
|
||||
cmake-build-debug/
|
||||
.idea/
|
||||
bazel-bin
|
||||
bazel-genfiles
|
||||
bazel-googletest
|
||||
bazel-out
|
||||
bazel-testlogs
|
||||
# python
|
||||
*.pyc
|
||||
|
||||
# Visual Studio files
|
||||
.vs
|
||||
*.sdf
|
||||
*.opensdf
|
||||
*.VC.opendb
|
||||
*.suo
|
||||
*.user
|
||||
_ReSharper.Caches/
|
||||
Win32-Debug/
|
||||
Win32-Release/
|
||||
x64-Debug/
|
||||
x64-Release/
|
||||
|
||||
# Ignore autoconf / automake files
|
||||
Makefile.in
|
||||
aclocal.m4
|
||||
configure
|
||||
build-aux/
|
||||
autom4te.cache/
|
||||
googletest/m4/libtool.m4
|
||||
googletest/m4/ltoptions.m4
|
||||
googletest/m4/ltsugar.m4
|
||||
googletest/m4/ltversion.m4
|
||||
googletest/m4/lt~obsolete.m4
|
||||
googlemock/m4
|
||||
|
||||
# Ignore generated directories.
|
||||
googlemock/fused-src/
|
||||
googletest/fused-src/
|
||||
|
||||
# macOS files
|
||||
.DS_Store
|
||||
googletest/.DS_Store
|
||||
googletest/xcode/.DS_Store
|
||||
|
||||
# Ignore cmake generated directories and files.
|
||||
CMakeFiles
|
||||
CTestTestfile.cmake
|
||||
Makefile
|
||||
cmake_install.cmake
|
||||
googlemock/CMakeFiles
|
||||
googlemock/CTestTestfile.cmake
|
||||
googlemock/Makefile
|
||||
googlemock/cmake_install.cmake
|
||||
googlemock/gtest
|
||||
/bin
|
||||
/googlemock/gmock.dir
|
||||
/googlemock/gmock_main.dir
|
||||
/googlemock/RUN_TESTS.vcxproj.filters
|
||||
/googlemock/RUN_TESTS.vcxproj
|
||||
/googlemock/INSTALL.vcxproj.filters
|
||||
/googlemock/INSTALL.vcxproj
|
||||
/googlemock/gmock_main.vcxproj.filters
|
||||
/googlemock/gmock_main.vcxproj
|
||||
/googlemock/gmock.vcxproj.filters
|
||||
/googlemock/gmock.vcxproj
|
||||
/googlemock/gmock.sln
|
||||
/googlemock/ALL_BUILD.vcxproj.filters
|
||||
/googlemock/ALL_BUILD.vcxproj
|
||||
/lib
|
||||
/Win32
|
||||
/ZERO_CHECK.vcxproj.filters
|
||||
/ZERO_CHECK.vcxproj
|
||||
/RUN_TESTS.vcxproj.filters
|
||||
/RUN_TESTS.vcxproj
|
||||
/INSTALL.vcxproj.filters
|
||||
/INSTALL.vcxproj
|
||||
/googletest-distribution.sln
|
||||
/CMakeCache.txt
|
||||
/ALL_BUILD.vcxproj.filters
|
||||
/ALL_BUILD.vcxproj
|
||||
@ -0,0 +1,190 @@
|
||||
# Copyright 2017 Google Inc.
|
||||
# All Rights Reserved.
|
||||
#
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are
|
||||
# met:
|
||||
#
|
||||
# * Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
# * Redistributions in binary form must reproduce the above
|
||||
# copyright notice, this list of conditions and the following disclaimer
|
||||
# in the documentation and/or other materials provided with the
|
||||
# distribution.
|
||||
# * Neither the name of Google Inc. nor the names of its
|
||||
# contributors may be used to endorse or promote products derived from
|
||||
# this software without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
#
|
||||
# Bazel Build for Google C++ Testing Framework(Google Test)
|
||||
|
||||
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
|
||||
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
licenses(["notice"])
|
||||
|
||||
exports_files(["LICENSE"])
|
||||
|
||||
config_setting(
|
||||
name = "windows",
|
||||
constraint_values = ["@platforms//os:windows"],
|
||||
)
|
||||
|
||||
config_setting(
|
||||
name = "msvc_compiler",
|
||||
flag_values = {
|
||||
"@bazel_tools//tools/cpp:compiler": "msvc-cl",
|
||||
},
|
||||
visibility = [":__subpackages__"],
|
||||
)
|
||||
|
||||
config_setting(
|
||||
name = "has_absl",
|
||||
values = {"define": "absl=1"},
|
||||
)
|
||||
|
||||
# Library that defines the FRIEND_TEST macro.
|
||||
cc_library(
|
||||
name = "gtest_prod",
|
||||
hdrs = ["googletest/include/gtest/gtest_prod.h"],
|
||||
includes = ["googletest/include"],
|
||||
)
|
||||
|
||||
# Google Test including Google Mock
|
||||
cc_library(
|
||||
name = "gtest",
|
||||
srcs = glob(
|
||||
include = [
|
||||
"googletest/src/*.cc",
|
||||
"googletest/src/*.h",
|
||||
"googletest/include/gtest/**/*.h",
|
||||
"googlemock/src/*.cc",
|
||||
"googlemock/include/gmock/**/*.h",
|
||||
],
|
||||
exclude = [
|
||||
"googletest/src/gtest-all.cc",
|
||||
"googletest/src/gtest_main.cc",
|
||||
"googlemock/src/gmock-all.cc",
|
||||
"googlemock/src/gmock_main.cc",
|
||||
],
|
||||
),
|
||||
hdrs = glob([
|
||||
"googletest/include/gtest/*.h",
|
||||
"googlemock/include/gmock/*.h",
|
||||
]),
|
||||
copts = select({
|
||||
":windows": [],
|
||||
"//conditions:default": ["-pthread"],
|
||||
}),
|
||||
defines = select({
|
||||
":has_absl": ["GTEST_HAS_ABSL=1"],
|
||||
"//conditions:default": [],
|
||||
}),
|
||||
features = select({
|
||||
":windows": ["windows_export_all_symbols"],
|
||||
"//conditions:default": [],
|
||||
}),
|
||||
includes = [
|
||||
"googlemock",
|
||||
"googlemock/include",
|
||||
"googletest",
|
||||
"googletest/include",
|
||||
],
|
||||
linkopts = select({
|
||||
":windows": [],
|
||||
"//conditions:default": ["-pthread"],
|
||||
}),
|
||||
deps = select({
|
||||
":has_absl": [
|
||||
"@com_google_absl//absl/debugging:failure_signal_handler",
|
||||
"@com_google_absl//absl/debugging:stacktrace",
|
||||
"@com_google_absl//absl/debugging:symbolize",
|
||||
"@com_google_absl//absl/strings",
|
||||
"@com_google_absl//absl/types:any",
|
||||
"@com_google_absl//absl/types:optional",
|
||||
"@com_google_absl//absl/types:variant",
|
||||
],
|
||||
"//conditions:default": [],
|
||||
}),
|
||||
)
|
||||
|
||||
cc_library(
|
||||
name = "gtest_main",
|
||||
srcs = ["googlemock/src/gmock_main.cc"],
|
||||
features = select({
|
||||
":windows": ["windows_export_all_symbols"],
|
||||
"//conditions:default": [],
|
||||
}),
|
||||
deps = [":gtest"],
|
||||
)
|
||||
|
||||
# The following rules build samples of how to use gTest.
|
||||
cc_library(
|
||||
name = "gtest_sample_lib",
|
||||
srcs = [
|
||||
"googletest/samples/sample1.cc",
|
||||
"googletest/samples/sample2.cc",
|
||||
"googletest/samples/sample4.cc",
|
||||
],
|
||||
hdrs = [
|
||||
"googletest/samples/prime_tables.h",
|
||||
"googletest/samples/sample1.h",
|
||||
"googletest/samples/sample2.h",
|
||||
"googletest/samples/sample3-inl.h",
|
||||
"googletest/samples/sample4.h",
|
||||
],
|
||||
features = select({
|
||||
":windows": ["windows_export_all_symbols"],
|
||||
"//conditions:default": [],
|
||||
}),
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "gtest_samples",
|
||||
size = "small",
|
||||
# All Samples except:
|
||||
# sample9 (main)
|
||||
# sample10 (main and takes a command line option and needs to be separate)
|
||||
srcs = [
|
||||
"googletest/samples/sample1_unittest.cc",
|
||||
"googletest/samples/sample2_unittest.cc",
|
||||
"googletest/samples/sample3_unittest.cc",
|
||||
"googletest/samples/sample4_unittest.cc",
|
||||
"googletest/samples/sample5_unittest.cc",
|
||||
"googletest/samples/sample6_unittest.cc",
|
||||
"googletest/samples/sample7_unittest.cc",
|
||||
"googletest/samples/sample8_unittest.cc",
|
||||
],
|
||||
linkstatic = 0,
|
||||
deps = [
|
||||
"gtest_sample_lib",
|
||||
":gtest_main",
|
||||
],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "sample9_unittest",
|
||||
size = "small",
|
||||
srcs = ["googletest/samples/sample9_unittest.cc"],
|
||||
deps = [":gtest"],
|
||||
)
|
||||
|
||||
cc_test(
|
||||
name = "sample10_unittest",
|
||||
size = "small",
|
||||
srcs = ["googletest/samples/sample10_unittest.cc"],
|
||||
deps = [":gtest"],
|
||||
)
|
||||
@ -0,0 +1,32 @@
|
||||
# Note: CMake support is community-based. The maintainers do not use CMake
|
||||
# internally.
|
||||
|
||||
cmake_minimum_required(VERSION 2.8.12)
|
||||
|
||||
if (POLICY CMP0048)
|
||||
cmake_policy(SET CMP0048 NEW)
|
||||
endif (POLICY CMP0048)
|
||||
|
||||
project(googletest-distribution)
|
||||
set(GOOGLETEST_VERSION 1.11.0)
|
||||
|
||||
if (CMAKE_VERSION VERSION_GREATER "3.0.2")
|
||||
if(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
enable_testing()
|
||||
|
||||
include(CMakeDependentOption)
|
||||
include(GNUInstallDirs)
|
||||
|
||||
#Note that googlemock target already builds googletest
|
||||
option(BUILD_GMOCK "Builds the googlemock subproject" ON)
|
||||
option(INSTALL_GTEST "Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)" ON)
|
||||
|
||||
if(BUILD_GMOCK)
|
||||
add_subdirectory( googlemock )
|
||||
else()
|
||||
add_subdirectory( googletest )
|
||||
endif()
|
||||
@ -0,0 +1,130 @@
|
||||
# How to become a contributor and submit your own code
|
||||
|
||||
## Contributor License Agreements
|
||||
|
||||
We'd love to accept your patches! Before we can take them, we have to jump a
|
||||
couple of legal hurdles.
|
||||
|
||||
Please fill out either the individual or corporate Contributor License Agreement
|
||||
(CLA).
|
||||
|
||||
* If you are an individual writing original source code and you're sure you
|
||||
own the intellectual property, then you'll need to sign an
|
||||
[individual CLA](https://developers.google.com/open-source/cla/individual).
|
||||
* If you work for a company that wants to allow you to contribute your work,
|
||||
then you'll need to sign a
|
||||
[corporate CLA](https://developers.google.com/open-source/cla/corporate).
|
||||
|
||||
Follow either of the two links above to access the appropriate CLA and
|
||||
instructions for how to sign and return it. Once we receive it, we'll be able to
|
||||
accept your pull requests.
|
||||
|
||||
## Are you a Googler?
|
||||
|
||||
If you are a Googler, please make an attempt to submit an internal change rather
|
||||
than a GitHub Pull Request. If you are not able to submit an internal change a
|
||||
PR is acceptable as an alternative.
|
||||
|
||||
## Contributing A Patch
|
||||
|
||||
1. Submit an issue describing your proposed change to the
|
||||
[issue tracker](https://github.com/google/googletest/issues).
|
||||
2. Please don't mix more than one logical change per submittal, because it
|
||||
makes the history hard to follow. If you want to make a change that doesn't
|
||||
have a corresponding issue in the issue tracker, please create one.
|
||||
3. Also, coordinate with team members that are listed on the issue in question.
|
||||
This ensures that work isn't being duplicated and communicating your plan
|
||||
early also generally leads to better patches.
|
||||
4. If your proposed change is accepted, and you haven't already done so, sign a
|
||||
Contributor License Agreement (see details above).
|
||||
5. Fork the desired repo, develop and test your code changes.
|
||||
6. Ensure that your code adheres to the existing style in the sample to which
|
||||
you are contributing.
|
||||
7. Ensure that your code has an appropriate set of unit tests which all pass.
|
||||
8. Submit a pull request.
|
||||
|
||||
## The Google Test and Google Mock Communities
|
||||
|
||||
The Google Test community exists primarily through the
|
||||
[discussion group](http://groups.google.com/group/googletestframework) and the
|
||||
GitHub repository. Likewise, the Google Mock community exists primarily through
|
||||
their own [discussion group](http://groups.google.com/group/googlemock). You are
|
||||
definitely encouraged to contribute to the discussion and you can also help us
|
||||
to keep the effectiveness of the group high by following and promoting the
|
||||
guidelines listed here.
|
||||
|
||||
### Please Be Friendly
|
||||
|
||||
Showing courtesy and respect to others is a vital part of the Google culture,
|
||||
and we strongly encourage everyone participating in Google Test development to
|
||||
join us in accepting nothing less. Of course, being courteous is not the same as
|
||||
failing to constructively disagree with each other, but it does mean that we
|
||||
should be respectful of each other when enumerating the 42 technical reasons
|
||||
that a particular proposal may not be the best choice. There's never a reason to
|
||||
be antagonistic or dismissive toward anyone who is sincerely trying to
|
||||
contribute to a discussion.
|
||||
|
||||
Sure, C++ testing is serious business and all that, but it's also a lot of fun.
|
||||
Let's keep it that way. Let's strive to be one of the friendliest communities in
|
||||
all of open source.
|
||||
|
||||
As always, discuss Google Test in the official GoogleTest discussion group. You
|
||||
don't have to actually submit code in order to sign up. Your participation
|
||||
itself is a valuable contribution.
|
||||
|
||||
## Style
|
||||
|
||||
To keep the source consistent, readable, diffable and easy to merge, we use a
|
||||
fairly rigid coding style, as defined by the
|
||||
[google-styleguide](https://github.com/google/styleguide) project. All patches
|
||||
will be expected to conform to the style outlined
|
||||
[here](https://google.github.io/styleguide/cppguide.html). Use
|
||||
[.clang-format](https://github.com/google/googletest/blob/master/.clang-format)
|
||||
to check your formatting.
|
||||
|
||||
## Requirements for Contributors
|
||||
|
||||
If you plan to contribute a patch, you need to build Google Test, Google Mock,
|
||||
and their own tests from a git checkout, which has further requirements:
|
||||
|
||||
* [Python](https://www.python.org/) v2.3 or newer (for running some of the
|
||||
tests and re-generating certain source files from templates)
|
||||
* [CMake](https://cmake.org/) v2.8.12 or newer
|
||||
|
||||
## Developing Google Test and Google Mock
|
||||
|
||||
This section discusses how to make your own changes to the Google Test project.
|
||||
|
||||
### Testing Google Test and Google Mock Themselves
|
||||
|
||||
To make sure your changes work as intended and don't break existing
|
||||
functionality, you'll want to compile and run Google Test and GoogleMock's own
|
||||
tests. For that you can use CMake:
|
||||
|
||||
mkdir mybuild
|
||||
cd mybuild
|
||||
cmake -Dgtest_build_tests=ON -Dgmock_build_tests=ON ${GTEST_REPO_DIR}
|
||||
|
||||
To choose between building only Google Test or Google Mock, you may modify your
|
||||
cmake command to be one of each
|
||||
|
||||
cmake -Dgtest_build_tests=ON ${GTEST_DIR} # sets up Google Test tests
|
||||
cmake -Dgmock_build_tests=ON ${GMOCK_DIR} # sets up Google Mock tests
|
||||
|
||||
Make sure you have Python installed, as some of Google Test's tests are written
|
||||
in Python. If the cmake command complains about not being able to find Python
|
||||
(`Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE)`), try telling it
|
||||
explicitly where your Python executable can be found:
|
||||
|
||||
cmake -DPYTHON_EXECUTABLE=path/to/python ...
|
||||
|
||||
Next, you can build Google Test and / or Google Mock and all desired tests. On
|
||||
\*nix, this is usually done by
|
||||
|
||||
make
|
||||
|
||||
To run the tests, do
|
||||
|
||||
make test
|
||||
|
||||
All tests should pass.
|
||||
@ -0,0 +1,63 @@
|
||||
# This file contains a list of people who've made non-trivial
|
||||
# contribution to the Google C++ Testing Framework project. People
|
||||
# who commit code to the project are encouraged to add their names
|
||||
# here. Please keep the list sorted by first names.
|
||||
|
||||
Ajay Joshi <jaj@google.com>
|
||||
Balázs Dán <balazs.dan@gmail.com>
|
||||
Benoit Sigoure <tsuna@google.com>
|
||||
Bharat Mediratta <bharat@menalto.com>
|
||||
Bogdan Piloca <boo@google.com>
|
||||
Chandler Carruth <chandlerc@google.com>
|
||||
Chris Prince <cprince@google.com>
|
||||
Chris Taylor <taylorc@google.com>
|
||||
Dan Egnor <egnor@google.com>
|
||||
Dave MacLachlan <dmaclach@gmail.com>
|
||||
David Anderson <danderson@google.com>
|
||||
Dean Sturtevant
|
||||
Eric Roman <eroman@chromium.org>
|
||||
Gene Volovich <gv@cite.com>
|
||||
Hady Zalek <hady.zalek@gmail.com>
|
||||
Hal Burch <gmock@hburch.com>
|
||||
Jeffrey Yasskin <jyasskin@google.com>
|
||||
Jim Keller <jimkeller@google.com>
|
||||
Joe Walnes <joe@truemesh.com>
|
||||
Jon Wray <jwray@google.com>
|
||||
Jói Sigurðsson <joi@google.com>
|
||||
Keir Mierle <mierle@gmail.com>
|
||||
Keith Ray <keith.ray@gmail.com>
|
||||
Kenton Varda <kenton@google.com>
|
||||
Kostya Serebryany <kcc@google.com>
|
||||
Krystian Kuzniarek <krystian.kuzniarek@gmail.com>
|
||||
Lev Makhlis
|
||||
Manuel Klimek <klimek@google.com>
|
||||
Mario Tanev <radix@google.com>
|
||||
Mark Paskin
|
||||
Markus Heule <markus.heule@gmail.com>
|
||||
Matthew Simmons <simmonmt@acm.org>
|
||||
Mika Raento <mikie@iki.fi>
|
||||
Mike Bland <mbland@google.com>
|
||||
Miklós Fazekas <mfazekas@szemafor.com>
|
||||
Neal Norwitz <nnorwitz@gmail.com>
|
||||
Nermin Ozkiranartli <nermin@google.com>
|
||||
Owen Carlsen <ocarlsen@google.com>
|
||||
Paneendra Ba <paneendra@google.com>
|
||||
Pasi Valminen <pasi.valminen@gmail.com>
|
||||
Patrick Hanna <phanna@google.com>
|
||||
Patrick Riley <pfr@google.com>
|
||||
Paul Menage <menage@google.com>
|
||||
Peter Kaminski <piotrk@google.com>
|
||||
Piotr Kaminski <piotrk@google.com>
|
||||
Preston Jackson <preston.a.jackson@gmail.com>
|
||||
Rainer Klaffenboeck <rainer.klaffenboeck@dynatrace.com>
|
||||
Russ Cox <rsc@google.com>
|
||||
Russ Rufer <russ@pentad.com>
|
||||
Sean Mcafee <eefacm@gmail.com>
|
||||
Sigurður Ásgeirsson <siggi@google.com>
|
||||
Sverre Sundsdal <sundsdal@gmail.com>
|
||||
Takeshi Yoshino <tyoshino@google.com>
|
||||
Tracy Bialik <tracy@pentad.com>
|
||||
Vadim Berman <vadimb@google.com>
|
||||
Vlad Losev <vladl@google.com>
|
||||
Wolfgang Klier <wklier@google.com>
|
||||
Zhanyong Wan <wan@google.com>
|
||||
@ -0,0 +1,28 @@
|
||||
Copyright 2008, Google Inc.
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@ -0,0 +1,140 @@
|
||||
# GoogleTest
|
||||
|
||||
### Announcements
|
||||
|
||||
#### Live at Head
|
||||
|
||||
GoogleTest now follows the
|
||||
[Abseil Live at Head philosophy](https://abseil.io/about/philosophy#upgrade-support).
|
||||
We recommend using the latest commit in the `master` branch in your projects.
|
||||
|
||||
#### Documentation Updates
|
||||
|
||||
Our documentation is now live on GitHub Pages at
|
||||
https://google.github.io/googletest/. We recommend browsing the documentation on
|
||||
GitHub Pages rather than directly in the repository.
|
||||
|
||||
#### Release 1.10.x
|
||||
|
||||
[Release 1.10.x](https://github.com/google/googletest/releases/tag/release-1.10.0)
|
||||
is now available.
|
||||
|
||||
#### Coming Soon
|
||||
|
||||
* We are planning to take a dependency on
|
||||
[Abseil](https://github.com/abseil/abseil-cpp).
|
||||
* More documentation improvements are planned.
|
||||
|
||||
## Welcome to **GoogleTest**, Google's C++ test framework!
|
||||
|
||||
This repository is a merger of the formerly separate GoogleTest and GoogleMock
|
||||
projects. These were so closely related that it makes sense to maintain and
|
||||
release them together.
|
||||
|
||||
### Getting Started
|
||||
|
||||
See the [GoogleTest User's Guide](https://google.github.io/googletest/) for
|
||||
documentation. We recommend starting with the
|
||||
[GoogleTest Primer](https://google.github.io/googletest/primer.html).
|
||||
|
||||
More information about building GoogleTest can be found at
|
||||
[googletest/README.md](googletest/README.md).
|
||||
|
||||
## Features
|
||||
|
||||
* An [xUnit](https://en.wikipedia.org/wiki/XUnit) test framework.
|
||||
* Test discovery.
|
||||
* A rich set of assertions.
|
||||
* User-defined assertions.
|
||||
* Death tests.
|
||||
* Fatal and non-fatal failures.
|
||||
* Value-parameterized tests.
|
||||
* Type-parameterized tests.
|
||||
* Various options for running the tests.
|
||||
* XML test report generation.
|
||||
|
||||
## Supported Platforms
|
||||
|
||||
GoogleTest requires a codebase and compiler compliant with the C++11 standard or
|
||||
newer.
|
||||
|
||||
The GoogleTest code is officially supported on the following platforms.
|
||||
Operating systems or tools not listed below are community-supported. For
|
||||
community-supported platforms, patches that do not complicate the code may be
|
||||
considered.
|
||||
|
||||
If you notice any problems on your platform, please file an issue on the
|
||||
[GoogleTest GitHub Issue Tracker](https://github.com/google/googletest/issues).
|
||||
Pull requests containing fixes are welcome!
|
||||
|
||||
### Operating Systems
|
||||
|
||||
* Linux
|
||||
* macOS
|
||||
* Windows
|
||||
|
||||
### Compilers
|
||||
|
||||
* gcc 5.0+
|
||||
* clang 5.0+
|
||||
* MSVC 2015+
|
||||
|
||||
**macOS users:** Xcode 9.3+ provides clang 5.0+.
|
||||
|
||||
### Build Systems
|
||||
|
||||
* [Bazel](https://bazel.build/)
|
||||
* [CMake](https://cmake.org/)
|
||||
|
||||
**Note:** Bazel is the build system used by the team internally and in tests.
|
||||
CMake is supported on a best-effort basis and by the community.
|
||||
|
||||
## Who Is Using GoogleTest?
|
||||
|
||||
In addition to many internal projects at Google, GoogleTest is also used by the
|
||||
following notable projects:
|
||||
|
||||
* The [Chromium projects](http://www.chromium.org/) (behind the Chrome browser
|
||||
and Chrome OS).
|
||||
* The [LLVM](http://llvm.org/) compiler.
|
||||
* [Protocol Buffers](https://github.com/google/protobuf), Google's data
|
||||
interchange format.
|
||||
* The [OpenCV](http://opencv.org/) computer vision library.
|
||||
|
||||
## Related Open Source Projects
|
||||
|
||||
[GTest Runner](https://github.com/nholthaus/gtest-runner) is a Qt5 based
|
||||
automated test-runner and Graphical User Interface with powerful features for
|
||||
Windows and Linux platforms.
|
||||
|
||||
[GoogleTest UI](https://github.com/ospector/gtest-gbar) is a test runner that
|
||||
runs your test binary, allows you to track its progress via a progress bar, and
|
||||
displays a list of test failures. Clicking on one shows failure text. Google
|
||||
Test UI is written in C#.
|
||||
|
||||
[GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event
|
||||
listener for GoogleTest that implements the
|
||||
[TAP protocol](https://en.wikipedia.org/wiki/Test_Anything_Protocol) for test
|
||||
result output. If your test runner understands TAP, you may find it useful.
|
||||
|
||||
[gtest-parallel](https://github.com/google/gtest-parallel) is a test runner that
|
||||
runs tests from your binary in parallel to provide significant speed-up.
|
||||
|
||||
[GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter)
|
||||
is a VS Code extension allowing to view GoogleTest in a tree view, and run/debug
|
||||
your tests.
|
||||
|
||||
[C++ TestMate](https://github.com/matepek/vscode-catch2-test-adapter) is a VS
|
||||
Code extension allowing to view GoogleTest in a tree view, and run/debug your
|
||||
tests.
|
||||
|
||||
[Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser
|
||||
that generates stub code for GoogleTest.
|
||||
|
||||
## Contributing Changes
|
||||
|
||||
Please read
|
||||
[`CONTRIBUTING.md`](https://github.com/google/googletest/blob/master/CONTRIBUTING.md)
|
||||
for details on how to contribute to this project.
|
||||
|
||||
Happy testing!
|
||||
@ -0,0 +1,24 @@
|
||||
workspace(name = "com_google_googletest")
|
||||
|
||||
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
|
||||
|
||||
http_archive(
|
||||
name = "com_google_absl",
|
||||
urls = ["https://github.com/abseil/abseil-cpp/archive/7971fb358ae376e016d2d4fc9327aad95659b25e.zip"], # 2021-05-20T02:59:16Z
|
||||
strip_prefix = "abseil-cpp-7971fb358ae376e016d2d4fc9327aad95659b25e",
|
||||
sha256 = "aeba534f7307e36fe084b452299e49b97420667a8d28102cf9a0daeed340b859",
|
||||
)
|
||||
|
||||
http_archive(
|
||||
name = "rules_cc",
|
||||
urls = ["https://github.com/bazelbuild/rules_cc/archive/68cb652a71e7e7e2858c50593e5a9e3b94e5b9a9.zip"], # 2021-05-14T14:51:14Z
|
||||
strip_prefix = "rules_cc-68cb652a71e7e7e2858c50593e5a9e3b94e5b9a9",
|
||||
sha256 = "1e19e9a3bc3d4ee91d7fcad00653485ee6c798efbbf9588d40b34cbfbded143d",
|
||||
)
|
||||
|
||||
http_archive(
|
||||
name = "rules_python",
|
||||
urls = ["https://github.com/bazelbuild/rules_python/archive/ed6cc8f2c3692a6a7f013ff8bc185ba77eb9b4d2.zip"], # 2021-05-17T00:24:16Z
|
||||
strip_prefix = "rules_python-ed6cc8f2c3692a6a7f013ff8bc185ba77eb9b4d2",
|
||||
sha256 = "98b3c592faea9636ac8444bfd9de7f3fb4c60590932d6e6ac5946e3f8dbd5ff6",
|
||||
)
|
||||
@ -0,0 +1,126 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Copyright 2020, Google Inc.
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are
|
||||
# met:
|
||||
#
|
||||
# * Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
# * Redistributions in binary form must reproduce the above
|
||||
# copyright notice, this list of conditions and the following disclaimer
|
||||
# in the documentation and/or other materials provided with the
|
||||
# distribution.
|
||||
# * Neither the name of Google Inc. nor the names of its
|
||||
# contributors may be used to endorse or promote products derived from
|
||||
# this software without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
set -euox pipefail
|
||||
|
||||
readonly LINUX_LATEST_CONTAINER="gcr.io/google.com/absl-177019/linux_hybrid-latest:20210525"
|
||||
readonly LINUX_GCC_FLOOR_CONTAINER="gcr.io/google.com/absl-177019/linux_gcc-floor:20201015"
|
||||
|
||||
if [[ -z ${GTEST_ROOT:-} ]]; then
|
||||
GTEST_ROOT="$(realpath $(dirname ${0})/..)"
|
||||
fi
|
||||
|
||||
if [[ -z ${STD:-} ]]; then
|
||||
STD="c++11 c++14 c++17 c++20"
|
||||
fi
|
||||
|
||||
# Test the CMake build
|
||||
for cc in /usr/local/bin/gcc /opt/llvm/clang/bin/clang; do
|
||||
for cmake_off_on in OFF ON; do
|
||||
time docker run \
|
||||
--volume="${GTEST_ROOT}:/src:ro" \
|
||||
--tmpfs="/build:exec" \
|
||||
--workdir="/build" \
|
||||
--rm \
|
||||
--env="CC=${cc}" \
|
||||
--env="CXX_FLAGS=\"-Werror -Wdeprecated\"" \
|
||||
${LINUX_LATEST_CONTAINER} \
|
||||
/bin/bash -c "
|
||||
cmake /src \
|
||||
-DCMAKE_CXX_STANDARD=11 \
|
||||
-Dgtest_build_samples=ON \
|
||||
-Dgtest_build_tests=ON \
|
||||
-Dgmock_build_tests=ON \
|
||||
-Dcxx_no_exception=${cmake_off_on} \
|
||||
-Dcxx_no_rtti=${cmake_off_on} && \
|
||||
make -j$(nproc) && \
|
||||
ctest -j$(nproc) --output-on-failure"
|
||||
done
|
||||
done
|
||||
|
||||
# Do one test with an older version of GCC
|
||||
time docker run \
|
||||
--volume="${GTEST_ROOT}:/src:ro" \
|
||||
--workdir="/src" \
|
||||
--rm \
|
||||
--env="CC=/usr/local/bin/gcc" \
|
||||
${LINUX_GCC_FLOOR_CONTAINER} \
|
||||
/usr/local/bin/bazel test ... \
|
||||
--copt="-Wall" \
|
||||
--copt="-Werror" \
|
||||
--copt="-Wno-error=pragmas" \
|
||||
--keep_going \
|
||||
--show_timestamps \
|
||||
--test_output=errors
|
||||
|
||||
# Test GCC
|
||||
for std in ${STD}; do
|
||||
for absl in 0 1; do
|
||||
time docker run \
|
||||
--volume="${GTEST_ROOT}:/src:ro" \
|
||||
--workdir="/src" \
|
||||
--rm \
|
||||
--env="CC=/usr/local/bin/gcc" \
|
||||
--env="BAZEL_CXXOPTS=-std=${std}" \
|
||||
${LINUX_LATEST_CONTAINER} \
|
||||
/usr/local/bin/bazel test ... \
|
||||
--copt="-Wall" \
|
||||
--copt="-Werror" \
|
||||
--define="absl=${absl}" \
|
||||
--distdir="/bazel-distdir" \
|
||||
--keep_going \
|
||||
--show_timestamps \
|
||||
--test_output=errors
|
||||
done
|
||||
done
|
||||
|
||||
# Test Clang
|
||||
for std in ${STD}; do
|
||||
for absl in 0 1; do
|
||||
time docker run \
|
||||
--volume="${GTEST_ROOT}:/src:ro" \
|
||||
--workdir="/src" \
|
||||
--rm \
|
||||
--env="CC=/opt/llvm/clang/bin/clang" \
|
||||
--env="BAZEL_CXXOPTS=-std=${std}" \
|
||||
${LINUX_LATEST_CONTAINER} \
|
||||
/usr/local/bin/bazel test ... \
|
||||
--copt="--gcc-toolchain=/usr/local" \
|
||||
--copt="-Wall" \
|
||||
--copt="-Werror" \
|
||||
--define="absl=${absl}" \
|
||||
--distdir="/bazel-distdir" \
|
||||
--keep_going \
|
||||
--linkopt="--gcc-toolchain=/usr/local" \
|
||||
--show_timestamps \
|
||||
--test_output=errors
|
||||
done
|
||||
done
|
||||
@ -0,0 +1,73 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Copyright 2020, Google Inc.
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source and binary forms, with or without
|
||||
# modification, are permitted provided that the following conditions are
|
||||
# met:
|
||||
#
|
||||
# * Redistributions of source code must retain the above copyright
|
||||
# notice, this list of conditions and the following disclaimer.
|
||||
# * Redistributions in binary form must reproduce the above
|
||||
# copyright notice, this list of conditions and the following disclaimer
|
||||
# in the documentation and/or other materials provided with the
|
||||
# distribution.
|
||||
# * Neither the name of Google Inc. nor the names of its
|
||||
# contributors may be used to endorse or promote products derived from
|
||||
# this software without specific prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
set -euox pipefail
|
||||
|
||||
if [[ -z ${GTEST_ROOT:-} ]]; then
|
||||
GTEST_ROOT="$(realpath $(dirname ${0})/..)"
|
||||
fi
|
||||
|
||||
# Test the CMake build
|
||||
for cmake_off_on in OFF ON; do
|
||||
BUILD_DIR=$(mktemp -d build_dir.XXXXXXXX)
|
||||
cd ${BUILD_DIR}
|
||||
time cmake ${GTEST_ROOT} \
|
||||
-DCMAKE_CXX_STANDARD=11 \
|
||||
-Dgtest_build_samples=ON \
|
||||
-Dgtest_build_tests=ON \
|
||||
-Dgmock_build_tests=ON \
|
||||
-Dcxx_no_exception=${cmake_off_on} \
|
||||
-Dcxx_no_rtti=${cmake_off_on}
|
||||
time make
|
||||
time ctest -j$(nproc) --output-on-failure
|
||||
done
|
||||
|
||||
# Test the Bazel build
|
||||
|
||||
# If we are running on Kokoro, check for a versioned Bazel binary.
|
||||
KOKORO_GFILE_BAZEL_BIN="bazel-3.7.0-darwin-x86_64"
|
||||
if [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f ${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN} ]]; then
|
||||
BAZEL_BIN="${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN}"
|
||||
chmod +x ${BAZEL_BIN}
|
||||
else
|
||||
BAZEL_BIN="bazel"
|
||||
fi
|
||||
|
||||
cd ${GTEST_ROOT}
|
||||
for absl in 0 1; do
|
||||
${BAZEL_BIN} test ... \
|
||||
--copt="-Wall" \
|
||||
--copt="-Werror" \
|
||||
--define="absl=${absl}" \
|
||||
--keep_going \
|
||||
--show_timestamps \
|
||||
--test_output=errors
|
||||
done
|
||||
@ -0,0 +1 @@
|
||||
title: GoogleTest
|
||||
@ -0,0 +1,43 @@
|
||||
nav:
|
||||
- section: "Get Started"
|
||||
items:
|
||||
- title: "Supported Platforms"
|
||||
url: "/platforms.html"
|
||||
- title: "Quickstart: Bazel"
|
||||
url: "/quickstart-bazel.html"
|
||||
- title: "Quickstart: CMake"
|
||||
url: "/quickstart-cmake.html"
|
||||
- section: "Guides"
|
||||
items:
|
||||
- title: "GoogleTest Primer"
|
||||
url: "/primer.html"
|
||||
- title: "Advanced Topics"
|
||||
url: "/advanced.html"
|
||||
- title: "Mocking for Dummies"
|
||||
url: "/gmock_for_dummies.html"
|
||||
- title: "Mocking Cookbook"
|
||||
url: "/gmock_cook_book.html"
|
||||
- title: "Mocking Cheat Sheet"
|
||||
url: "/gmock_cheat_sheet.html"
|
||||
- section: "References"
|
||||
items:
|
||||
- title: "Testing Reference"
|
||||
url: "/reference/testing.html"
|
||||
- title: "Mocking Reference"
|
||||
url: "/reference/mocking.html"
|
||||
- title: "Assertions"
|
||||
url: "/reference/assertions.html"
|
||||
- title: "Matchers"
|
||||
url: "/reference/matchers.html"
|
||||
- title: "Actions"
|
||||
url: "/reference/actions.html"
|
||||
- title: "Testing FAQ"
|
||||
url: "/faq.html"
|
||||
- title: "Mocking FAQ"
|
||||
url: "/gmock_faq.html"
|
||||
- title: "Code Samples"
|
||||
url: "/samples.html"
|
||||
- title: "Using pkg-config"
|
||||
url: "/pkgconfig.html"
|
||||
- title: "Community Documentation"
|
||||
url: "/community_created_documentation.html"
|
||||
@ -0,0 +1,58 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="{{ site.lang | default: "en-US" }}">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
|
||||
{% seo %}
|
||||
<link rel="stylesheet" href="{{ "/assets/css/style.css?v=" | append: site.github.build_revision | relative_url }}">
|
||||
<script>
|
||||
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
|
||||
ga('create', 'UA-197576187-1', { 'storage': 'none' });
|
||||
ga('set', 'referrer', document.referrer.split('?')[0]);
|
||||
ga('set', 'location', window.location.href.split('?')[0]);
|
||||
ga('set', 'anonymizeIp', true);
|
||||
ga('send', 'pageview');
|
||||
</script>
|
||||
<script async src='https://www.google-analytics.com/analytics.js'></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="sidebar">
|
||||
<div class="header">
|
||||
<h1><a href="{{ "/" | relative_url }}">{{ site.title | default: "Documentation" }}</a></h1>
|
||||
</div>
|
||||
<input type="checkbox" id="nav-toggle" class="nav-toggle">
|
||||
<label for="nav-toggle" class="expander">
|
||||
<span class="arrow"></span>
|
||||
</label>
|
||||
<nav>
|
||||
{% for item in site.data.navigation.nav %}
|
||||
<h2>{{ item.section }}</h2>
|
||||
<ul>
|
||||
{% for subitem in item.items %}
|
||||
<a href="{{subitem.url | relative_url }}">
|
||||
<li class="{% if subitem.url == page.url %}active{% endif %}">
|
||||
{{ subitem.title }}
|
||||
</li>
|
||||
</a>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endfor %}
|
||||
</nav>
|
||||
</div>
|
||||
<div class="main markdown-body">
|
||||
<div class="main-inner">
|
||||
{{ content }}
|
||||
</div>
|
||||
<div class="footer">
|
||||
GoogleTest ·
|
||||
<a href="https://github.com/google/googletest">GitHub Repository</a> ·
|
||||
<a href="https://github.com/google/googletest/blob/master/LICENSE">License</a> ·
|
||||
<a href="https://policies.google.com/privacy">Privacy Policy</a>
|
||||
</div>
|
||||
</div>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/4.1.0/anchor.min.js" integrity="sha256-lZaRhKri35AyJSypXXs4o6OPFTbTmUoltBbDCbdzegg=" crossorigin="anonymous"></script>
|
||||
<script>anchors.add('.main h2, .main h3, .main h4, .main h5, .main h6');</script>
|
||||
</body>
|
||||
</html>
|
||||
@ -0,0 +1,200 @@
|
||||
// Styles for GoogleTest docs website on GitHub Pages.
|
||||
// Color variables are defined in
|
||||
// https://github.com/pages-themes/primer/tree/master/_sass/primer-support/lib/variables
|
||||
|
||||
$sidebar-width: 260px;
|
||||
|
||||
body {
|
||||
display: flex;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
background: $black;
|
||||
color: $text-white;
|
||||
flex-shrink: 0;
|
||||
height: 100vh;
|
||||
overflow: auto;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
width: $sidebar-width;
|
||||
}
|
||||
|
||||
.sidebar h1 {
|
||||
font-size: 1.5em;
|
||||
}
|
||||
|
||||
.sidebar h2 {
|
||||
color: $gray-light;
|
||||
font-size: 0.8em;
|
||||
font-weight: normal;
|
||||
margin-bottom: 0.8em;
|
||||
padding-left: 2.5em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.sidebar .header {
|
||||
background: $black;
|
||||
padding: 2em;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.sidebar .header a {
|
||||
color: $text-white;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.sidebar .nav-toggle {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.sidebar .expander {
|
||||
cursor: pointer;
|
||||
display: none;
|
||||
height: 3em;
|
||||
position: absolute;
|
||||
right: 1em;
|
||||
top: 1.5em;
|
||||
width: 3em;
|
||||
}
|
||||
|
||||
.sidebar .expander .arrow {
|
||||
border: solid $white;
|
||||
border-width: 0 3px 3px 0;
|
||||
display: block;
|
||||
height: 0.7em;
|
||||
margin: 1em auto;
|
||||
transform: rotate(45deg);
|
||||
transition: transform 0.5s;
|
||||
width: 0.7em;
|
||||
}
|
||||
|
||||
.sidebar nav {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.sidebar nav ul {
|
||||
list-style-type: none;
|
||||
margin-bottom: 1em;
|
||||
padding: 0;
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 2em;
|
||||
}
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
li {
|
||||
color: $text-white;
|
||||
padding-left: 2em;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
li.active {
|
||||
background: $border-gray-darker;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
li:hover {
|
||||
background: $border-gray-darker;
|
||||
}
|
||||
}
|
||||
|
||||
.main {
|
||||
background-color: $bg-gray;
|
||||
width: calc(100% - #{$sidebar-width});
|
||||
}
|
||||
|
||||
.main .main-inner {
|
||||
background-color: $white;
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.main .footer {
|
||||
margin: 0;
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.main table th {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.main .callout {
|
||||
border-left: 0.25em solid $white;
|
||||
padding: 1em;
|
||||
|
||||
a {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
&.important {
|
||||
background-color: $bg-yellow-light;
|
||||
border-color: $bg-yellow;
|
||||
color: $black;
|
||||
}
|
||||
|
||||
&.note {
|
||||
background-color: $bg-blue-light;
|
||||
border-color: $text-blue;
|
||||
color: $text-blue;
|
||||
}
|
||||
|
||||
&.tip {
|
||||
background-color: $green-000;
|
||||
border-color: $green-700;
|
||||
color: $green-700;
|
||||
}
|
||||
|
||||
&.warning {
|
||||
background-color: $red-000;
|
||||
border-color: $text-red;
|
||||
color: $text-red;
|
||||
}
|
||||
}
|
||||
|
||||
.main .good pre {
|
||||
background-color: $bg-green-light;
|
||||
}
|
||||
|
||||
.main .bad pre {
|
||||
background-color: $red-000;
|
||||
}
|
||||
|
||||
@media all and (max-width: 768px) {
|
||||
body {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
height: auto;
|
||||
position: relative;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.sidebar .expander {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.sidebar nav {
|
||||
height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.sidebar .nav-toggle:checked {
|
||||
& ~ nav {
|
||||
height: auto;
|
||||
}
|
||||
|
||||
& + .expander .arrow {
|
||||
transform: rotate(-135deg);
|
||||
}
|
||||
}
|
||||
|
||||
.main {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,5 @@
|
||||
---
|
||||
---
|
||||
|
||||
@import "jekyll-theme-primer";
|
||||
@import "main";
|
||||
@ -0,0 +1,7 @@
|
||||
# Community-Created Documentation
|
||||
|
||||
The following is a list, in no particular order, of links to documentation
|
||||
created by the Googletest community.
|
||||
|
||||
* [Googlemock Insights](https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/googletest/insights.md),
|
||||
by [ElectricRCAircraftGuy](https://github.com/ElectricRCAircraftGuy)
|
||||
@ -0,0 +1,693 @@
|
||||
# Googletest FAQ
|
||||
|
||||
## Why should test suite names and test names not contain underscore?
|
||||
|
||||
{: .callout .note}
|
||||
Note: Googletest reserves underscore (`_`) for special purpose keywords, such as
|
||||
[the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition
|
||||
to the following rationale.
|
||||
|
||||
Underscore (`_`) is special, as C++ reserves the following to be used by the
|
||||
compiler and the standard library:
|
||||
|
||||
1. any identifier that starts with an `_` followed by an upper-case letter, and
|
||||
2. any identifier that contains two consecutive underscores (i.e. `__`)
|
||||
*anywhere* in its name.
|
||||
|
||||
User code is *prohibited* from using such identifiers.
|
||||
|
||||
Now let's look at what this means for `TEST` and `TEST_F`.
|
||||
|
||||
Currently `TEST(TestSuiteName, TestName)` generates a class named
|
||||
`TestSuiteName_TestName_Test`. What happens if `TestSuiteName` or `TestName`
|
||||
contains `_`?
|
||||
|
||||
1. If `TestSuiteName` starts with an `_` followed by an upper-case letter (say,
|
||||
`_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus
|
||||
invalid.
|
||||
2. If `TestSuiteName` ends with an `_` (say, `Foo_`), we get
|
||||
`Foo__TestName_Test`, which is invalid.
|
||||
3. If `TestName` starts with an `_` (say, `_Bar`), we get
|
||||
`TestSuiteName__Bar_Test`, which is invalid.
|
||||
4. If `TestName` ends with an `_` (say, `Bar_`), we get
|
||||
`TestSuiteName_Bar__Test`, which is invalid.
|
||||
|
||||
So clearly `TestSuiteName` and `TestName` cannot start or end with `_`
|
||||
(Actually, `TestSuiteName` can start with `_` -- as long as the `_` isn't
|
||||
followed by an upper-case letter. But that's getting complicated. So for
|
||||
simplicity we just say that it cannot start with `_`.).
|
||||
|
||||
It may seem fine for `TestSuiteName` and `TestName` to contain `_` in the
|
||||
middle. However, consider this:
|
||||
|
||||
```c++
|
||||
TEST(Time, Flies_Like_An_Arrow) { ... }
|
||||
TEST(Time_Flies, Like_An_Arrow) { ... }
|
||||
```
|
||||
|
||||
Now, the two `TEST`s will both generate the same class
|
||||
(`Time_Flies_Like_An_Arrow_Test`). That's not good.
|
||||
|
||||
So for simplicity, we just ask the users to avoid `_` in `TestSuiteName` and
|
||||
`TestName`. The rule is more constraining than necessary, but it's simple and
|
||||
easy to remember. It also gives googletest some wiggle room in case its
|
||||
implementation needs to change in the future.
|
||||
|
||||
If you violate the rule, there may not be immediate consequences, but your test
|
||||
may (just may) break with a new compiler (or a new version of the compiler you
|
||||
are using) or with a new version of googletest. Therefore it's best to follow
|
||||
the rule.
|
||||
|
||||
## Why does googletest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`?
|
||||
|
||||
First of all, you can use `nullptr` with each of these macros, e.g.
|
||||
`EXPECT_EQ(ptr, nullptr)`, `EXPECT_NE(ptr, nullptr)`, `ASSERT_EQ(ptr, nullptr)`,
|
||||
`ASSERT_NE(ptr, nullptr)`. This is the preferred syntax in the style guide
|
||||
because `nullptr` does not have the type problems that `NULL` does.
|
||||
|
||||
Due to some peculiarity of C++, it requires some non-trivial template meta
|
||||
programming tricks to support using `NULL` as an argument of the `EXPECT_XX()`
|
||||
and `ASSERT_XX()` macros. Therefore we only do it where it's most needed
|
||||
(otherwise we make the implementation of googletest harder to maintain and more
|
||||
error-prone than necessary).
|
||||
|
||||
Historically, the `EXPECT_EQ()` macro took the *expected* value as its first
|
||||
argument and the *actual* value as the second, though this argument order is now
|
||||
discouraged. It was reasonable that someone wanted
|
||||
to write `EXPECT_EQ(NULL, some_expression)`, and this indeed was requested
|
||||
several times. Therefore we implemented it.
|
||||
|
||||
The need for `EXPECT_NE(NULL, ptr)` wasn't nearly as strong. When the assertion
|
||||
fails, you already know that `ptr` must be `NULL`, so it doesn't add any
|
||||
information to print `ptr` in this case. That means `EXPECT_TRUE(ptr != NULL)`
|
||||
works just as well.
|
||||
|
||||
If we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'd have to
|
||||
support `EXPECT_NE(ptr, NULL)` as well. This means using the template meta
|
||||
programming tricks twice in the implementation, making it even harder to
|
||||
understand and maintain. We believe the benefit doesn't justify the cost.
|
||||
|
||||
Finally, with the growth of the gMock matcher library, we are encouraging people
|
||||
to use the unified `EXPECT_THAT(value, matcher)` syntax more often in tests. One
|
||||
significant advantage of the matcher approach is that matchers can be easily
|
||||
combined to form new matchers, while the `EXPECT_NE`, etc, macros cannot be
|
||||
easily combined. Therefore we want to invest more in the matchers than in the
|
||||
`EXPECT_XX()` macros.
|
||||
|
||||
## I need to test that different implementations of an interface satisfy some common requirements. Should I use typed tests or value-parameterized tests?
|
||||
|
||||
For testing various implementations of the same interface, either typed tests or
|
||||
value-parameterized tests can get it done. It's really up to you the user to
|
||||
decide which is more convenient for you, depending on your particular case. Some
|
||||
rough guidelines:
|
||||
|
||||
* Typed tests can be easier to write if instances of the different
|
||||
implementations can be created the same way, modulo the type. For example,
|
||||
if all these implementations have a public default constructor (such that
|
||||
you can write `new TypeParam`), or if their factory functions have the same
|
||||
form (e.g. `CreateInstance<TypeParam>()`).
|
||||
* Value-parameterized tests can be easier to write if you need different code
|
||||
patterns to create different implementations' instances, e.g. `new Foo` vs
|
||||
`new Bar(5)`. To accommodate for the differences, you can write factory
|
||||
function wrappers and pass these function pointers to the tests as their
|
||||
parameters.
|
||||
* When a typed test fails, the default output includes the name of the type,
|
||||
which can help you quickly identify which implementation is wrong.
|
||||
Value-parameterized tests only show the number of the failed iteration by
|
||||
default. You will need to define a function that returns the iteration name
|
||||
and pass it as the third parameter to INSTANTIATE_TEST_SUITE_P to have more
|
||||
useful output.
|
||||
* When using typed tests, you need to make sure you are testing against the
|
||||
interface type, not the concrete types (in other words, you want to make
|
||||
sure `implicit_cast<MyInterface*>(my_concrete_impl)` works, not just that
|
||||
`my_concrete_impl` works). It's less likely to make mistakes in this area
|
||||
when using value-parameterized tests.
|
||||
|
||||
I hope I didn't confuse you more. :-) If you don't mind, I'd suggest you to give
|
||||
both approaches a try. Practice is a much better way to grasp the subtle
|
||||
differences between the two tools. Once you have some concrete experience, you
|
||||
can much more easily decide which one to use the next time.
|
||||
|
||||
## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help!
|
||||
|
||||
{: .callout .note}
|
||||
**Note:** `ProtocolMessageEquals` and `ProtocolMessageEquiv` are *deprecated*
|
||||
now. Please use `EqualsProto`, etc instead.
|
||||
|
||||
`ProtocolMessageEquals` and `ProtocolMessageEquiv` were redefined recently and
|
||||
are now less tolerant of invalid protocol buffer definitions. In particular, if
|
||||
you have a `foo.proto` that doesn't fully qualify the type of a protocol message
|
||||
it references (e.g. `message<Bar>` where it should be `message<blah.Bar>`), you
|
||||
will now get run-time errors like:
|
||||
|
||||
```
|
||||
... descriptor.cc:...] Invalid proto descriptor for file "path/to/foo.proto":
|
||||
... descriptor.cc:...] blah.MyMessage.my_field: ".Bar" is not defined.
|
||||
```
|
||||
|
||||
If you see this, your `.proto` file is broken and needs to be fixed by making
|
||||
the types fully qualified. The new definition of `ProtocolMessageEquals` and
|
||||
`ProtocolMessageEquiv` just happen to reveal your bug.
|
||||
|
||||
## My death test modifies some state, but the change seems lost after the death test finishes. Why?
|
||||
|
||||
Death tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the
|
||||
expected crash won't kill the test program (i.e. the parent process). As a
|
||||
result, any in-memory side effects they incur are observable in their respective
|
||||
sub-processes, but not in the parent process. You can think of them as running
|
||||
in a parallel universe, more or less.
|
||||
|
||||
In particular, if you use mocking and the death test statement invokes some mock
|
||||
methods, the parent process will think the calls have never occurred. Therefore,
|
||||
you may want to move your `EXPECT_CALL` statements inside the `EXPECT_DEATH`
|
||||
macro.
|
||||
|
||||
## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a googletest bug?
|
||||
|
||||
Actually, the bug is in `htonl()`.
|
||||
|
||||
According to `'man htonl'`, `htonl()` is a *function*, which means it's valid to
|
||||
use `htonl` as a function pointer. However, in opt mode `htonl()` is defined as
|
||||
a *macro*, which breaks this usage.
|
||||
|
||||
Worse, the macro definition of `htonl()` uses a `gcc` extension and is *not*
|
||||
standard C++. That hacky implementation has some ad hoc limitations. In
|
||||
particular, it prevents you from writing `Foo<sizeof(htonl(x))>()`, where `Foo`
|
||||
is a template that has an integral argument.
|
||||
|
||||
The implementation of `EXPECT_EQ(a, b)` uses `sizeof(... a ...)` inside a
|
||||
template argument, and thus doesn't compile in opt mode when `a` contains a call
|
||||
to `htonl()`. It is difficult to make `EXPECT_EQ` bypass the `htonl()` bug, as
|
||||
the solution must work with different compilers on various platforms.
|
||||
|
||||
## The compiler complains about "undefined references" to some static const member variables, but I did define them in the class body. What's wrong?
|
||||
|
||||
If your class has a static data member:
|
||||
|
||||
```c++
|
||||
// foo.h
|
||||
class Foo {
|
||||
...
|
||||
static const int kBar = 100;
|
||||
};
|
||||
```
|
||||
|
||||
You also need to define it *outside* of the class body in `foo.cc`:
|
||||
|
||||
```c++
|
||||
const int Foo::kBar; // No initializer here.
|
||||
```
|
||||
|
||||
Otherwise your code is **invalid C++**, and may break in unexpected ways. In
|
||||
particular, using it in googletest comparison assertions (`EXPECT_EQ`, etc) will
|
||||
generate an "undefined reference" linker error. The fact that "it used to work"
|
||||
doesn't mean it's valid. It just means that you were lucky. :-)
|
||||
|
||||
If the declaration of the static data member is `constexpr` then it is
|
||||
implicitly an `inline` definition, and a separate definition in `foo.cc` is not
|
||||
needed:
|
||||
|
||||
```c++
|
||||
// foo.h
|
||||
class Foo {
|
||||
...
|
||||
static constexpr int kBar = 100; // Defines kBar, no need to do it in foo.cc.
|
||||
};
|
||||
```
|
||||
|
||||
## Can I derive a test fixture from another?
|
||||
|
||||
Yes.
|
||||
|
||||
Each test fixture has a corresponding and same named test suite. This means only
|
||||
one test suite can use a particular fixture. Sometimes, however, multiple test
|
||||
cases may want to use the same or slightly different fixtures. For example, you
|
||||
may want to make sure that all of a GUI library's test suites don't leak
|
||||
important system resources like fonts and brushes.
|
||||
|
||||
In googletest, you share a fixture among test suites by putting the shared logic
|
||||
in a base test fixture, then deriving from that base a separate fixture for each
|
||||
test suite that wants to use this common logic. You then use `TEST_F()` to write
|
||||
tests using each derived fixture.
|
||||
|
||||
Typically, your code looks like this:
|
||||
|
||||
```c++
|
||||
// Defines a base test fixture.
|
||||
class BaseTest : public ::testing::Test {
|
||||
protected:
|
||||
...
|
||||
};
|
||||
|
||||
// Derives a fixture FooTest from BaseTest.
|
||||
class FooTest : public BaseTest {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
BaseTest::SetUp(); // Sets up the base fixture first.
|
||||
... additional set-up work ...
|
||||
}
|
||||
|
||||
void TearDown() override {
|
||||
... clean-up work for FooTest ...
|
||||
BaseTest::TearDown(); // Remember to tear down the base fixture
|
||||
// after cleaning up FooTest!
|
||||
}
|
||||
|
||||
... functions and variables for FooTest ...
|
||||
};
|
||||
|
||||
// Tests that use the fixture FooTest.
|
||||
TEST_F(FooTest, Bar) { ... }
|
||||
TEST_F(FooTest, Baz) { ... }
|
||||
|
||||
... additional fixtures derived from BaseTest ...
|
||||
```
|
||||
|
||||
If necessary, you can continue to derive test fixtures from a derived fixture.
|
||||
googletest has no limit on how deep the hierarchy can be.
|
||||
|
||||
For a complete example using derived test fixtures, see
|
||||
[sample5_unittest.cc](https://github.com/google/googletest/blob/master/googletest/samples/sample5_unittest.cc).
|
||||
|
||||
## My compiler complains "void value not ignored as it ought to be." What does this mean?
|
||||
|
||||
You're probably using an `ASSERT_*()` in a function that doesn't return `void`.
|
||||
`ASSERT_*()` can only be used in `void` functions, due to exceptions being
|
||||
disabled by our build system. Please see more details
|
||||
[here](advanced.md#assertion-placement).
|
||||
|
||||
## My death test hangs (or seg-faults). How do I fix it?
|
||||
|
||||
In googletest, death tests are run in a child process and the way they work is
|
||||
delicate. To write death tests you really need to understand how they work—see
|
||||
the details at [Death Assertions](reference/assertions.md#death) in the
|
||||
Assertions Reference.
|
||||
|
||||
In particular, death tests don't like having multiple threads in the parent
|
||||
process. So the first thing you can try is to eliminate creating threads outside
|
||||
of `EXPECT_DEATH()`. For example, you may want to use mocks or fake objects
|
||||
instead of real ones in your tests.
|
||||
|
||||
Sometimes this is impossible as some library you must use may be creating
|
||||
threads before `main()` is even reached. In this case, you can try to minimize
|
||||
the chance of conflicts by either moving as many activities as possible inside
|
||||
`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or
|
||||
leaving as few things as possible in it. Also, you can try to set the death test
|
||||
style to `"threadsafe"`, which is safer but slower, and see if it helps.
|
||||
|
||||
If you go with thread-safe death tests, remember that they rerun the test
|
||||
program from the beginning in the child process. Therefore make sure your
|
||||
program can run side-by-side with itself and is deterministic.
|
||||
|
||||
In the end, this boils down to good concurrent programming. You have to make
|
||||
sure that there are no race conditions or deadlocks in your program. No silver
|
||||
bullet - sorry!
|
||||
|
||||
## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp}
|
||||
|
||||
The first thing to remember is that googletest does **not** reuse the same test
|
||||
fixture object across multiple tests. For each `TEST_F`, googletest will create
|
||||
a **fresh** test fixture object, immediately call `SetUp()`, run the test body,
|
||||
call `TearDown()`, and then delete the test fixture object.
|
||||
|
||||
When you need to write per-test set-up and tear-down logic, you have the choice
|
||||
between using the test fixture constructor/destructor or `SetUp()/TearDown()`.
|
||||
The former is usually preferred, as it has the following benefits:
|
||||
|
||||
* By initializing a member variable in the constructor, we have the option to
|
||||
make it `const`, which helps prevent accidental changes to its value and
|
||||
makes the tests more obviously correct.
|
||||
* In case we need to subclass the test fixture class, the subclass'
|
||||
constructor is guaranteed to call the base class' constructor *first*, and
|
||||
the subclass' destructor is guaranteed to call the base class' destructor
|
||||
*afterward*. With `SetUp()/TearDown()`, a subclass may make the mistake of
|
||||
forgetting to call the base class' `SetUp()/TearDown()` or call them at the
|
||||
wrong time.
|
||||
|
||||
You may still want to use `SetUp()/TearDown()` in the following cases:
|
||||
|
||||
* C++ does not allow virtual function calls in constructors and destructors.
|
||||
You can call a method declared as virtual, but it will not use dynamic
|
||||
dispatch, it will use the definition from the class the constructor of which
|
||||
is currently executing. This is because calling a virtual method before the
|
||||
derived class constructor has a chance to run is very dangerous - the
|
||||
virtual method might operate on uninitialized data. Therefore, if you need
|
||||
to call a method that will be overridden in a derived class, you have to use
|
||||
`SetUp()/TearDown()`.
|
||||
* In the body of a constructor (or destructor), it's not possible to use the
|
||||
`ASSERT_xx` macros. Therefore, if the set-up operation could cause a fatal
|
||||
test failure that should prevent the test from running, it's necessary to
|
||||
use `abort` and abort the whole test
|
||||
executable, or to use `SetUp()` instead of a constructor.
|
||||
* If the tear-down operation could throw an exception, you must use
|
||||
`TearDown()` as opposed to the destructor, as throwing in a destructor leads
|
||||
to undefined behavior and usually will kill your program right away. Note
|
||||
that many standard libraries (like STL) may throw when exceptions are
|
||||
enabled in the compiler. Therefore you should prefer `TearDown()` if you
|
||||
want to write portable tests that work with or without exceptions.
|
||||
* The googletest team is considering making the assertion macros throw on
|
||||
platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux
|
||||
client-side), which will eliminate the need for the user to propagate
|
||||
failures from a subroutine to its caller. Therefore, you shouldn't use
|
||||
googletest assertions in a destructor if your code could run on such a
|
||||
platform.
|
||||
|
||||
## The compiler complains "no matching function to call" when I use ASSERT_PRED*. How do I fix it?
|
||||
|
||||
See details for [`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the
|
||||
Assertions Reference.
|
||||
|
||||
## My compiler complains about "ignoring return value" when I call RUN_ALL_TESTS(). Why?
|
||||
|
||||
Some people had been ignoring the return value of `RUN_ALL_TESTS()`. That is,
|
||||
instead of
|
||||
|
||||
```c++
|
||||
return RUN_ALL_TESTS();
|
||||
```
|
||||
|
||||
they write
|
||||
|
||||
```c++
|
||||
RUN_ALL_TESTS();
|
||||
```
|
||||
|
||||
This is **wrong and dangerous**. The testing services needs to see the return
|
||||
value of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your
|
||||
`main()` function ignores it, your test will be considered successful even if it
|
||||
has a googletest assertion failure. Very bad.
|
||||
|
||||
We have decided to fix this (thanks to Michael Chastain for the idea). Now, your
|
||||
code will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with
|
||||
`gcc`. If you do so, you'll get a compiler error.
|
||||
|
||||
If you see the compiler complaining about you ignoring the return value of
|
||||
`RUN_ALL_TESTS()`, the fix is simple: just make sure its value is used as the
|
||||
return value of `main()`.
|
||||
|
||||
But how could we introduce a change that breaks existing tests? Well, in this
|
||||
case, the code was already broken in the first place, so we didn't break it. :-)
|
||||
|
||||
## My compiler complains that a constructor (or destructor) cannot return a value. What's going on?
|
||||
|
||||
Due to a peculiarity of C++, in order to support the syntax for streaming
|
||||
messages to an `ASSERT_*`, e.g.
|
||||
|
||||
```c++
|
||||
ASSERT_EQ(1, Foo()) << "blah blah" << foo;
|
||||
```
|
||||
|
||||
we had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and
|
||||
`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the
|
||||
content of your constructor/destructor to a private void member function, or
|
||||
switch to `EXPECT_*()` if that works. This
|
||||
[section](advanced.md#assertion-placement) in the user's guide explains it.
|
||||
|
||||
## My SetUp() function is not called. Why?
|
||||
|
||||
C++ is case-sensitive. Did you spell it as `Setup()`?
|
||||
|
||||
Similarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and
|
||||
wonder why it's never called.
|
||||
|
||||
|
||||
## I have several test suites which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious.
|
||||
|
||||
You don't have to. Instead of
|
||||
|
||||
```c++
|
||||
class FooTest : public BaseTest {};
|
||||
|
||||
TEST_F(FooTest, Abc) { ... }
|
||||
TEST_F(FooTest, Def) { ... }
|
||||
|
||||
class BarTest : public BaseTest {};
|
||||
|
||||
TEST_F(BarTest, Abc) { ... }
|
||||
TEST_F(BarTest, Def) { ... }
|
||||
```
|
||||
|
||||
you can simply `typedef` the test fixtures:
|
||||
|
||||
```c++
|
||||
typedef BaseTest FooTest;
|
||||
|
||||
TEST_F(FooTest, Abc) { ... }
|
||||
TEST_F(FooTest, Def) { ... }
|
||||
|
||||
typedef BaseTest BarTest;
|
||||
|
||||
TEST_F(BarTest, Abc) { ... }
|
||||
TEST_F(BarTest, Def) { ... }
|
||||
```
|
||||
|
||||
## googletest output is buried in a whole bunch of LOG messages. What do I do?
|
||||
|
||||
The googletest output is meant to be a concise and human-friendly report. If
|
||||
your test generates textual output itself, it will mix with the googletest
|
||||
output, making it hard to read. However, there is an easy solution to this
|
||||
problem.
|
||||
|
||||
Since `LOG` messages go to stderr, we decided to let googletest output go to
|
||||
stdout. This way, you can easily separate the two using redirection. For
|
||||
example:
|
||||
|
||||
```shell
|
||||
$ ./my_test > gtest_output.txt
|
||||
```
|
||||
|
||||
## Why should I prefer test fixtures over global variables?
|
||||
|
||||
There are several good reasons:
|
||||
|
||||
1. It's likely your test needs to change the states of its global variables.
|
||||
This makes it difficult to keep side effects from escaping one test and
|
||||
contaminating others, making debugging difficult. By using fixtures, each
|
||||
test has a fresh set of variables that's different (but with the same
|
||||
names). Thus, tests are kept independent of each other.
|
||||
2. Global variables pollute the global namespace.
|
||||
3. Test fixtures can be reused via subclassing, which cannot be done easily
|
||||
with global variables. This is useful if many test suites have something in
|
||||
common.
|
||||
|
||||
## What can the statement argument in ASSERT_DEATH() be?
|
||||
|
||||
`ASSERT_DEATH(statement, matcher)` (or any death assertion macro) can be used
|
||||
wherever *`statement`* is valid. So basically *`statement`* can be any C++
|
||||
statement that makes sense in the current context. In particular, it can
|
||||
reference global and/or local variables, and can be:
|
||||
|
||||
* a simple function call (often the case),
|
||||
* a complex expression, or
|
||||
* a compound statement.
|
||||
|
||||
Some examples are shown here:
|
||||
|
||||
```c++
|
||||
// A death test can be a simple function call.
|
||||
TEST(MyDeathTest, FunctionCall) {
|
||||
ASSERT_DEATH(Xyz(5), "Xyz failed");
|
||||
}
|
||||
|
||||
// Or a complex expression that references variables and functions.
|
||||
TEST(MyDeathTest, ComplexExpression) {
|
||||
const bool c = Condition();
|
||||
ASSERT_DEATH((c ? Func1(0) : object2.Method("test")),
|
||||
"(Func1|Method) failed");
|
||||
}
|
||||
|
||||
// Death assertions can be used anywhere in a function. In
|
||||
// particular, they can be inside a loop.
|
||||
TEST(MyDeathTest, InsideLoop) {
|
||||
// Verifies that Foo(0), Foo(1), ..., and Foo(4) all die.
|
||||
for (int i = 0; i < 5; i++) {
|
||||
EXPECT_DEATH_M(Foo(i), "Foo has \\d+ errors",
|
||||
::testing::Message() << "where i is " << i);
|
||||
}
|
||||
}
|
||||
|
||||
// A death assertion can contain a compound statement.
|
||||
TEST(MyDeathTest, CompoundStatement) {
|
||||
// Verifies that at lease one of Bar(0), Bar(1), ..., and
|
||||
// Bar(4) dies.
|
||||
ASSERT_DEATH({
|
||||
for (int i = 0; i < 5; i++) {
|
||||
Bar(i);
|
||||
}
|
||||
},
|
||||
"Bar has \\d+ errors");
|
||||
}
|
||||
```
|
||||
|
||||
## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``"no matching function for call to `FooTest::FooTest()'"``. Why?
|
||||
|
||||
Googletest needs to be able to create objects of your test fixture class, so it
|
||||
must have a default constructor. Normally the compiler will define one for you.
|
||||
However, there are cases where you have to define your own:
|
||||
|
||||
* If you explicitly declare a non-default constructor for class `FooTest`
|
||||
(`DISALLOW_EVIL_CONSTRUCTORS()` does this), then you need to define a
|
||||
default constructor, even if it would be empty.
|
||||
* If `FooTest` has a const non-static data member, then you have to define the
|
||||
default constructor *and* initialize the const member in the initializer
|
||||
list of the constructor. (Early versions of `gcc` doesn't force you to
|
||||
initialize the const member. It's a bug that has been fixed in `gcc 4`.)
|
||||
|
||||
## Why does ASSERT_DEATH complain about previous threads that were already joined?
|
||||
|
||||
With the Linux pthread library, there is no turning back once you cross the line
|
||||
from a single thread to multiple threads. The first time you create a thread, a
|
||||
manager thread is created in addition, so you get 3, not 2, threads. Later when
|
||||
the thread you create joins the main thread, the thread count decrements by 1,
|
||||
but the manager thread will never be killed, so you still have 2 threads, which
|
||||
means you cannot safely run a death test.
|
||||
|
||||
The new NPTL thread library doesn't suffer from this problem, as it doesn't
|
||||
create a manager thread. However, if you don't control which machine your test
|
||||
runs on, you shouldn't depend on this.
|
||||
|
||||
## Why does googletest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH?
|
||||
|
||||
googletest does not interleave tests from different test suites. That is, it
|
||||
runs all tests in one test suite first, and then runs all tests in the next test
|
||||
suite, and so on. googletest does this because it needs to set up a test suite
|
||||
before the first test in it is run, and tear it down afterwards. Splitting up
|
||||
the test case would require multiple set-up and tear-down processes, which is
|
||||
inefficient and makes the semantics unclean.
|
||||
|
||||
If we were to determine the order of tests based on test name instead of test
|
||||
case name, then we would have a problem with the following situation:
|
||||
|
||||
```c++
|
||||
TEST_F(FooTest, AbcDeathTest) { ... }
|
||||
TEST_F(FooTest, Uvw) { ... }
|
||||
|
||||
TEST_F(BarTest, DefDeathTest) { ... }
|
||||
TEST_F(BarTest, Xyz) { ... }
|
||||
```
|
||||
|
||||
Since `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't
|
||||
interleave tests from different test suites, we need to run all tests in the
|
||||
`FooTest` case before running any test in the `BarTest` case. This contradicts
|
||||
with the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`.
|
||||
|
||||
## But I don't like calling my entire test suite \*DeathTest when it contains both death tests and non-death tests. What do I do?
|
||||
|
||||
You don't have to, but if you like, you may split up the test suite into
|
||||
`FooTest` and `FooDeathTest`, where the names make it clear that they are
|
||||
related:
|
||||
|
||||
```c++
|
||||
class FooTest : public ::testing::Test { ... };
|
||||
|
||||
TEST_F(FooTest, Abc) { ... }
|
||||
TEST_F(FooTest, Def) { ... }
|
||||
|
||||
using FooDeathTest = FooTest;
|
||||
|
||||
TEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }
|
||||
TEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }
|
||||
```
|
||||
|
||||
## googletest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds?
|
||||
|
||||
Printing the LOG messages generated by the statement inside `EXPECT_DEATH()`
|
||||
makes it harder to search for real problems in the parent's log. Therefore,
|
||||
googletest only prints them when the death test has failed.
|
||||
|
||||
If you really need to see such LOG messages, a workaround is to temporarily
|
||||
break the death test (e.g. by changing the regex pattern it is expected to
|
||||
match). Admittedly, this is a hack. We'll consider a more permanent solution
|
||||
after the fork-and-exec-style death tests are implemented.
|
||||
|
||||
## The compiler complains about `no match for 'operator<<'` when I use an assertion. What gives?
|
||||
|
||||
If you use a user-defined type `FooType` in an assertion, you must make sure
|
||||
there is an `std::ostream& operator<<(std::ostream&, const FooType&)` function
|
||||
defined such that we can print a value of `FooType`.
|
||||
|
||||
In addition, if `FooType` is declared in a name space, the `<<` operator also
|
||||
needs to be defined in the *same* name space. See
|
||||
[Tip of the Week #49](http://abseil.io/tips/49) for details.
|
||||
|
||||
## How do I suppress the memory leak messages on Windows?
|
||||
|
||||
Since the statically initialized googletest singleton requires allocations on
|
||||
the heap, the Visual C++ memory leak detector will report memory leaks at the
|
||||
end of the program run. The easiest way to avoid this is to use the
|
||||
`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any
|
||||
statically initialized heap objects. See MSDN for more details and additional
|
||||
heap check/debug routines.
|
||||
|
||||
## How can my code detect if it is running in a test?
|
||||
|
||||
If you write code that sniffs whether it's running in a test and does different
|
||||
things accordingly, you are leaking test-only logic into production code and
|
||||
there is no easy way to ensure that the test-only code paths aren't run by
|
||||
mistake in production. Such cleverness also leads to
|
||||
[Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly
|
||||
advise against the practice, and googletest doesn't provide a way to do it.
|
||||
|
||||
In general, the recommended way to cause the code to behave differently under
|
||||
test is [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection). You can inject
|
||||
different functionality from the test and from the production code. Since your
|
||||
production code doesn't link in the for-test logic at all (the
|
||||
[`testonly`](http://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure
|
||||
that), there is no danger in accidentally running it.
|
||||
|
||||
However, if you *really*, *really*, *really* have no choice, and if you follow
|
||||
the rule of ending your test program names with `_test`, you can use the
|
||||
*horrible* hack of sniffing your executable name (`argv[0]` in `main()`) to know
|
||||
whether the code is under test.
|
||||
|
||||
## How do I temporarily disable a test?
|
||||
|
||||
If you have a broken test that you cannot fix right away, you can add the
|
||||
`DISABLED_` prefix to its name. This will exclude it from execution. This is
|
||||
better than commenting out the code or using `#if 0`, as disabled tests are
|
||||
still compiled (and thus won't rot).
|
||||
|
||||
To include disabled tests in test execution, just invoke the test program with
|
||||
the `--gtest_also_run_disabled_tests` flag.
|
||||
|
||||
## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces?
|
||||
|
||||
Yes.
|
||||
|
||||
The rule is **all test methods in the same test suite must use the same fixture
|
||||
class.** This means that the following is **allowed** because both tests use the
|
||||
same fixture class (`::testing::Test`).
|
||||
|
||||
```c++
|
||||
namespace foo {
|
||||
TEST(CoolTest, DoSomething) {
|
||||
SUCCEED();
|
||||
}
|
||||
} // namespace foo
|
||||
|
||||
namespace bar {
|
||||
TEST(CoolTest, DoSomething) {
|
||||
SUCCEED();
|
||||
}
|
||||
} // namespace bar
|
||||
```
|
||||
|
||||
However, the following code is **not allowed** and will produce a runtime error
|
||||
from googletest because the test methods are using different test fixture
|
||||
classes with the same test suite name.
|
||||
|
||||
```c++
|
||||
namespace foo {
|
||||
class CoolTest : public ::testing::Test {}; // Fixture foo::CoolTest
|
||||
TEST_F(CoolTest, DoSomething) {
|
||||
SUCCEED();
|
||||
}
|
||||
} // namespace foo
|
||||
|
||||
namespace bar {
|
||||
class CoolTest : public ::testing::Test {}; // Fixture: bar::CoolTest
|
||||
TEST_F(CoolTest, DoSomething) {
|
||||
SUCCEED();
|
||||
}
|
||||
} // namespace bar
|
||||
```
|
||||
@ -0,0 +1,241 @@
|
||||
# gMock Cheat Sheet
|
||||
|
||||
## Defining a Mock Class
|
||||
|
||||
### Mocking a Normal Class {#MockClass}
|
||||
|
||||
Given
|
||||
|
||||
```cpp
|
||||
class Foo {
|
||||
...
|
||||
virtual ~Foo();
|
||||
virtual int GetSize() const = 0;
|
||||
virtual string Describe(const char* name) = 0;
|
||||
virtual string Describe(int type) = 0;
|
||||
virtual bool Process(Bar elem, int count) = 0;
|
||||
};
|
||||
```
|
||||
|
||||
(note that `~Foo()` **must** be virtual) we can define its mock as
|
||||
|
||||
```cpp
|
||||
#include "gmock/gmock.h"
|
||||
|
||||
class MockFoo : public Foo {
|
||||
...
|
||||
MOCK_METHOD(int, GetSize, (), (const, override));
|
||||
MOCK_METHOD(string, Describe, (const char* name), (override));
|
||||
MOCK_METHOD(string, Describe, (int type), (override));
|
||||
MOCK_METHOD(bool, Process, (Bar elem, int count), (override));
|
||||
};
|
||||
```
|
||||
|
||||
To create a "nice" mock, which ignores all uninteresting calls, a "naggy" mock,
|
||||
which warns on all uninteresting calls, or a "strict" mock, which treats them as
|
||||
failures:
|
||||
|
||||
```cpp
|
||||
using ::testing::NiceMock;
|
||||
using ::testing::NaggyMock;
|
||||
using ::testing::StrictMock;
|
||||
|
||||
NiceMock<MockFoo> nice_foo; // The type is a subclass of MockFoo.
|
||||
NaggyMock<MockFoo> naggy_foo; // The type is a subclass of MockFoo.
|
||||
StrictMock<MockFoo> strict_foo; // The type is a subclass of MockFoo.
|
||||
```
|
||||
|
||||
{: .callout .note}
|
||||
**Note:** A mock object is currently naggy by default. We may make it nice by
|
||||
default in the future.
|
||||
|
||||
### Mocking a Class Template {#MockTemplate}
|
||||
|
||||
Class templates can be mocked just like any class.
|
||||
|
||||
To mock
|
||||
|
||||
```cpp
|
||||
template <typename Elem>
|
||||
class StackInterface {
|
||||
...
|
||||
virtual ~StackInterface();
|
||||
virtual int GetSize() const = 0;
|
||||
virtual void Push(const Elem& x) = 0;
|
||||
};
|
||||
```
|
||||
|
||||
(note that all member functions that are mocked, including `~StackInterface()`
|
||||
**must** be virtual).
|
||||
|
||||
```cpp
|
||||
template <typename Elem>
|
||||
class MockStack : public StackInterface<Elem> {
|
||||
...
|
||||
MOCK_METHOD(int, GetSize, (), (const, override));
|
||||
MOCK_METHOD(void, Push, (const Elem& x), (override));
|
||||
};
|
||||
```
|
||||
|
||||
### Specifying Calling Conventions for Mock Functions
|
||||
|
||||
If your mock function doesn't use the default calling convention, you can
|
||||
specify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter.
|
||||
For example,
|
||||
|
||||
```cpp
|
||||
MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE)));
|
||||
MOCK_METHOD(int, Bar, (double x, double y),
|
||||
(const, Calltype(STDMETHODCALLTYPE)));
|
||||
```
|
||||
|
||||
where `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows.
|
||||
|
||||
## Using Mocks in Tests {#UsingMocks}
|
||||
|
||||
The typical work flow is:
|
||||
|
||||
1. Import the gMock names you need to use. All gMock symbols are in the
|
||||
`testing` namespace unless they are macros or otherwise noted.
|
||||
2. Create the mock objects.
|
||||
3. Optionally, set the default actions of the mock objects.
|
||||
4. Set your expectations on the mock objects (How will they be called? What
|
||||
will they do?).
|
||||
5. Exercise code that uses the mock objects; if necessary, check the result
|
||||
using googletest assertions.
|
||||
6. When a mock object is destructed, gMock automatically verifies that all
|
||||
expectations on it have been satisfied.
|
||||
|
||||
Here's an example:
|
||||
|
||||
```cpp
|
||||
using ::testing::Return; // #1
|
||||
|
||||
TEST(BarTest, DoesThis) {
|
||||
MockFoo foo; // #2
|
||||
|
||||
ON_CALL(foo, GetSize()) // #3
|
||||
.WillByDefault(Return(1));
|
||||
// ... other default actions ...
|
||||
|
||||
EXPECT_CALL(foo, Describe(5)) // #4
|
||||
.Times(3)
|
||||
.WillRepeatedly(Return("Category 5"));
|
||||
// ... other expectations ...
|
||||
|
||||
EXPECT_EQ(MyProductionFunction(&foo), "good"); // #5
|
||||
} // #6
|
||||
```
|
||||
|
||||
## Setting Default Actions {#OnCall}
|
||||
|
||||
gMock has a **built-in default action** for any function that returns `void`,
|
||||
`bool`, a numeric value, or a pointer. In C++11, it will additionally returns
|
||||
the default-constructed value, if one exists for the given type.
|
||||
|
||||
To customize the default action for functions with return type `T`, use
|
||||
[`DefaultValue<T>`](reference/mocking.md#DefaultValue). For example:
|
||||
|
||||
```cpp
|
||||
// Sets the default action for return type std::unique_ptr<Buzz> to
|
||||
// creating a new Buzz every time.
|
||||
DefaultValue<std::unique_ptr<Buzz>>::SetFactory(
|
||||
[] { return MakeUnique<Buzz>(AccessLevel::kInternal); });
|
||||
|
||||
// When this fires, the default action of MakeBuzz() will run, which
|
||||
// will return a new Buzz object.
|
||||
EXPECT_CALL(mock_buzzer_, MakeBuzz("hello")).Times(AnyNumber());
|
||||
|
||||
auto buzz1 = mock_buzzer_.MakeBuzz("hello");
|
||||
auto buzz2 = mock_buzzer_.MakeBuzz("hello");
|
||||
EXPECT_NE(buzz1, nullptr);
|
||||
EXPECT_NE(buzz2, nullptr);
|
||||
EXPECT_NE(buzz1, buzz2);
|
||||
|
||||
// Resets the default action for return type std::unique_ptr<Buzz>,
|
||||
// to avoid interfere with other tests.
|
||||
DefaultValue<std::unique_ptr<Buzz>>::Clear();
|
||||
```
|
||||
|
||||
To customize the default action for a particular method of a specific mock
|
||||
object, use [`ON_CALL`](reference/mocking.md#ON_CALL). `ON_CALL` has a similar
|
||||
syntax to `EXPECT_CALL`, but it is used for setting default behaviors when you
|
||||
do not require that the mock method is called. See
|
||||
[Knowing When to Expect](gmock_cook_book.md#UseOnCall) for a more detailed
|
||||
discussion.
|
||||
|
||||
## Setting Expectations {#ExpectCall}
|
||||
|
||||
See [`EXPECT_CALL`](reference/mocking.md#EXPECT_CALL) in the Mocking Reference.
|
||||
|
||||
## Matchers {#MatcherList}
|
||||
|
||||
See the [Matchers Reference](reference/matchers.md).
|
||||
|
||||
## Actions {#ActionList}
|
||||
|
||||
See the [Actions Reference](reference/actions.md).
|
||||
|
||||
## Cardinalities {#CardinalityList}
|
||||
|
||||
See the [`Times` clause](reference/mocking.md#EXPECT_CALL.Times) of
|
||||
`EXPECT_CALL` in the Mocking Reference.
|
||||
|
||||
## Expectation Order
|
||||
|
||||
By default, expectations can be matched in *any* order. If some or all
|
||||
expectations must be matched in a given order, you can use the
|
||||
[`After` clause](reference/mocking.md#EXPECT_CALL.After) or
|
||||
[`InSequence` clause](reference/mocking.md#EXPECT_CALL.InSequence) of
|
||||
`EXPECT_CALL`, or use an [`InSequence` object](reference/mocking.md#InSequence).
|
||||
|
||||
## Verifying and Resetting a Mock
|
||||
|
||||
gMock will verify the expectations on a mock object when it is destructed, or
|
||||
you can do it earlier:
|
||||
|
||||
```cpp
|
||||
using ::testing::Mock;
|
||||
...
|
||||
// Verifies and removes the expectations on mock_obj;
|
||||
// returns true if and only if successful.
|
||||
Mock::VerifyAndClearExpectations(&mock_obj);
|
||||
...
|
||||
// Verifies and removes the expectations on mock_obj;
|
||||
// also removes the default actions set by ON_CALL();
|
||||
// returns true if and only if successful.
|
||||
Mock::VerifyAndClear(&mock_obj);
|
||||
```
|
||||
|
||||
Do not set new expectations after verifying and clearing a mock after its use.
|
||||
Setting expectations after code that exercises the mock has undefined behavior.
|
||||
See [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more
|
||||
information.
|
||||
|
||||
You can also tell gMock that a mock object can be leaked and doesn't need to be
|
||||
verified:
|
||||
|
||||
```cpp
|
||||
Mock::AllowLeak(&mock_obj);
|
||||
```
|
||||
|
||||
## Mock Classes
|
||||
|
||||
gMock defines a convenient mock class template
|
||||
|
||||
```cpp
|
||||
class MockFunction<R(A1, ..., An)> {
|
||||
public:
|
||||
MOCK_METHOD(R, Call, (A1, ..., An));
|
||||
};
|
||||
```
|
||||
|
||||
See this [recipe](gmock_cook_book.md#using-check-points) for one application of
|
||||
it.
|
||||
|
||||
## Flags
|
||||
|
||||
| Flag | Description |
|
||||
| :----------------------------- | :---------------------------------------- |
|
||||
| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. |
|
||||
| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,390 @@
|
||||
# Legacy gMock FAQ
|
||||
|
||||
### When I call a method on my mock object, the method for the real object is invoked instead. What's the problem?
|
||||
|
||||
In order for a method to be mocked, it must be *virtual*, unless you use the
|
||||
[high-perf dependency injection technique](gmock_cook_book.md#MockingNonVirtualMethods).
|
||||
|
||||
### Can I mock a variadic function?
|
||||
|
||||
You cannot mock a variadic function (i.e. a function taking ellipsis (`...`)
|
||||
arguments) directly in gMock.
|
||||
|
||||
The problem is that in general, there is *no way* for a mock object to know how
|
||||
many arguments are passed to the variadic method, and what the arguments' types
|
||||
are. Only the *author of the base class* knows the protocol, and we cannot look
|
||||
into his or her head.
|
||||
|
||||
Therefore, to mock such a function, the *user* must teach the mock object how to
|
||||
figure out the number of arguments and their types. One way to do it is to
|
||||
provide overloaded versions of the function.
|
||||
|
||||
Ellipsis arguments are inherited from C and not really a C++ feature. They are
|
||||
unsafe to use and don't work with arguments that have constructors or
|
||||
destructors. Therefore we recommend to avoid them in C++ as much as possible.
|
||||
|
||||
### MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why?
|
||||
|
||||
If you compile this using Microsoft Visual C++ 2005 SP1:
|
||||
|
||||
```cpp
|
||||
class Foo {
|
||||
...
|
||||
virtual void Bar(const int i) = 0;
|
||||
};
|
||||
|
||||
class MockFoo : public Foo {
|
||||
...
|
||||
MOCK_METHOD(void, Bar, (const int i), (override));
|
||||
};
|
||||
```
|
||||
|
||||
You may get the following warning:
|
||||
|
||||
```shell
|
||||
warning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier
|
||||
```
|
||||
|
||||
This is a MSVC bug. The same code compiles fine with gcc, for example. If you
|
||||
use Visual C++ 2008 SP1, you would get the warning:
|
||||
|
||||
```shell
|
||||
warning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers
|
||||
```
|
||||
|
||||
In C++, if you *declare* a function with a `const` parameter, the `const`
|
||||
modifier is ignored. Therefore, the `Foo` base class above is equivalent to:
|
||||
|
||||
```cpp
|
||||
class Foo {
|
||||
...
|
||||
virtual void Bar(int i) = 0; // int or const int? Makes no difference.
|
||||
};
|
||||
```
|
||||
|
||||
In fact, you can *declare* `Bar()` with an `int` parameter, and define it with a
|
||||
`const int` parameter. The compiler will still match them up.
|
||||
|
||||
Since making a parameter `const` is meaningless in the method declaration, we
|
||||
recommend to remove it in both `Foo` and `MockFoo`. That should workaround the
|
||||
VC bug.
|
||||
|
||||
Note that we are talking about the *top-level* `const` modifier here. If the
|
||||
function parameter is passed by pointer or reference, declaring the pointee or
|
||||
referee as `const` is still meaningful. For example, the following two
|
||||
declarations are *not* equivalent:
|
||||
|
||||
```cpp
|
||||
void Bar(int* p); // Neither p nor *p is const.
|
||||
void Bar(const int* p); // p is not const, but *p is.
|
||||
```
|
||||
|
||||
### I can't figure out why gMock thinks my expectations are not satisfied. What should I do?
|
||||
|
||||
You might want to run your test with `--gmock_verbose=info`. This flag lets
|
||||
gMock print a trace of every mock function call it receives. By studying the
|
||||
trace, you'll gain insights on why the expectations you set are not met.
|
||||
|
||||
If you see the message "The mock function has no default action set, and its
|
||||
return type has no default value set.", then try
|
||||
[adding a default action](gmock_cheat_sheet.md#OnCall). Due to a known issue,
|
||||
unexpected calls on mocks without default actions don't print out a detailed
|
||||
comparison between the actual arguments and the expected arguments.
|
||||
|
||||
### My program crashed and `ScopedMockLog` spit out tons of messages. Is it a gMock bug?
|
||||
|
||||
gMock and `ScopedMockLog` are likely doing the right thing here.
|
||||
|
||||
When a test crashes, the failure signal handler will try to log a lot of
|
||||
information (the stack trace, and the address map, for example). The messages
|
||||
are compounded if you have many threads with depth stacks. When `ScopedMockLog`
|
||||
intercepts these messages and finds that they don't match any expectations, it
|
||||
prints an error for each of them.
|
||||
|
||||
You can learn to ignore the errors, or you can rewrite your expectations to make
|
||||
your test more robust, for example, by adding something like:
|
||||
|
||||
```cpp
|
||||
using ::testing::AnyNumber;
|
||||
using ::testing::Not;
|
||||
...
|
||||
// Ignores any log not done by us.
|
||||
EXPECT_CALL(log, Log(_, Not(EndsWith("/my_file.cc")), _))
|
||||
.Times(AnyNumber());
|
||||
```
|
||||
|
||||
### How can I assert that a function is NEVER called?
|
||||
|
||||
```cpp
|
||||
using ::testing::_;
|
||||
...
|
||||
EXPECT_CALL(foo, Bar(_))
|
||||
.Times(0);
|
||||
```
|
||||
|
||||
### I have a failed test where gMock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant?
|
||||
|
||||
When gMock detects a failure, it prints relevant information (the mock function
|
||||
arguments, the state of relevant expectations, and etc) to help the user debug.
|
||||
If another failure is detected, gMock will do the same, including printing the
|
||||
state of relevant expectations.
|
||||
|
||||
Sometimes an expectation's state didn't change between two failures, and you'll
|
||||
see the same description of the state twice. They are however *not* redundant,
|
||||
as they refer to *different points in time*. The fact they are the same *is*
|
||||
interesting information.
|
||||
|
||||
### I get a heapcheck failure when using a mock object, but using a real object is fine. What can be wrong?
|
||||
|
||||
Does the class (hopefully a pure interface) you are mocking have a virtual
|
||||
destructor?
|
||||
|
||||
Whenever you derive from a base class, make sure its destructor is virtual.
|
||||
Otherwise Bad Things will happen. Consider the following code:
|
||||
|
||||
```cpp
|
||||
class Base {
|
||||
public:
|
||||
// Not virtual, but should be.
|
||||
~Base() { ... }
|
||||
...
|
||||
};
|
||||
|
||||
class Derived : public Base {
|
||||
public:
|
||||
...
|
||||
private:
|
||||
std::string value_;
|
||||
};
|
||||
|
||||
...
|
||||
Base* p = new Derived;
|
||||
...
|
||||
delete p; // Surprise! ~Base() will be called, but ~Derived() will not
|
||||
// - value_ is leaked.
|
||||
```
|
||||
|
||||
By changing `~Base()` to virtual, `~Derived()` will be correctly called when
|
||||
`delete p` is executed, and the heap checker will be happy.
|
||||
|
||||
### The "newer expectations override older ones" rule makes writing expectations awkward. Why does gMock do that?
|
||||
|
||||
When people complain about this, often they are referring to code like:
|
||||
|
||||
```cpp
|
||||
using ::testing::Return;
|
||||
...
|
||||
// foo.Bar() should be called twice, return 1 the first time, and return
|
||||
// 2 the second time. However, I have to write the expectations in the
|
||||
// reverse order. This sucks big time!!!
|
||||
EXPECT_CALL(foo, Bar())
|
||||
.WillOnce(Return(2))
|
||||
.RetiresOnSaturation();
|
||||
EXPECT_CALL(foo, Bar())
|
||||
.WillOnce(Return(1))
|
||||
.RetiresOnSaturation();
|
||||
```
|
||||
|
||||
The problem, is that they didn't pick the **best** way to express the test's
|
||||
intent.
|
||||
|
||||
By default, expectations don't have to be matched in *any* particular order. If
|
||||
you want them to match in a certain order, you need to be explicit. This is
|
||||
gMock's (and jMock's) fundamental philosophy: it's easy to accidentally
|
||||
over-specify your tests, and we want to make it harder to do so.
|
||||
|
||||
There are two better ways to write the test spec. You could either put the
|
||||
expectations in sequence:
|
||||
|
||||
```cpp
|
||||
using ::testing::Return;
|
||||
...
|
||||
// foo.Bar() should be called twice, return 1 the first time, and return
|
||||
// 2 the second time. Using a sequence, we can write the expectations
|
||||
// in their natural order.
|
||||
{
|
||||
InSequence s;
|
||||
EXPECT_CALL(foo, Bar())
|
||||
.WillOnce(Return(1))
|
||||
.RetiresOnSaturation();
|
||||
EXPECT_CALL(foo, Bar())
|
||||
.WillOnce(Return(2))
|
||||
.RetiresOnSaturation();
|
||||
}
|
||||
```
|
||||
|
||||
or you can put the sequence of actions in the same expectation:
|
||||
|
||||
```cpp
|
||||
using ::testing::Return;
|
||||
...
|
||||
// foo.Bar() should be called twice, return 1 the first time, and return
|
||||
// 2 the second time.
|
||||
EXPECT_CALL(foo, Bar())
|
||||
.WillOnce(Return(1))
|
||||
.WillOnce(Return(2))
|
||||
.RetiresOnSaturation();
|
||||
```
|
||||
|
||||
Back to the original questions: why does gMock search the expectations (and
|
||||
`ON_CALL`s) from back to front? Because this allows a user to set up a mock's
|
||||
behavior for the common case early (e.g. in the mock's constructor or the test
|
||||
fixture's set-up phase) and customize it with more specific rules later. If
|
||||
gMock searches from front to back, this very useful pattern won't be possible.
|
||||
|
||||
### gMock prints a warning when a function without EXPECT_CALL is called, even if I have set its behavior using ON_CALL. Would it be reasonable not to show the warning in this case?
|
||||
|
||||
When choosing between being neat and being safe, we lean toward the latter. So
|
||||
the answer is that we think it's better to show the warning.
|
||||
|
||||
Often people write `ON_CALL`s in the mock object's constructor or `SetUp()`, as
|
||||
the default behavior rarely changes from test to test. Then in the test body
|
||||
they set the expectations, which are often different for each test. Having an
|
||||
`ON_CALL` in the set-up part of a test doesn't mean that the calls are expected.
|
||||
If there's no `EXPECT_CALL` and the method is called, it's possibly an error. If
|
||||
we quietly let the call go through without notifying the user, bugs may creep in
|
||||
unnoticed.
|
||||
|
||||
If, however, you are sure that the calls are OK, you can write
|
||||
|
||||
```cpp
|
||||
using ::testing::_;
|
||||
...
|
||||
EXPECT_CALL(foo, Bar(_))
|
||||
.WillRepeatedly(...);
|
||||
```
|
||||
|
||||
instead of
|
||||
|
||||
```cpp
|
||||
using ::testing::_;
|
||||
...
|
||||
ON_CALL(foo, Bar(_))
|
||||
.WillByDefault(...);
|
||||
```
|
||||
|
||||
This tells gMock that you do expect the calls and no warning should be printed.
|
||||
|
||||
Also, you can control the verbosity by specifying `--gmock_verbose=error`. Other
|
||||
values are `info` and `warning`. If you find the output too noisy when
|
||||
debugging, just choose a less verbose level.
|
||||
|
||||
### How can I delete the mock function's argument in an action?
|
||||
|
||||
If your mock function takes a pointer argument and you want to delete that
|
||||
argument, you can use testing::DeleteArg<N>() to delete the N'th (zero-indexed)
|
||||
argument:
|
||||
|
||||
```cpp
|
||||
using ::testing::_;
|
||||
...
|
||||
MOCK_METHOD(void, Bar, (X* x, const Y& y));
|
||||
...
|
||||
EXPECT_CALL(mock_foo_, Bar(_, _))
|
||||
.WillOnce(testing::DeleteArg<0>()));
|
||||
```
|
||||
|
||||
### How can I perform an arbitrary action on a mock function's argument?
|
||||
|
||||
If you find yourself needing to perform some action that's not supported by
|
||||
gMock directly, remember that you can define your own actions using
|
||||
[`MakeAction()`](#NewMonoActions) or
|
||||
[`MakePolymorphicAction()`](#NewPolyActions), or you can write a stub function
|
||||
and invoke it using [`Invoke()`](#FunctionsAsActions).
|
||||
|
||||
```cpp
|
||||
using ::testing::_;
|
||||
using ::testing::Invoke;
|
||||
...
|
||||
MOCK_METHOD(void, Bar, (X* p));
|
||||
...
|
||||
EXPECT_CALL(mock_foo_, Bar(_))
|
||||
.WillOnce(Invoke(MyAction(...)));
|
||||
```
|
||||
|
||||
### My code calls a static/global function. Can I mock it?
|
||||
|
||||
You can, but you need to make some changes.
|
||||
|
||||
In general, if you find yourself needing to mock a static function, it's a sign
|
||||
that your modules are too tightly coupled (and less flexible, less reusable,
|
||||
less testable, etc). You are probably better off defining a small interface and
|
||||
call the function through that interface, which then can be easily mocked. It's
|
||||
a bit of work initially, but usually pays for itself quickly.
|
||||
|
||||
This Google Testing Blog
|
||||
[post](https://testing.googleblog.com/2008/06/defeat-static-cling.html) says it
|
||||
excellently. Check it out.
|
||||
|
||||
### My mock object needs to do complex stuff. It's a lot of pain to specify the actions. gMock sucks!
|
||||
|
||||
I know it's not a question, but you get an answer for free any way. :-)
|
||||
|
||||
With gMock, you can create mocks in C++ easily. And people might be tempted to
|
||||
use them everywhere. Sometimes they work great, and sometimes you may find them,
|
||||
well, a pain to use. So, what's wrong in the latter case?
|
||||
|
||||
When you write a test without using mocks, you exercise the code and assert that
|
||||
it returns the correct value or that the system is in an expected state. This is
|
||||
sometimes called "state-based testing".
|
||||
|
||||
Mocks are great for what some call "interaction-based" testing: instead of
|
||||
checking the system state at the very end, mock objects verify that they are
|
||||
invoked the right way and report an error as soon as it arises, giving you a
|
||||
handle on the precise context in which the error was triggered. This is often
|
||||
more effective and economical to do than state-based testing.
|
||||
|
||||
If you are doing state-based testing and using a test double just to simulate
|
||||
the real object, you are probably better off using a fake. Using a mock in this
|
||||
case causes pain, as it's not a strong point for mocks to perform complex
|
||||
actions. If you experience this and think that mocks suck, you are just not
|
||||
using the right tool for your problem. Or, you might be trying to solve the
|
||||
wrong problem. :-)
|
||||
|
||||
### I got a warning "Uninteresting function call encountered - default action taken.." Should I panic?
|
||||
|
||||
By all means, NO! It's just an FYI. :-)
|
||||
|
||||
What it means is that you have a mock function, you haven't set any expectations
|
||||
on it (by gMock's rule this means that you are not interested in calls to this
|
||||
function and therefore it can be called any number of times), and it is called.
|
||||
That's OK - you didn't say it's not OK to call the function!
|
||||
|
||||
What if you actually meant to disallow this function to be called, but forgot to
|
||||
write `EXPECT_CALL(foo, Bar()).Times(0)`? While one can argue that it's the
|
||||
user's fault, gMock tries to be nice and prints you a note.
|
||||
|
||||
So, when you see the message and believe that there shouldn't be any
|
||||
uninteresting calls, you should investigate what's going on. To make your life
|
||||
easier, gMock dumps the stack trace when an uninteresting call is encountered.
|
||||
From that you can figure out which mock function it is, and how it is called.
|
||||
|
||||
### I want to define a custom action. Should I use Invoke() or implement the ActionInterface interface?
|
||||
|
||||
Either way is fine - you want to choose the one that's more convenient for your
|
||||
circumstance.
|
||||
|
||||
Usually, if your action is for a particular function type, defining it using
|
||||
`Invoke()` should be easier; if your action can be used in functions of
|
||||
different types (e.g. if you are defining `Return(*value*)`),
|
||||
`MakePolymorphicAction()` is easiest. Sometimes you want precise control on what
|
||||
types of functions the action can be used in, and implementing `ActionInterface`
|
||||
is the way to go here. See the implementation of `Return()` in
|
||||
`testing/base/public/gmock-actions.h` for an example.
|
||||
|
||||
### I use SetArgPointee() in WillOnce(), but gcc complains about "conflicting return type specified". What does it mean?
|
||||
|
||||
You got this error as gMock has no idea what value it should return when the
|
||||
mock method is called. `SetArgPointee()` says what the side effect is, but
|
||||
doesn't say what the return value should be. You need `DoAll()` to chain a
|
||||
`SetArgPointee()` with a `Return()` that provides a value appropriate to the API
|
||||
being mocked.
|
||||
|
||||
See this [recipe](gmock_cook_book.md#mocking-side-effects) for more details and
|
||||
an example.
|
||||
|
||||
### I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do?
|
||||
|
||||
We've noticed that when the `/clr` compiler flag is used, Visual C++ uses 5~6
|
||||
times as much memory when compiling a mock class. We suggest to avoid `/clr`
|
||||
when compiling native C++ mocks.
|
||||
@ -0,0 +1,700 @@
|
||||
# gMock for Dummies
|
||||
|
||||
## What Is gMock?
|
||||
|
||||
When you write a prototype or test, often it's not feasible or wise to rely on
|
||||
real objects entirely. A **mock object** implements the same interface as a real
|
||||
object (so it can be used as one), but lets you specify at run time how it will
|
||||
be used and what it should do (which methods will be called? in which order? how
|
||||
many times? with what arguments? what will they return? etc).
|
||||
|
||||
It is easy to confuse the term *fake objects* with mock objects. Fakes and mocks
|
||||
actually mean very different things in the Test-Driven Development (TDD)
|
||||
community:
|
||||
|
||||
* **Fake** objects have working implementations, but usually take some
|
||||
shortcut (perhaps to make the operations less expensive), which makes them
|
||||
not suitable for production. An in-memory file system would be an example of
|
||||
a fake.
|
||||
* **Mocks** are objects pre-programmed with *expectations*, which form a
|
||||
specification of the calls they are expected to receive.
|
||||
|
||||
If all this seems too abstract for you, don't worry - the most important thing
|
||||
to remember is that a mock allows you to check the *interaction* between itself
|
||||
and code that uses it. The difference between fakes and mocks shall become much
|
||||
clearer once you start to use mocks.
|
||||
|
||||
**gMock** is a library (sometimes we also call it a "framework" to make it sound
|
||||
cool) for creating mock classes and using them. It does to C++ what
|
||||
jMock/EasyMock does to Java (well, more or less).
|
||||
|
||||
When using gMock,
|
||||
|
||||
1. first, you use some simple macros to describe the interface you want to
|
||||
mock, and they will expand to the implementation of your mock class;
|
||||
2. next, you create some mock objects and specify its expectations and behavior
|
||||
using an intuitive syntax;
|
||||
3. then you exercise code that uses the mock objects. gMock will catch any
|
||||
violation to the expectations as soon as it arises.
|
||||
|
||||
## Why gMock?
|
||||
|
||||
While mock objects help you remove unnecessary dependencies in tests and make
|
||||
them fast and reliable, using mocks manually in C++ is *hard*:
|
||||
|
||||
* Someone has to implement the mocks. The job is usually tedious and
|
||||
error-prone. No wonder people go great distance to avoid it.
|
||||
* The quality of those manually written mocks is a bit, uh, unpredictable. You
|
||||
may see some really polished ones, but you may also see some that were
|
||||
hacked up in a hurry and have all sorts of ad hoc restrictions.
|
||||
* The knowledge you gained from using one mock doesn't transfer to the next
|
||||
one.
|
||||
|
||||
In contrast, Java and Python programmers have some fine mock frameworks (jMock,
|
||||
EasyMock, etc), which automate the creation of mocks. As a result, mocking is a
|
||||
proven effective technique and widely adopted practice in those communities.
|
||||
Having the right tool absolutely makes the difference.
|
||||
|
||||
gMock was built to help C++ programmers. It was inspired by jMock and EasyMock,
|
||||
but designed with C++'s specifics in mind. It is your friend if any of the
|
||||
following problems is bothering you:
|
||||
|
||||
* You are stuck with a sub-optimal design and wish you had done more
|
||||
prototyping before it was too late, but prototyping in C++ is by no means
|
||||
"rapid".
|
||||
* Your tests are slow as they depend on too many libraries or use expensive
|
||||
resources (e.g. a database).
|
||||
* Your tests are brittle as some resources they use are unreliable (e.g. the
|
||||
network).
|
||||
* You want to test how your code handles a failure (e.g. a file checksum
|
||||
error), but it's not easy to cause one.
|
||||
* You need to make sure that your module interacts with other modules in the
|
||||
right way, but it's hard to observe the interaction; therefore you resort to
|
||||
observing the side effects at the end of the action, but it's awkward at
|
||||
best.
|
||||
* You want to "mock out" your dependencies, except that they don't have mock
|
||||
implementations yet; and, frankly, you aren't thrilled by some of those
|
||||
hand-written mocks.
|
||||
|
||||
We encourage you to use gMock as
|
||||
|
||||
* a *design* tool, for it lets you experiment with your interface design early
|
||||
and often. More iterations lead to better designs!
|
||||
* a *testing* tool to cut your tests' outbound dependencies and probe the
|
||||
interaction between your module and its collaborators.
|
||||
|
||||
## Getting Started
|
||||
|
||||
gMock is bundled with googletest.
|
||||
|
||||
## A Case for Mock Turtles
|
||||
|
||||
Let's look at an example. Suppose you are developing a graphics program that
|
||||
relies on a [LOGO](http://en.wikipedia.org/wiki/Logo_programming_language)-like
|
||||
API for drawing. How would you test that it does the right thing? Well, you can
|
||||
run it and compare the screen with a golden screen snapshot, but let's admit it:
|
||||
tests like this are expensive to run and fragile (What if you just upgraded to a
|
||||
shiny new graphics card that has better anti-aliasing? Suddenly you have to
|
||||
update all your golden images.). It would be too painful if all your tests are
|
||||
like this. Fortunately, you learned about
|
||||
[Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection) and know the right thing
|
||||
to do: instead of having your application talk to the system API directly, wrap
|
||||
the API in an interface (say, `Turtle`) and code to that interface:
|
||||
|
||||
```cpp
|
||||
class Turtle {
|
||||
...
|
||||
virtual ~Turtle() {}
|
||||
virtual void PenUp() = 0;
|
||||
virtual void PenDown() = 0;
|
||||
virtual void Forward(int distance) = 0;
|
||||
virtual void Turn(int degrees) = 0;
|
||||
virtual void GoTo(int x, int y) = 0;
|
||||
virtual int GetX() const = 0;
|
||||
virtual int GetY() const = 0;
|
||||
};
|
||||
```
|
||||
|
||||
(Note that the destructor of `Turtle` **must** be virtual, as is the case for
|
||||
**all** classes you intend to inherit from - otherwise the destructor of the
|
||||
derived class will not be called when you delete an object through a base
|
||||
pointer, and you'll get corrupted program states like memory leaks.)
|
||||
|
||||
You can control whether the turtle's movement will leave a trace using `PenUp()`
|
||||
and `PenDown()`, and control its movement using `Forward()`, `Turn()`, and
|
||||
`GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the
|
||||
turtle.
|
||||
|
||||
Your program will normally use a real implementation of this interface. In
|
||||
tests, you can use a mock implementation instead. This allows you to easily
|
||||
check what drawing primitives your program is calling, with what arguments, and
|
||||
in which order. Tests written this way are much more robust (they won't break
|
||||
because your new machine does anti-aliasing differently), easier to read and
|
||||
maintain (the intent of a test is expressed in the code, not in some binary
|
||||
images), and run *much, much faster*.
|
||||
|
||||
## Writing the Mock Class
|
||||
|
||||
If you are lucky, the mocks you need to use have already been implemented by
|
||||
some nice people. If, however, you find yourself in the position to write a mock
|
||||
class, relax - gMock turns this task into a fun game! (Well, almost.)
|
||||
|
||||
### How to Define It
|
||||
|
||||
Using the `Turtle` interface as example, here are the simple steps you need to
|
||||
follow:
|
||||
|
||||
* Derive a class `MockTurtle` from `Turtle`.
|
||||
* Take a *virtual* function of `Turtle` (while it's possible to
|
||||
[mock non-virtual methods using templates](gmock_cook_book.md#MockingNonVirtualMethods),
|
||||
it's much more involved).
|
||||
* In the `public:` section of the child class, write `MOCK_METHOD();`
|
||||
* Now comes the fun part: you take the function signature, cut-and-paste it
|
||||
into the macro, and add two commas - one between the return type and the
|
||||
name, another between the name and the argument list.
|
||||
* If you're mocking a const method, add a 4th parameter containing `(const)`
|
||||
(the parentheses are required).
|
||||
* Since you're overriding a virtual method, we suggest adding the `override`
|
||||
keyword. For const methods the 4th parameter becomes `(const, override)`,
|
||||
for non-const methods just `(override)`. This isn't mandatory.
|
||||
* Repeat until all virtual functions you want to mock are done. (It goes
|
||||
without saying that *all* pure virtual methods in your abstract class must
|
||||
be either mocked or overridden.)
|
||||
|
||||
After the process, you should have something like:
|
||||
|
||||
```cpp
|
||||
#include "gmock/gmock.h" // Brings in gMock.
|
||||
|
||||
class MockTurtle : public Turtle {
|
||||
public:
|
||||
...
|
||||
MOCK_METHOD(void, PenUp, (), (override));
|
||||
MOCK_METHOD(void, PenDown, (), (override));
|
||||
MOCK_METHOD(void, Forward, (int distance), (override));
|
||||
MOCK_METHOD(void, Turn, (int degrees), (override));
|
||||
MOCK_METHOD(void, GoTo, (int x, int y), (override));
|
||||
MOCK_METHOD(int, GetX, (), (const, override));
|
||||
MOCK_METHOD(int, GetY, (), (const, override));
|
||||
};
|
||||
```
|
||||
|
||||
You don't need to define these mock methods somewhere else - the `MOCK_METHOD`
|
||||
macro will generate the definitions for you. It's that simple!
|
||||
|
||||
### Where to Put It
|
||||
|
||||
When you define a mock class, you need to decide where to put its definition.
|
||||
Some people put it in a `_test.cc`. This is fine when the interface being mocked
|
||||
(say, `Foo`) is owned by the same person or team. Otherwise, when the owner of
|
||||
`Foo` changes it, your test could break. (You can't really expect `Foo`'s
|
||||
maintainer to fix every test that uses `Foo`, can you?)
|
||||
|
||||
So, the rule of thumb is: if you need to mock `Foo` and it's owned by others,
|
||||
define the mock class in `Foo`'s package (better, in a `testing` sub-package
|
||||
such that you can clearly separate production code and testing utilities), put
|
||||
it in a `.h` and a `cc_library`. Then everyone can reference them from their
|
||||
tests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and
|
||||
only tests that depend on the changed methods need to be fixed.
|
||||
|
||||
Another way to do it: you can introduce a thin layer `FooAdaptor` on top of
|
||||
`Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb
|
||||
changes in `Foo` much more easily. While this is more work initially, carefully
|
||||
choosing the adaptor interface can make your code easier to write and more
|
||||
readable (a net win in the long run), as you can choose `FooAdaptor` to fit your
|
||||
specific domain much better than `Foo` does.
|
||||
|
||||
## Using Mocks in Tests
|
||||
|
||||
Once you have a mock class, using it is easy. The typical work flow is:
|
||||
|
||||
1. Import the gMock names from the `testing` namespace such that you can use
|
||||
them unqualified (You only have to do it once per file). Remember that
|
||||
namespaces are a good idea.
|
||||
2. Create some mock objects.
|
||||
3. Specify your expectations on them (How many times will a method be called?
|
||||
With what arguments? What should it do? etc.).
|
||||
4. Exercise some code that uses the mocks; optionally, check the result using
|
||||
googletest assertions. If a mock method is called more than expected or with
|
||||
wrong arguments, you'll get an error immediately.
|
||||
5. When a mock is destructed, gMock will automatically check whether all
|
||||
expectations on it have been satisfied.
|
||||
|
||||
Here's an example:
|
||||
|
||||
```cpp
|
||||
#include "path/to/mock-turtle.h"
|
||||
#include "gmock/gmock.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
using ::testing::AtLeast; // #1
|
||||
|
||||
TEST(PainterTest, CanDrawSomething) {
|
||||
MockTurtle turtle; // #2
|
||||
EXPECT_CALL(turtle, PenDown()) // #3
|
||||
.Times(AtLeast(1));
|
||||
|
||||
Painter painter(&turtle); // #4
|
||||
|
||||
EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); // #5
|
||||
}
|
||||
```
|
||||
|
||||
As you might have guessed, this test checks that `PenDown()` is called at least
|
||||
once. If the `painter` object didn't call this method, your test will fail with
|
||||
a message like this:
|
||||
|
||||
```text
|
||||
path/to/my_test.cc:119: Failure
|
||||
Actual function call count doesn't match this expectation:
|
||||
Actually: never called;
|
||||
Expected: called at least once.
|
||||
Stack trace:
|
||||
...
|
||||
```
|
||||
|
||||
**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on
|
||||
the line number to jump right to the failed expectation.
|
||||
|
||||
**Tip 2:** If your mock objects are never deleted, the final verification won't
|
||||
happen. Therefore it's a good idea to turn on the heap checker in your tests
|
||||
when you allocate mocks on the heap. You get that automatically if you use the
|
||||
`gtest_main` library already.
|
||||
|
||||
**Important note:** gMock requires expectations to be set **before** the mock
|
||||
functions are called, otherwise the behavior is **undefined**. Do not alternate
|
||||
between calls to `EXPECT_CALL()` and calls to the mock functions, and do not set
|
||||
any expectations on a mock after passing the mock to an API.
|
||||
|
||||
This means `EXPECT_CALL()` should be read as expecting that a call will occur
|
||||
*in the future*, not that a call has occurred. Why does gMock work like that?
|
||||
Well, specifying the expectation beforehand allows gMock to report a violation
|
||||
as soon as it rises, when the context (stack trace, etc) is still available.
|
||||
This makes debugging much easier.
|
||||
|
||||
Admittedly, this test is contrived and doesn't do much. You can easily achieve
|
||||
the same effect without using gMock. However, as we shall reveal soon, gMock
|
||||
allows you to do *so much more* with the mocks.
|
||||
|
||||
## Setting Expectations
|
||||
|
||||
The key to using a mock object successfully is to set the *right expectations*
|
||||
on it. If you set the expectations too strict, your test will fail as the result
|
||||
of unrelated changes. If you set them too loose, bugs can slip through. You want
|
||||
to do it just right such that your test can catch exactly the kind of bugs you
|
||||
intend it to catch. gMock provides the necessary means for you to do it "just
|
||||
right."
|
||||
|
||||
### General Syntax
|
||||
|
||||
In gMock we use the `EXPECT_CALL()` macro to set an expectation on a mock
|
||||
method. The general syntax is:
|
||||
|
||||
```cpp
|
||||
EXPECT_CALL(mock_object, method(matchers))
|
||||
.Times(cardinality)
|
||||
.WillOnce(action)
|
||||
.WillRepeatedly(action);
|
||||
```
|
||||
|
||||
The macro has two arguments: first the mock object, and then the method and its
|
||||
arguments. Note that the two are separated by a comma (`,`), not a period (`.`).
|
||||
(Why using a comma? The answer is that it was necessary for technical reasons.)
|
||||
If the method is not overloaded, the macro can also be called without matchers:
|
||||
|
||||
```cpp
|
||||
EXPECT_CALL(mock_object, non-overloaded-method)
|
||||
.Times(cardinality)
|
||||
.WillOnce(action)
|
||||
.WillRepeatedly(action);
|
||||
```
|
||||
|
||||
This syntax allows the test writer to specify "called with any arguments"
|
||||
without explicitly specifying the number or types of arguments. To avoid
|
||||
unintended ambiguity, this syntax may only be used for methods that are not
|
||||
overloaded.
|
||||
|
||||
Either form of the macro can be followed by some optional *clauses* that provide
|
||||
more information about the expectation. We'll discuss how each clause works in
|
||||
the coming sections.
|
||||
|
||||
This syntax is designed to make an expectation read like English. For example,
|
||||
you can probably guess that
|
||||
|
||||
```cpp
|
||||
using ::testing::Return;
|
||||
...
|
||||
EXPECT_CALL(turtle, GetX())
|
||||
.Times(5)
|
||||
.WillOnce(Return(100))
|
||||
.WillOnce(Return(150))
|
||||
.WillRepeatedly(Return(200));
|
||||
```
|
||||
|
||||
says that the `turtle` object's `GetX()` method will be called five times, it
|
||||
will return 100 the first time, 150 the second time, and then 200 every time.
|
||||
Some people like to call this style of syntax a Domain-Specific Language (DSL).
|
||||
|
||||
{: .callout .note}
|
||||
**Note:** Why do we use a macro to do this? Well it serves two purposes: first
|
||||
it makes expectations easily identifiable (either by `grep` or by a human
|
||||
reader), and second it allows gMock to include the source file location of a
|
||||
failed expectation in messages, making debugging easier.
|
||||
|
||||
### Matchers: What Arguments Do We Expect?
|
||||
|
||||
When a mock function takes arguments, we may specify what arguments we are
|
||||
expecting, for example:
|
||||
|
||||
```cpp
|
||||
// Expects the turtle to move forward by 100 units.
|
||||
EXPECT_CALL(turtle, Forward(100));
|
||||
```
|
||||
|
||||
Oftentimes you do not want to be too specific. Remember that talk about tests
|
||||
being too rigid? Over specification leads to brittle tests and obscures the
|
||||
intent of tests. Therefore we encourage you to specify only what's necessary—no
|
||||
more, no less. If you aren't interested in the value of an argument, write `_`
|
||||
as the argument, which means "anything goes":
|
||||
|
||||
```cpp
|
||||
using ::testing::_;
|
||||
...
|
||||
// Expects that the turtle jumps to somewhere on the x=50 line.
|
||||
EXPECT_CALL(turtle, GoTo(50, _));
|
||||
```
|
||||
|
||||
`_` is an instance of what we call **matchers**. A matcher is like a predicate
|
||||
and can test whether an argument is what we'd expect. You can use a matcher
|
||||
inside `EXPECT_CALL()` wherever a function argument is expected. `_` is a
|
||||
convenient way of saying "any value".
|
||||
|
||||
In the above examples, `100` and `50` are also matchers; implicitly, they are
|
||||
the same as `Eq(100)` and `Eq(50)`, which specify that the argument must be
|
||||
equal (using `operator==`) to the matcher argument. There are many
|
||||
[built-in matchers](reference/matchers.md) for common types (as well as
|
||||
[custom matchers](gmock_cook_book.md#NewMatchers)); for example:
|
||||
|
||||
```cpp
|
||||
using ::testing::Ge;
|
||||
...
|
||||
// Expects the turtle moves forward by at least 100.
|
||||
EXPECT_CALL(turtle, Forward(Ge(100)));
|
||||
```
|
||||
|
||||
If you don't care about *any* arguments, rather than specify `_` for each of
|
||||
them you may instead omit the parameter list:
|
||||
|
||||
```cpp
|
||||
// Expects the turtle to move forward.
|
||||
EXPECT_CALL(turtle, Forward);
|
||||
// Expects the turtle to jump somewhere.
|
||||
EXPECT_CALL(turtle, GoTo);
|
||||
```
|
||||
|
||||
This works for all non-overloaded methods; if a method is overloaded, you need
|
||||
to help gMock resolve which overload is expected by specifying the number of
|
||||
arguments and possibly also the
|
||||
[types of the arguments](gmock_cook_book.md#SelectOverload).
|
||||
|
||||
### Cardinalities: How Many Times Will It Be Called?
|
||||
|
||||
The first clause we can specify following an `EXPECT_CALL()` is `Times()`. We
|
||||
call its argument a **cardinality** as it tells *how many times* the call should
|
||||
occur. It allows us to repeat an expectation many times without actually writing
|
||||
it as many times. More importantly, a cardinality can be "fuzzy", just like a
|
||||
matcher can be. This allows a user to express the intent of a test exactly.
|
||||
|
||||
An interesting special case is when we say `Times(0)`. You may have guessed - it
|
||||
means that the function shouldn't be called with the given arguments at all, and
|
||||
gMock will report a googletest failure whenever the function is (wrongfully)
|
||||
called.
|
||||
|
||||
We've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the
|
||||
list of built-in cardinalities you can use, see
|
||||
[here](gmock_cheat_sheet.md#CardinalityList).
|
||||
|
||||
The `Times()` clause can be omitted. **If you omit `Times()`, gMock will infer
|
||||
the cardinality for you.** The rules are easy to remember:
|
||||
|
||||
* If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the
|
||||
`EXPECT_CALL()`, the inferred cardinality is `Times(1)`.
|
||||
* If there are *n* `WillOnce()`'s but **no** `WillRepeatedly()`, where *n* >=
|
||||
1, the cardinality is `Times(n)`.
|
||||
* If there are *n* `WillOnce()`'s and **one** `WillRepeatedly()`, where *n* >=
|
||||
0, the cardinality is `Times(AtLeast(n))`.
|
||||
|
||||
**Quick quiz:** what do you think will happen if a function is expected to be
|
||||
called twice but actually called four times?
|
||||
|
||||
### Actions: What Should It Do?
|
||||
|
||||
Remember that a mock object doesn't really have a working implementation? We as
|
||||
users have to tell it what to do when a method is invoked. This is easy in
|
||||
gMock.
|
||||
|
||||
First, if the return type of a mock function is a built-in type or a pointer,
|
||||
the function has a **default action** (a `void` function will just return, a
|
||||
`bool` function will return `false`, and other functions will return 0). In
|
||||
addition, in C++ 11 and above, a mock function whose return type is
|
||||
default-constructible (i.e. has a default constructor) has a default action of
|
||||
returning a default-constructed value. If you don't say anything, this behavior
|
||||
will be used.
|
||||
|
||||
Second, if a mock function doesn't have a default action, or the default action
|
||||
doesn't suit you, you can specify the action to be taken each time the
|
||||
expectation matches using a series of `WillOnce()` clauses followed by an
|
||||
optional `WillRepeatedly()`. For example,
|
||||
|
||||
```cpp
|
||||
using ::testing::Return;
|
||||
...
|
||||
EXPECT_CALL(turtle, GetX())
|
||||
.WillOnce(Return(100))
|
||||
.WillOnce(Return(200))
|
||||
.WillOnce(Return(300));
|
||||
```
|
||||
|
||||
says that `turtle.GetX()` will be called *exactly three times* (gMock inferred
|
||||
this from how many `WillOnce()` clauses we've written, since we didn't
|
||||
explicitly write `Times()`), and will return 100, 200, and 300 respectively.
|
||||
|
||||
```cpp
|
||||
using ::testing::Return;
|
||||
...
|
||||
EXPECT_CALL(turtle, GetY())
|
||||
.WillOnce(Return(100))
|
||||
.WillOnce(Return(200))
|
||||
.WillRepeatedly(Return(300));
|
||||
```
|
||||
|
||||
says that `turtle.GetY()` will be called *at least twice* (gMock knows this as
|
||||
we've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no
|
||||
explicit `Times()`), will return 100 and 200 respectively the first two times,
|
||||
and 300 from the third time on.
|
||||
|
||||
Of course, if you explicitly write a `Times()`, gMock will not try to infer the
|
||||
cardinality itself. What if the number you specified is larger than there are
|
||||
`WillOnce()` clauses? Well, after all `WillOnce()`s are used up, gMock will do
|
||||
the *default* action for the function every time (unless, of course, you have a
|
||||
`WillRepeatedly()`.).
|
||||
|
||||
What can we do inside `WillOnce()` besides `Return()`? You can return a
|
||||
reference using `ReturnRef(*variable*)`, or invoke a pre-defined function, among
|
||||
[others](gmock_cook_book.md#using-actions).
|
||||
|
||||
**Important note:** The `EXPECT_CALL()` statement evaluates the action clause
|
||||
only once, even though the action may be performed many times. Therefore you
|
||||
must be careful about side effects. The following may not do what you want:
|
||||
|
||||
```cpp
|
||||
using ::testing::Return;
|
||||
...
|
||||
int n = 100;
|
||||
EXPECT_CALL(turtle, GetX())
|
||||
.Times(4)
|
||||
.WillRepeatedly(Return(n++));
|
||||
```
|
||||
|
||||
Instead of returning 100, 101, 102, ..., consecutively, this mock function will
|
||||
always return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)`
|
||||
will create a new `Foo` object when the `EXPECT_CALL()` is executed, and will
|
||||
return the same pointer every time. If you want the side effect to happen every
|
||||
time, you need to define a custom action, which we'll teach in the
|
||||
[cook book](gmock_cook_book.md).
|
||||
|
||||
Time for another quiz! What do you think the following means?
|
||||
|
||||
```cpp
|
||||
using ::testing::Return;
|
||||
...
|
||||
EXPECT_CALL(turtle, GetY())
|
||||
.Times(4)
|
||||
.WillOnce(Return(100));
|
||||
```
|
||||
|
||||
Obviously `turtle.GetY()` is expected to be called four times. But if you think
|
||||
it will return 100 every time, think twice! Remember that one `WillOnce()`
|
||||
clause will be consumed each time the function is invoked and the default action
|
||||
will be taken afterwards. So the right answer is that `turtle.GetY()` will
|
||||
return 100 the first time, but **return 0 from the second time on**, as
|
||||
returning 0 is the default action for `int` functions.
|
||||
|
||||
### Using Multiple Expectations {#MultiExpectations}
|
||||
|
||||
So far we've only shown examples where you have a single expectation. More
|
||||
realistically, you'll specify expectations on multiple mock methods which may be
|
||||
from multiple mock objects.
|
||||
|
||||
By default, when a mock method is invoked, gMock will search the expectations in
|
||||
the **reverse order** they are defined, and stop when an active expectation that
|
||||
matches the arguments is found (you can think of it as "newer rules override
|
||||
older ones."). If the matching expectation cannot take any more calls, you will
|
||||
get an upper-bound-violated failure. Here's an example:
|
||||
|
||||
```cpp
|
||||
using ::testing::_;
|
||||
...
|
||||
EXPECT_CALL(turtle, Forward(_)); // #1
|
||||
EXPECT_CALL(turtle, Forward(10)) // #2
|
||||
.Times(2);
|
||||
```
|
||||
|
||||
If `Forward(10)` is called three times in a row, the third time it will be an
|
||||
error, as the last matching expectation (#2) has been saturated. If, however,
|
||||
the third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK,
|
||||
as now #1 will be the matching expectation.
|
||||
|
||||
{: .callout .note}
|
||||
**Note:** Why does gMock search for a match in the *reverse* order of the
|
||||
expectations? The reason is that this allows a user to set up the default
|
||||
expectations in a mock object's constructor or the test fixture's set-up phase
|
||||
and then customize the mock by writing more specific expectations in the test
|
||||
body. So, if you have two expectations on the same method, you want to put the
|
||||
one with more specific matchers **after** the other, or the more specific rule
|
||||
would be shadowed by the more general one that comes after it.
|
||||
|
||||
{: .callout .tip}
|
||||
**Tip:** It is very common to start with a catch-all expectation for a method
|
||||
and `Times(AnyNumber())` (omitting arguments, or with `_` for all arguments, if
|
||||
overloaded). This makes any calls to the method expected. This is not necessary
|
||||
for methods that are not mentioned at all (these are "uninteresting"), but is
|
||||
useful for methods that have some expectations, but for which other calls are
|
||||
ok. See
|
||||
[Understanding Uninteresting vs Unexpected Calls](gmock_cook_book.md#uninteresting-vs-unexpected).
|
||||
|
||||
### Ordered vs Unordered Calls {#OrderedCalls}
|
||||
|
||||
By default, an expectation can match a call even though an earlier expectation
|
||||
hasn't been satisfied. In other words, the calls don't have to occur in the
|
||||
order the expectations are specified.
|
||||
|
||||
Sometimes, you may want all the expected calls to occur in a strict order. To
|
||||
say this in gMock is easy:
|
||||
|
||||
```cpp
|
||||
using ::testing::InSequence;
|
||||
...
|
||||
TEST(FooTest, DrawsLineSegment) {
|
||||
...
|
||||
{
|
||||
InSequence seq;
|
||||
|
||||
EXPECT_CALL(turtle, PenDown());
|
||||
EXPECT_CALL(turtle, Forward(100));
|
||||
EXPECT_CALL(turtle, PenUp());
|
||||
}
|
||||
Foo();
|
||||
}
|
||||
```
|
||||
|
||||
By creating an object of type `InSequence`, all expectations in its scope are
|
||||
put into a *sequence* and have to occur *sequentially*. Since we are just
|
||||
relying on the constructor and destructor of this object to do the actual work,
|
||||
its name is really irrelevant.
|
||||
|
||||
In this example, we test that `Foo()` calls the three expected functions in the
|
||||
order as written. If a call is made out-of-order, it will be an error.
|
||||
|
||||
(What if you care about the relative order of some of the calls, but not all of
|
||||
them? Can you specify an arbitrary partial order? The answer is ... yes! The
|
||||
details can be found [here](gmock_cook_book.md#OrderedCalls).)
|
||||
|
||||
### All Expectations Are Sticky (Unless Said Otherwise) {#StickyExpectations}
|
||||
|
||||
Now let's do a quick quiz to see how well you can use this mock stuff already.
|
||||
How would you test that the turtle is asked to go to the origin *exactly twice*
|
||||
(you want to ignore any other instructions it receives)?
|
||||
|
||||
After you've come up with your answer, take a look at ours and compare notes
|
||||
(solve it yourself first - don't cheat!):
|
||||
|
||||
```cpp
|
||||
using ::testing::_;
|
||||
using ::testing::AnyNumber;
|
||||
...
|
||||
EXPECT_CALL(turtle, GoTo(_, _)) // #1
|
||||
.Times(AnyNumber());
|
||||
EXPECT_CALL(turtle, GoTo(0, 0)) // #2
|
||||
.Times(2);
|
||||
```
|
||||
|
||||
Suppose `turtle.GoTo(0, 0)` is called three times. In the third time, gMock will
|
||||
see that the arguments match expectation #2 (remember that we always pick the
|
||||
last matching expectation). Now, since we said that there should be only two
|
||||
such calls, gMock will report an error immediately. This is basically what we've
|
||||
told you in the [Using Multiple Expectations](#MultiExpectations) section above.
|
||||
|
||||
This example shows that **expectations in gMock are "sticky" by default**, in
|
||||
the sense that they remain active even after we have reached their invocation
|
||||
upper bounds. This is an important rule to remember, as it affects the meaning
|
||||
of the spec, and is **different** to how it's done in many other mocking
|
||||
frameworks (Why'd we do that? Because we think our rule makes the common cases
|
||||
easier to express and understand.).
|
||||
|
||||
Simple? Let's see if you've really understood it: what does the following code
|
||||
say?
|
||||
|
||||
```cpp
|
||||
using ::testing::Return;
|
||||
...
|
||||
for (int i = n; i > 0; i--) {
|
||||
EXPECT_CALL(turtle, GetX())
|
||||
.WillOnce(Return(10*i));
|
||||
}
|
||||
```
|
||||
|
||||
If you think it says that `turtle.GetX()` will be called `n` times and will
|
||||
return 10, 20, 30, ..., consecutively, think twice! The problem is that, as we
|
||||
said, expectations are sticky. So, the second time `turtle.GetX()` is called,
|
||||
the last (latest) `EXPECT_CALL()` statement will match, and will immediately
|
||||
lead to an "upper bound violated" error - this piece of code is not very useful!
|
||||
|
||||
One correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is
|
||||
to explicitly say that the expectations are *not* sticky. In other words, they
|
||||
should *retire* as soon as they are saturated:
|
||||
|
||||
```cpp
|
||||
using ::testing::Return;
|
||||
...
|
||||
for (int i = n; i > 0; i--) {
|
||||
EXPECT_CALL(turtle, GetX())
|
||||
.WillOnce(Return(10*i))
|
||||
.RetiresOnSaturation();
|
||||
}
|
||||
```
|
||||
|
||||
And, there's a better way to do it: in this case, we expect the calls to occur
|
||||
in a specific order, and we line up the actions to match the order. Since the
|
||||
order is important here, we should make it explicit using a sequence:
|
||||
|
||||
```cpp
|
||||
using ::testing::InSequence;
|
||||
using ::testing::Return;
|
||||
...
|
||||
{
|
||||
InSequence s;
|
||||
|
||||
for (int i = 1; i <= n; i++) {
|
||||
EXPECT_CALL(turtle, GetX())
|
||||
.WillOnce(Return(10*i))
|
||||
.RetiresOnSaturation();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
By the way, the other situation where an expectation may *not* be sticky is when
|
||||
it's in a sequence - as soon as another expectation that comes after it in the
|
||||
sequence has been used, it automatically retires (and will never be used to
|
||||
match any call).
|
||||
|
||||
### Uninteresting Calls
|
||||
|
||||
A mock object may have many methods, and not all of them are that interesting.
|
||||
For example, in some tests we may not care about how many times `GetX()` and
|
||||
`GetY()` get called.
|
||||
|
||||
In gMock, if you are not interested in a method, just don't say anything about
|
||||
it. If a call to this method occurs, you'll see a warning in the test output,
|
||||
but it won't be a failure. This is called "naggy" behavior; to change, see
|
||||
[The Nice, the Strict, and the Naggy](gmock_cook_book.md#NiceStrictNaggy).
|
||||
@ -0,0 +1,22 @@
|
||||
# GoogleTest User's Guide
|
||||
|
||||
## Welcome to GoogleTest!
|
||||
|
||||
GoogleTest is Google's C++ testing and mocking framework. This user's guide has
|
||||
the following contents:
|
||||
|
||||
* [GoogleTest Primer](primer.md) - Teaches you how to write simple tests using
|
||||
GoogleTest. Read this first if you are new to GoogleTest.
|
||||
* [GoogleTest Advanced](advanced.md) - Read this when you've finished the
|
||||
Primer and want to utilize GoogleTest to its full potential.
|
||||
* [GoogleTest Samples](samples.md) - Describes some GoogleTest samples.
|
||||
* [GoogleTest FAQ](faq.md) - Have a question? Want some tips? Check here
|
||||
first.
|
||||
* [Mocking for Dummies](gmock_for_dummies.md) - Teaches you how to create mock
|
||||
objects and use them in tests.
|
||||
* [Mocking Cookbook](gmock_cook_book.md) - Includes tips and approaches to
|
||||
common mocking use cases.
|
||||
* [Mocking Cheat Sheet](gmock_cheat_sheet.md) - A handy reference for
|
||||
matchers, actions, invariants, and more.
|
||||
* [Mocking FAQ](gmock_faq.md) - Contains answers to some mocking-specific
|
||||
questions.
|
||||
@ -0,0 +1,148 @@
|
||||
## Using GoogleTest from various build systems
|
||||
|
||||
GoogleTest comes with pkg-config files that can be used to determine all
|
||||
necessary flags for compiling and linking to GoogleTest (and GoogleMock).
|
||||
Pkg-config is a standardised plain-text format containing
|
||||
|
||||
* the includedir (-I) path
|
||||
* necessary macro (-D) definitions
|
||||
* further required flags (-pthread)
|
||||
* the library (-L) path
|
||||
* the library (-l) to link to
|
||||
|
||||
All current build systems support pkg-config in one way or another. For all
|
||||
examples here we assume you want to compile the sample
|
||||
`samples/sample3_unittest.cc`.
|
||||
|
||||
### CMake
|
||||
|
||||
Using `pkg-config` in CMake is fairly easy:
|
||||
|
||||
```cmake
|
||||
cmake_minimum_required(VERSION 3.0)
|
||||
|
||||
cmake_policy(SET CMP0048 NEW)
|
||||
project(my_gtest_pkgconfig VERSION 0.0.1 LANGUAGES CXX)
|
||||
|
||||
find_package(PkgConfig)
|
||||
pkg_search_module(GTEST REQUIRED gtest_main)
|
||||
|
||||
add_executable(testapp samples/sample3_unittest.cc)
|
||||
target_link_libraries(testapp ${GTEST_LDFLAGS})
|
||||
target_compile_options(testapp PUBLIC ${GTEST_CFLAGS})
|
||||
|
||||
include(CTest)
|
||||
add_test(first_and_only_test testapp)
|
||||
```
|
||||
|
||||
It is generally recommended that you use `target_compile_options` + `_CFLAGS`
|
||||
over `target_include_directories` + `_INCLUDE_DIRS` as the former includes not
|
||||
just -I flags (GoogleTest might require a macro indicating to internal headers
|
||||
that all libraries have been compiled with threading enabled. In addition,
|
||||
GoogleTest might also require `-pthread` in the compiling step, and as such
|
||||
splitting the pkg-config `Cflags` variable into include dirs and macros for
|
||||
`target_compile_definitions()` might still miss this). The same recommendation
|
||||
goes for using `_LDFLAGS` over the more commonplace `_LIBRARIES`, which happens
|
||||
to discard `-L` flags and `-pthread`.
|
||||
|
||||
### Help! pkg-config can't find GoogleTest!
|
||||
|
||||
Let's say you have a `CMakeLists.txt` along the lines of the one in this
|
||||
tutorial and you try to run `cmake`. It is very possible that you get a failure
|
||||
along the lines of:
|
||||
|
||||
```
|
||||
-- Checking for one of the modules 'gtest_main'
|
||||
CMake Error at /usr/share/cmake/Modules/FindPkgConfig.cmake:640 (message):
|
||||
None of the required 'gtest_main' found
|
||||
```
|
||||
|
||||
These failures are common if you installed GoogleTest yourself and have not
|
||||
sourced it from a distro or other package manager. If so, you need to tell
|
||||
pkg-config where it can find the `.pc` files containing the information. Say you
|
||||
installed GoogleTest to `/usr/local`, then it might be that the `.pc` files are
|
||||
installed under `/usr/local/lib64/pkgconfig`. If you set
|
||||
|
||||
```
|
||||
export PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig
|
||||
```
|
||||
|
||||
pkg-config will also try to look in `PKG_CONFIG_PATH` to find `gtest_main.pc`.
|
||||
|
||||
### Using pkg-config in a cross-compilation setting
|
||||
|
||||
Pkg-config can be used in a cross-compilation setting too. To do this, let's
|
||||
assume the final prefix of the cross-compiled installation will be `/usr`, and
|
||||
your sysroot is `/home/MYUSER/sysroot`. Configure and install GTest using
|
||||
|
||||
```
|
||||
mkdir build && cmake -DCMAKE_INSTALL_PREFIX=/usr ..
|
||||
```
|
||||
|
||||
Install into the sysroot using `DESTDIR`:
|
||||
|
||||
```
|
||||
make -j install DESTDIR=/home/MYUSER/sysroot
|
||||
```
|
||||
|
||||
Before we continue, it is recommended to **always** define the following two
|
||||
variables for pkg-config in a cross-compilation setting:
|
||||
|
||||
```
|
||||
export PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=yes
|
||||
export PKG_CONFIG_ALLOW_SYSTEM_LIBS=yes
|
||||
```
|
||||
|
||||
otherwise `pkg-config` will filter `-I` and `-L` flags against standard prefixes
|
||||
such as `/usr` (see https://bugs.freedesktop.org/show_bug.cgi?id=28264#c3 for
|
||||
reasons why this stripping needs to occur usually).
|
||||
|
||||
If you look at the generated pkg-config file, it will look something like
|
||||
|
||||
```
|
||||
libdir=/usr/lib64
|
||||
includedir=/usr/include
|
||||
|
||||
Name: gtest
|
||||
Description: GoogleTest (without main() function)
|
||||
Version: 1.10.0
|
||||
URL: https://github.com/google/googletest
|
||||
Libs: -L${libdir} -lgtest -lpthread
|
||||
Cflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 -lpthread
|
||||
```
|
||||
|
||||
Notice that the sysroot is not included in `libdir` and `includedir`! If you try
|
||||
to run `pkg-config` with the correct
|
||||
`PKG_CONFIG_LIBDIR=/home/MYUSER/sysroot/usr/lib64/pkgconfig` against this `.pc`
|
||||
file, you will get
|
||||
|
||||
```
|
||||
$ pkg-config --cflags gtest
|
||||
-DGTEST_HAS_PTHREAD=1 -lpthread -I/usr/include
|
||||
$ pkg-config --libs gtest
|
||||
-L/usr/lib64 -lgtest -lpthread
|
||||
```
|
||||
|
||||
which is obviously wrong and points to the `CBUILD` and not `CHOST` root. In
|
||||
order to use this in a cross-compilation setting, we need to tell pkg-config to
|
||||
inject the actual sysroot into `-I` and `-L` variables. Let us now tell
|
||||
pkg-config about the actual sysroot
|
||||
|
||||
```
|
||||
export PKG_CONFIG_DIR=
|
||||
export PKG_CONFIG_SYSROOT_DIR=/home/MYUSER/sysroot
|
||||
export PKG_CONFIG_LIBDIR=${PKG_CONFIG_SYSROOT_DIR}/usr/lib64/pkgconfig
|
||||
```
|
||||
|
||||
and running `pkg-config` again we get
|
||||
|
||||
```
|
||||
$ pkg-config --cflags gtest
|
||||
-DGTEST_HAS_PTHREAD=1 -lpthread -I/home/MYUSER/sysroot/usr/include
|
||||
$ pkg-config --libs gtest
|
||||
-L/home/MYUSER/sysroot/usr/lib64 -lgtest -lpthread
|
||||
```
|
||||
|
||||
which contains the correct sysroot now. For a more comprehensive guide to also
|
||||
including `${CHOST}` in build system calls, see the excellent tutorial by Diego
|
||||
Elio Pettenò: <https://autotools.io/pkgconfig/cross-compiling.html>
|
||||
@ -0,0 +1,35 @@
|
||||
# Supported Platforms
|
||||
|
||||
GoogleTest requires a codebase and compiler compliant with the C++11 standard or
|
||||
newer.
|
||||
|
||||
The GoogleTest code is officially supported on the following platforms.
|
||||
Operating systems or tools not listed below are community-supported. For
|
||||
community-supported platforms, patches that do not complicate the code may be
|
||||
considered.
|
||||
|
||||
If you notice any problems on your platform, please file an issue on the
|
||||
[GoogleTest GitHub Issue Tracker](https://github.com/google/googletest/issues).
|
||||
Pull requests containing fixes are welcome!
|
||||
|
||||
### Operating systems
|
||||
|
||||
* Linux
|
||||
* macOS
|
||||
* Windows
|
||||
|
||||
### Compilers
|
||||
|
||||
* gcc 5.0+
|
||||
* clang 5.0+
|
||||
* MSVC 2015+
|
||||
|
||||
**macOS users:** Xcode 9.3+ provides clang 5.0+.
|
||||
|
||||
### Build systems
|
||||
|
||||
* [Bazel](https://bazel.build/)
|
||||
* [CMake](https://cmake.org/)
|
||||
|
||||
Bazel is the build system used by the team internally and in tests. CMake is
|
||||
supported on a best-effort basis and by the community.
|
||||
@ -0,0 +1,482 @@
|
||||
# Googletest Primer
|
||||
|
||||
## Introduction: Why googletest?
|
||||
|
||||
*googletest* helps you write better C++ tests.
|
||||
|
||||
googletest is a testing framework developed by the Testing Technology team with
|
||||
Google's specific requirements and constraints in mind. Whether you work on
|
||||
Linux, Windows, or a Mac, if you write C++ code, googletest can help you. And it
|
||||
supports *any* kind of tests, not just unit tests.
|
||||
|
||||
So what makes a good test, and how does googletest fit in? We believe:
|
||||
|
||||
1. Tests should be *independent* and *repeatable*. It's a pain to debug a test
|
||||
that succeeds or fails as a result of other tests. googletest isolates the
|
||||
tests by running each of them on a different object. When a test fails,
|
||||
googletest allows you to run it in isolation for quick debugging.
|
||||
2. Tests should be well *organized* and reflect the structure of the tested
|
||||
code. googletest groups related tests into test suites that can share data
|
||||
and subroutines. This common pattern is easy to recognize and makes tests
|
||||
easy to maintain. Such consistency is especially helpful when people switch
|
||||
projects and start to work on a new code base.
|
||||
3. Tests should be *portable* and *reusable*. Google has a lot of code that is
|
||||
platform-neutral; its tests should also be platform-neutral. googletest
|
||||
works on different OSes, with different compilers, with or without
|
||||
exceptions, so googletest tests can work with a variety of configurations.
|
||||
4. When tests fail, they should provide as much *information* about the problem
|
||||
as possible. googletest doesn't stop at the first test failure. Instead, it
|
||||
only stops the current test and continues with the next. You can also set up
|
||||
tests that report non-fatal failures after which the current test continues.
|
||||
Thus, you can detect and fix multiple bugs in a single run-edit-compile
|
||||
cycle.
|
||||
5. The testing framework should liberate test writers from housekeeping chores
|
||||
and let them focus on the test *content*. googletest automatically keeps
|
||||
track of all tests defined, and doesn't require the user to enumerate them
|
||||
in order to run them.
|
||||
6. Tests should be *fast*. With googletest, you can reuse shared resources
|
||||
across tests and pay for the set-up/tear-down only once, without making
|
||||
tests depend on each other.
|
||||
|
||||
Since googletest is based on the popular xUnit architecture, you'll feel right
|
||||
at home if you've used JUnit or PyUnit before. If not, it will take you about 10
|
||||
minutes to learn the basics and get started. So let's go!
|
||||
|
||||
## Beware of the nomenclature
|
||||
|
||||
{: .callout .note}
|
||||
_Note:_ There might be some confusion arising from different definitions of the
|
||||
terms _Test_, _Test Case_ and _Test Suite_, so beware of misunderstanding these.
|
||||
|
||||
Historically, googletest started to use the term _Test Case_ for grouping
|
||||
related tests, whereas current publications, including International Software
|
||||
Testing Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and
|
||||
various textbooks on software quality, use the term
|
||||
_[Test Suite][istqb test suite]_ for this.
|
||||
|
||||
The related term _Test_, as it is used in googletest, corresponds to the term
|
||||
_[Test Case][istqb test case]_ of ISTQB and others.
|
||||
|
||||
The term _Test_ is commonly of broad enough sense, including ISTQB's definition
|
||||
of _Test Case_, so it's not much of a problem here. But the term _Test Case_ as
|
||||
was used in Google Test is of contradictory sense and thus confusing.
|
||||
|
||||
googletest recently started replacing the term _Test Case_ with _Test Suite_.
|
||||
The preferred API is *TestSuite*. The older TestCase API is being slowly
|
||||
deprecated and refactored away.
|
||||
|
||||
So please be aware of the different definitions of the terms:
|
||||
|
||||
|
||||
Meaning | googletest Term | [ISTQB](http://www.istqb.org/) Term
|
||||
:----------------------------------------------------------------------------------- | :---------------------- | :----------------------------------
|
||||
Exercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case]
|
||||
|
||||
|
||||
[istqb test case]: http://glossary.istqb.org/en/search/test%20case
|
||||
[istqb test suite]: http://glossary.istqb.org/en/search/test%20suite
|
||||
|
||||
## Basic Concepts
|
||||
|
||||
When using googletest, you start by writing *assertions*, which are statements
|
||||
that check whether a condition is true. An assertion's result can be *success*,
|
||||
*nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the
|
||||
current function; otherwise the program continues normally.
|
||||
|
||||
*Tests* use assertions to verify the tested code's behavior. If a test crashes
|
||||
or has a failed assertion, then it *fails*; otherwise it *succeeds*.
|
||||
|
||||
A *test suite* contains one or many tests. You should group your tests into test
|
||||
suites that reflect the structure of the tested code. When multiple tests in a
|
||||
test suite need to share common objects and subroutines, you can put them into a
|
||||
*test fixture* class.
|
||||
|
||||
A *test program* can contain multiple test suites.
|
||||
|
||||
We'll now explain how to write a test program, starting at the individual
|
||||
assertion level and building up to tests and test suites.
|
||||
|
||||
## Assertions
|
||||
|
||||
googletest assertions are macros that resemble function calls. You test a class
|
||||
or function by making assertions about its behavior. When an assertion fails,
|
||||
googletest prints the assertion's source file and line number location, along
|
||||
with a failure message. You may also supply a custom failure message which will
|
||||
be appended to googletest's message.
|
||||
|
||||
The assertions come in pairs that test the same thing but have different effects
|
||||
on the current function. `ASSERT_*` versions generate fatal failures when they
|
||||
fail, and **abort the current function**. `EXPECT_*` versions generate nonfatal
|
||||
failures, which don't abort the current function. Usually `EXPECT_*` are
|
||||
preferred, as they allow more than one failure to be reported in a test.
|
||||
However, you should use `ASSERT_*` if it doesn't make sense to continue when the
|
||||
assertion in question fails.
|
||||
|
||||
Since a failed `ASSERT_*` returns from the current function immediately,
|
||||
possibly skipping clean-up code that comes after it, it may cause a space leak.
|
||||
Depending on the nature of the leak, it may or may not be worth fixing - so keep
|
||||
this in mind if you get a heap checker error in addition to assertion errors.
|
||||
|
||||
To provide a custom failure message, simply stream it into the macro using the
|
||||
`<<` operator or a sequence of such operators. See the following example, using
|
||||
the [`ASSERT_EQ` and `EXPECT_EQ`](reference/assertions.md#EXPECT_EQ) macros to
|
||||
verify value equality:
|
||||
|
||||
```c++
|
||||
ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";
|
||||
|
||||
for (int i = 0; i < x.size(); ++i) {
|
||||
EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
|
||||
}
|
||||
```
|
||||
|
||||
Anything that can be streamed to an `ostream` can be streamed to an assertion
|
||||
macro--in particular, C strings and `string` objects. If a wide string
|
||||
(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is
|
||||
streamed to an assertion, it will be translated to UTF-8 when printed.
|
||||
|
||||
GoogleTest provides a collection of assertions for verifying the behavior of
|
||||
your code in various ways. You can check Boolean conditions, compare values
|
||||
based on relational operators, verify string values, floating-point values, and
|
||||
much more. There are even assertions that enable you to verify more complex
|
||||
states by providing custom predicates. For the complete list of assertions
|
||||
provided by GoogleTest, see the [Assertions Reference](reference/assertions.md).
|
||||
|
||||
## Simple Tests
|
||||
|
||||
To create a test:
|
||||
|
||||
1. Use the `TEST()` macro to define and name a test function. These are
|
||||
ordinary C++ functions that don't return a value.
|
||||
2. In this function, along with any valid C++ statements you want to include,
|
||||
use the various googletest assertions to check values.
|
||||
3. The test's result is determined by the assertions; if any assertion in the
|
||||
test fails (either fatally or non-fatally), or if the test crashes, the
|
||||
entire test fails. Otherwise, it succeeds.
|
||||
|
||||
```c++
|
||||
TEST(TestSuiteName, TestName) {
|
||||
... test body ...
|
||||
}
|
||||
```
|
||||
|
||||
`TEST()` arguments go from general to specific. The *first* argument is the name
|
||||
of the test suite, and the *second* argument is the test's name within the test
|
||||
suite. Both names must be valid C++ identifiers, and they should not contain
|
||||
any underscores (`_`). A test's *full name* consists of its containing test suite and
|
||||
its individual name. Tests from different test suites can have the same
|
||||
individual name.
|
||||
|
||||
For example, let's take a simple integer function:
|
||||
|
||||
```c++
|
||||
int Factorial(int n); // Returns the factorial of n
|
||||
```
|
||||
|
||||
A test suite for this function might look like:
|
||||
|
||||
```c++
|
||||
// Tests factorial of 0.
|
||||
TEST(FactorialTest, HandlesZeroInput) {
|
||||
EXPECT_EQ(Factorial(0), 1);
|
||||
}
|
||||
|
||||
// Tests factorial of positive numbers.
|
||||
TEST(FactorialTest, HandlesPositiveInput) {
|
||||
EXPECT_EQ(Factorial(1), 1);
|
||||
EXPECT_EQ(Factorial(2), 2);
|
||||
EXPECT_EQ(Factorial(3), 6);
|
||||
EXPECT_EQ(Factorial(8), 40320);
|
||||
}
|
||||
```
|
||||
|
||||
googletest groups the test results by test suites, so logically related tests
|
||||
should be in the same test suite; in other words, the first argument to their
|
||||
`TEST()` should be the same. In the above example, we have two tests,
|
||||
`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test
|
||||
suite `FactorialTest`.
|
||||
|
||||
When naming your test suites and tests, you should follow the same convention as
|
||||
for
|
||||
[naming functions and classes](https://google.github.io/styleguide/cppguide.html#Function_Names).
|
||||
|
||||
**Availability**: Linux, Windows, Mac.
|
||||
|
||||
## Test Fixtures: Using the Same Data Configuration for Multiple Tests {#same-data-multiple-tests}
|
||||
|
||||
If you find yourself writing two or more tests that operate on similar data, you
|
||||
can use a *test fixture*. This allows you to reuse the same configuration of
|
||||
objects for several different tests.
|
||||
|
||||
To create a fixture:
|
||||
|
||||
1. Derive a class from `::testing::Test` . Start its body with `protected:`, as
|
||||
we'll want to access fixture members from sub-classes.
|
||||
2. Inside the class, declare any objects you plan to use.
|
||||
3. If necessary, write a default constructor or `SetUp()` function to prepare
|
||||
the objects for each test. A common mistake is to spell `SetUp()` as
|
||||
**`Setup()`** with a small `u` - Use `override` in C++11 to make sure you
|
||||
spelled it correctly.
|
||||
4. If necessary, write a destructor or `TearDown()` function to release any
|
||||
resources you allocated in `SetUp()` . To learn when you should use the
|
||||
constructor/destructor and when you should use `SetUp()/TearDown()`, read
|
||||
the [FAQ](faq.md#CtorVsSetUp).
|
||||
5. If needed, define subroutines for your tests to share.
|
||||
|
||||
When using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to
|
||||
access objects and subroutines in the test fixture:
|
||||
|
||||
```c++
|
||||
TEST_F(TestFixtureName, TestName) {
|
||||
... test body ...
|
||||
}
|
||||
```
|
||||
|
||||
Like `TEST()`, the first argument is the test suite name, but for `TEST_F()`
|
||||
this must be the name of the test fixture class. You've probably guessed: `_F`
|
||||
is for fixture.
|
||||
|
||||
Unfortunately, the C++ macro system does not allow us to create a single macro
|
||||
that can handle both types of tests. Using the wrong macro causes a compiler
|
||||
error.
|
||||
|
||||
Also, you must first define a test fixture class before using it in a
|
||||
`TEST_F()`, or you'll get the compiler error "`virtual outside class
|
||||
declaration`".
|
||||
|
||||
For each test defined with `TEST_F()`, googletest will create a *fresh* test
|
||||
fixture at runtime, immediately initialize it via `SetUp()`, run the test,
|
||||
clean up by calling `TearDown()`, and then delete the test fixture. Note that
|
||||
different tests in the same test suite have different test fixture objects, and
|
||||
googletest always deletes a test fixture before it creates the next one.
|
||||
googletest does **not** reuse the same test fixture for multiple tests. Any
|
||||
changes one test makes to the fixture do not affect other tests.
|
||||
|
||||
As an example, let's write tests for a FIFO queue class named `Queue`, which has
|
||||
the following interface:
|
||||
|
||||
```c++
|
||||
template <typename E> // E is the element type.
|
||||
class Queue {
|
||||
public:
|
||||
Queue();
|
||||
void Enqueue(const E& element);
|
||||
E* Dequeue(); // Returns NULL if the queue is empty.
|
||||
size_t size() const;
|
||||
...
|
||||
};
|
||||
```
|
||||
|
||||
First, define a fixture class. By convention, you should give it the name
|
||||
`FooTest` where `Foo` is the class being tested.
|
||||
|
||||
```c++
|
||||
class QueueTest : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
q1_.Enqueue(1);
|
||||
q2_.Enqueue(2);
|
||||
q2_.Enqueue(3);
|
||||
}
|
||||
|
||||
// void TearDown() override {}
|
||||
|
||||
Queue<int> q0_;
|
||||
Queue<int> q1_;
|
||||
Queue<int> q2_;
|
||||
};
|
||||
```
|
||||
|
||||
In this case, `TearDown()` is not needed since we don't have to clean up after
|
||||
each test, other than what's already done by the destructor.
|
||||
|
||||
Now we'll write tests using `TEST_F()` and this fixture.
|
||||
|
||||
```c++
|
||||
TEST_F(QueueTest, IsEmptyInitially) {
|
||||
EXPECT_EQ(q0_.size(), 0);
|
||||
}
|
||||
|
||||
TEST_F(QueueTest, DequeueWorks) {
|
||||
int* n = q0_.Dequeue();
|
||||
EXPECT_EQ(n, nullptr);
|
||||
|
||||
n = q1_.Dequeue();
|
||||
ASSERT_NE(n, nullptr);
|
||||
EXPECT_EQ(*n, 1);
|
||||
EXPECT_EQ(q1_.size(), 0);
|
||||
delete n;
|
||||
|
||||
n = q2_.Dequeue();
|
||||
ASSERT_NE(n, nullptr);
|
||||
EXPECT_EQ(*n, 2);
|
||||
EXPECT_EQ(q2_.size(), 1);
|
||||
delete n;
|
||||
}
|
||||
```
|
||||
|
||||
The above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is
|
||||
to use `EXPECT_*` when you want the test to continue to reveal more errors after
|
||||
the assertion failure, and use `ASSERT_*` when continuing after failure doesn't
|
||||
make sense. For example, the second assertion in the `Dequeue` test is
|
||||
`ASSERT_NE(n, nullptr)`, as we need to dereference the pointer `n` later, which
|
||||
would lead to a segfault when `n` is `NULL`.
|
||||
|
||||
When these tests run, the following happens:
|
||||
|
||||
1. googletest constructs a `QueueTest` object (let's call it `t1`).
|
||||
2. `t1.SetUp()` initializes `t1`.
|
||||
3. The first test (`IsEmptyInitially`) runs on `t1`.
|
||||
4. `t1.TearDown()` cleans up after the test finishes.
|
||||
5. `t1` is destructed.
|
||||
6. The above steps are repeated on another `QueueTest` object, this time
|
||||
running the `DequeueWorks` test.
|
||||
|
||||
**Availability**: Linux, Windows, Mac.
|
||||
|
||||
## Invoking the Tests
|
||||
|
||||
`TEST()` and `TEST_F()` implicitly register their tests with googletest. So,
|
||||
unlike with many other C++ testing frameworks, you don't have to re-list all
|
||||
your defined tests in order to run them.
|
||||
|
||||
After defining your tests, you can run them with `RUN_ALL_TESTS()`, which
|
||||
returns `0` if all the tests are successful, or `1` otherwise. Note that
|
||||
`RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from
|
||||
different test suites, or even different source files.
|
||||
|
||||
When invoked, the `RUN_ALL_TESTS()` macro:
|
||||
|
||||
* Saves the state of all googletest flags.
|
||||
|
||||
* Creates a test fixture object for the first test.
|
||||
|
||||
* Initializes it via `SetUp()`.
|
||||
|
||||
* Runs the test on the fixture object.
|
||||
|
||||
* Cleans up the fixture via `TearDown()`.
|
||||
|
||||
* Deletes the fixture.
|
||||
|
||||
* Restores the state of all googletest flags.
|
||||
|
||||
* Repeats the above steps for the next test, until all tests have run.
|
||||
|
||||
If a fatal failure happens the subsequent steps will be skipped.
|
||||
|
||||
{: .callout .important}
|
||||
> IMPORTANT: You must **not** ignore the return value of `RUN_ALL_TESTS()`, or
|
||||
> you will get a compiler error. The rationale for this design is that the
|
||||
> automated testing service determines whether a test has passed based on its
|
||||
> exit code, not on its stdout/stderr output; thus your `main()` function must
|
||||
> return the value of `RUN_ALL_TESTS()`.
|
||||
>
|
||||
> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than
|
||||
> once conflicts with some advanced googletest features (e.g., thread-safe
|
||||
> [death tests](advanced.md#death-tests)) and thus is not supported.
|
||||
|
||||
**Availability**: Linux, Windows, Mac.
|
||||
|
||||
## Writing the main() Function
|
||||
|
||||
Most users should _not_ need to write their own `main` function and instead link
|
||||
with `gtest_main` (as opposed to with `gtest`), which defines a suitable entry
|
||||
point. See the end of this section for details. The remainder of this section
|
||||
should only apply when you need to do something custom before the tests run that
|
||||
cannot be expressed within the framework of fixtures and test suites.
|
||||
|
||||
If you write your own `main` function, it should return the value of
|
||||
`RUN_ALL_TESTS()`.
|
||||
|
||||
You can start from this boilerplate:
|
||||
|
||||
```c++
|
||||
#include "this/package/foo.h"
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
namespace my {
|
||||
namespace project {
|
||||
namespace {
|
||||
|
||||
// The fixture for testing class Foo.
|
||||
class FooTest : public ::testing::Test {
|
||||
protected:
|
||||
// You can remove any or all of the following functions if their bodies would
|
||||
// be empty.
|
||||
|
||||
FooTest() {
|
||||
// You can do set-up work for each test here.
|
||||
}
|
||||
|
||||
~FooTest() override {
|
||||
// You can do clean-up work that doesn't throw exceptions here.
|
||||
}
|
||||
|
||||
// If the constructor and destructor are not enough for setting up
|
||||
// and cleaning up each test, you can define the following methods:
|
||||
|
||||
void SetUp() override {
|
||||
// Code here will be called immediately after the constructor (right
|
||||
// before each test).
|
||||
}
|
||||
|
||||
void TearDown() override {
|
||||
// Code here will be called immediately after each test (right
|
||||
// before the destructor).
|
||||
}
|
||||
|
||||
// Class members declared here can be used by all tests in the test suite
|
||||
// for Foo.
|
||||
};
|
||||
|
||||
// Tests that the Foo::Bar() method does Abc.
|
||||
TEST_F(FooTest, MethodBarDoesAbc) {
|
||||
const std::string input_filepath = "this/package/testdata/myinputfile.dat";
|
||||
const std::string output_filepath = "this/package/testdata/myoutputfile.dat";
|
||||
Foo f;
|
||||
EXPECT_EQ(f.Bar(input_filepath, output_filepath), 0);
|
||||
}
|
||||
|
||||
// Tests that Foo does Xyz.
|
||||
TEST_F(FooTest, DoesXyz) {
|
||||
// Exercises the Xyz feature of Foo.
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace project
|
||||
} // namespace my
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
```
|
||||
|
||||
The `::testing::InitGoogleTest()` function parses the command line for
|
||||
googletest flags, and removes all recognized flags. This allows the user to
|
||||
control a test program's behavior via various flags, which we'll cover in
|
||||
the [AdvancedGuide](advanced.md). You **must** call this function before calling
|
||||
`RUN_ALL_TESTS()`, or the flags won't be properly initialized.
|
||||
|
||||
On Windows, `InitGoogleTest()` also works with wide strings, so it can be used
|
||||
in programs compiled in `UNICODE` mode as well.
|
||||
|
||||
But maybe you think that writing all those `main` functions is too much work? We
|
||||
agree with you completely, and that's why Google Test provides a basic
|
||||
implementation of main(). If it fits your needs, then just link your test with
|
||||
the `gtest_main` library and you are good to go.
|
||||
|
||||
{: .callout .note}
|
||||
NOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`.
|
||||
|
||||
## Known Limitations
|
||||
|
||||
* Google Test is designed to be thread-safe. The implementation is thread-safe
|
||||
on systems where the `pthreads` library is available. It is currently
|
||||
_unsafe_ to use Google Test assertions from two threads concurrently on
|
||||
other systems (e.g. Windows). In most tests this is not an issue as usually
|
||||
the assertions are done in the main thread. If you want to help, you can
|
||||
volunteer to implement the necessary synchronization primitives in
|
||||
`gtest-port.h` for your platform.
|
||||
@ -0,0 +1,161 @@
|
||||
# Quickstart: Building with Bazel
|
||||
|
||||
This tutorial aims to get you up and running with GoogleTest using the Bazel
|
||||
build system. If you're using GoogleTest for the first time or need a refresher,
|
||||
we recommend this tutorial as a starting point.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
To complete this tutorial, you'll need:
|
||||
|
||||
* A compatible operating system (e.g. Linux, macOS, Windows).
|
||||
* A compatible C++ compiler that supports at least C++11.
|
||||
* [Bazel](https://bazel.build/), the preferred build system used by the
|
||||
GoogleTest team.
|
||||
|
||||
See [Supported Platforms](platforms.md) for more information about platforms
|
||||
compatible with GoogleTest.
|
||||
|
||||
If you don't already have Bazel installed, see the
|
||||
[Bazel installation guide](https://docs.bazel.build/versions/master/install.html).
|
||||
|
||||
{: .callout .note}
|
||||
Note: The terminal commands in this tutorial show a Unix shell prompt, but the
|
||||
commands work on the Windows command line as well.
|
||||
|
||||
## Set up a Bazel workspace
|
||||
|
||||
A
|
||||
[Bazel workspace](https://docs.bazel.build/versions/master/build-ref.html#workspace)
|
||||
is a directory on your filesystem that you use to manage source files for the
|
||||
software you want to build. Each workspace directory has a text file named
|
||||
`WORKSPACE` which may be empty, or may contain references to external
|
||||
dependencies required to build the outputs.
|
||||
|
||||
First, create a directory for your workspace:
|
||||
|
||||
```
|
||||
$ mkdir my_workspace && cd my_workspace
|
||||
```
|
||||
|
||||
Next, you’ll create the `WORKSPACE` file to specify dependencies. A common and
|
||||
recommended way to depend on GoogleTest is to use a
|
||||
[Bazel external dependency](https://docs.bazel.build/versions/master/external.html)
|
||||
via the
|
||||
[`http_archive` rule](https://docs.bazel.build/versions/master/repo/http.html#http_archive).
|
||||
To do this, in the root directory of your workspace (`my_workspace/`), create a
|
||||
file named `WORKSPACE` with the following contents:
|
||||
|
||||
```
|
||||
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
|
||||
|
||||
http_archive(
|
||||
name = "com_google_googletest",
|
||||
urls = ["https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip"],
|
||||
strip_prefix = "googletest-609281088cfefc76f9d0ce82e1ff6c30cc3591e5",
|
||||
)
|
||||
```
|
||||
|
||||
The above configuration declares a dependency on GoogleTest which is downloaded
|
||||
as a ZIP archive from GitHub. In the above example,
|
||||
`609281088cfefc76f9d0ce82e1ff6c30cc3591e5` is the Git commit hash of the
|
||||
GoogleTest version to use; we recommend updating the hash often to point to the
|
||||
latest version.
|
||||
|
||||
Bazel also needs a dependency on the
|
||||
[`rules_cc` repository](https://github.com/bazelbuild/rules_cc) to build C++
|
||||
code, so add the following to the `WORKSPACE` file:
|
||||
|
||||
```
|
||||
http_archive(
|
||||
name = "rules_cc",
|
||||
urls = ["https://github.com/bazelbuild/rules_cc/archive/40548a2974f1aea06215272d9c2b47a14a24e556.zip"],
|
||||
strip_prefix = "rules_cc-40548a2974f1aea06215272d9c2b47a14a24e556",
|
||||
)
|
||||
```
|
||||
|
||||
Now you're ready to build C++ code that uses GoogleTest.
|
||||
|
||||
## Create and run a binary
|
||||
|
||||
With your Bazel workspace set up, you can now use GoogleTest code within your
|
||||
own project.
|
||||
|
||||
As an example, create a file named `hello_test.cc` in your `my_workspace`
|
||||
directory with the following contents:
|
||||
|
||||
```cpp
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
// Demonstrate some basic assertions.
|
||||
TEST(HelloTest, BasicAssertions) {
|
||||
// Expect two strings not to be equal.
|
||||
EXPECT_STRNE("hello", "world");
|
||||
// Expect equality.
|
||||
EXPECT_EQ(7 * 6, 42);
|
||||
}
|
||||
```
|
||||
|
||||
GoogleTest provides [assertions](primer.md#assertions) that you use to test the
|
||||
behavior of your code. The above sample includes the main GoogleTest header file
|
||||
and demonstrates some basic assertions.
|
||||
|
||||
To build the code, create a file named `BUILD` in the same directory with the
|
||||
following contents:
|
||||
|
||||
```
|
||||
load("@rules_cc//cc:defs.bzl", "cc_test")
|
||||
|
||||
cc_test(
|
||||
name = "hello_test",
|
||||
size = "small",
|
||||
srcs = ["hello_test.cc"],
|
||||
deps = ["@com_google_googletest//:gtest_main"],
|
||||
)
|
||||
```
|
||||
|
||||
This `cc_test` rule declares the C++ test binary you want to build, and links to
|
||||
GoogleTest (`//:gtest_main`) using the prefix you specified in the `WORKSPACE`
|
||||
file (`@com_google_googletest`). For more information about Bazel `BUILD` files,
|
||||
see the
|
||||
[Bazel C++ Tutorial](https://docs.bazel.build/versions/master/tutorial/cpp.html).
|
||||
|
||||
Now you can build and run your test:
|
||||
|
||||
<pre>
|
||||
<strong>my_workspace$ bazel test --test_output=all //:hello_test</strong>
|
||||
INFO: Analyzed target //:hello_test (26 packages loaded, 362 targets configured).
|
||||
INFO: Found 1 test target...
|
||||
INFO: From Testing //:hello_test:
|
||||
==================== Test output for //:hello_test:
|
||||
Running main() from gmock_main.cc
|
||||
[==========] Running 1 test from 1 test suite.
|
||||
[----------] Global test environment set-up.
|
||||
[----------] 1 test from HelloTest
|
||||
[ RUN ] HelloTest.BasicAssertions
|
||||
[ OK ] HelloTest.BasicAssertions (0 ms)
|
||||
[----------] 1 test from HelloTest (0 ms total)
|
||||
|
||||
[----------] Global test environment tear-down
|
||||
[==========] 1 test from 1 test suite ran. (0 ms total)
|
||||
[ PASSED ] 1 test.
|
||||
================================================================================
|
||||
Target //:hello_test up-to-date:
|
||||
bazel-bin/hello_test
|
||||
INFO: Elapsed time: 4.190s, Critical Path: 3.05s
|
||||
INFO: 27 processes: 8 internal, 19 linux-sandbox.
|
||||
INFO: Build completed successfully, 27 total actions
|
||||
//:hello_test PASSED in 0.1s
|
||||
|
||||
INFO: Build completed successfully, 27 total actions
|
||||
</pre>
|
||||
|
||||
Congratulations! You've successfully built and run a test binary using
|
||||
GoogleTest.
|
||||
|
||||
## Next steps
|
||||
|
||||
* [Check out the Primer](primer.md) to start learning how to write simple
|
||||
tests.
|
||||
* [See the code samples](samples.md) for more examples showing how to use a
|
||||
variety of GoogleTest features.
|
||||
@ -0,0 +1,156 @@
|
||||
# Quickstart: Building with CMake
|
||||
|
||||
This tutorial aims to get you up and running with GoogleTest using CMake. If
|
||||
you're using GoogleTest for the first time or need a refresher, we recommend
|
||||
this tutorial as a starting point. If your project uses Bazel, see the
|
||||
[Quickstart for Bazel](quickstart-bazel.md) instead.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
To complete this tutorial, you'll need:
|
||||
|
||||
* A compatible operating system (e.g. Linux, macOS, Windows).
|
||||
* A compatible C++ compiler that supports at least C++11.
|
||||
* [CMake](https://cmake.org/) and a compatible build tool for building the
|
||||
project.
|
||||
* Compatible build tools include
|
||||
[Make](https://www.gnu.org/software/make/),
|
||||
[Ninja](https://ninja-build.org/), and others - see
|
||||
[CMake Generators](https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html)
|
||||
for more information.
|
||||
|
||||
See [Supported Platforms](platforms.md) for more information about platforms
|
||||
compatible with GoogleTest.
|
||||
|
||||
If you don't already have CMake installed, see the
|
||||
[CMake installation guide](https://cmake.org/install).
|
||||
|
||||
{: .callout .note}
|
||||
Note: The terminal commands in this tutorial show a Unix shell prompt, but the
|
||||
commands work on the Windows command line as well.
|
||||
|
||||
## Set up a project
|
||||
|
||||
CMake uses a file named `CMakeLists.txt` to configure the build system for a
|
||||
project. You'll use this file to set up your project and declare a dependency on
|
||||
GoogleTest.
|
||||
|
||||
First, create a directory for your project:
|
||||
|
||||
```
|
||||
$ mkdir my_project && cd my_project
|
||||
```
|
||||
|
||||
Next, you'll create the `CMakeLists.txt` file and declare a dependency on
|
||||
GoogleTest. There are many ways to express dependencies in the CMake ecosystem;
|
||||
in this quickstart, you'll use the
|
||||
[`FetchContent` CMake module](https://cmake.org/cmake/help/latest/module/FetchContent.html).
|
||||
To do this, in your project directory (`my_project`), create a file named
|
||||
`CMakeLists.txt` with the following contents:
|
||||
|
||||
```cmake
|
||||
cmake_minimum_required(VERSION 3.14)
|
||||
project(my_project)
|
||||
|
||||
# GoogleTest requires at least C++11
|
||||
set(CMAKE_CXX_STANDARD 11)
|
||||
|
||||
include(FetchContent)
|
||||
FetchContent_Declare(
|
||||
googletest
|
||||
URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip
|
||||
)
|
||||
# For Windows: Prevent overriding the parent project's compiler/linker settings
|
||||
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
|
||||
FetchContent_MakeAvailable(googletest)
|
||||
```
|
||||
|
||||
The above configuration declares a dependency on GoogleTest which is downloaded
|
||||
from GitHub. In the above example, `609281088cfefc76f9d0ce82e1ff6c30cc3591e5` is
|
||||
the Git commit hash of the GoogleTest version to use; we recommend updating the
|
||||
hash often to point to the latest version.
|
||||
|
||||
For more information about how to create `CMakeLists.txt` files, see the
|
||||
[CMake Tutorial](https://cmake.org/cmake/help/latest/guide/tutorial/index.html).
|
||||
|
||||
## Create and run a binary
|
||||
|
||||
With GoogleTest declared as a dependency, you can use GoogleTest code within
|
||||
your own project.
|
||||
|
||||
As an example, create a file named `hello_test.cc` in your `my_project`
|
||||
directory with the following contents:
|
||||
|
||||
```cpp
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
// Demonstrate some basic assertions.
|
||||
TEST(HelloTest, BasicAssertions) {
|
||||
// Expect two strings not to be equal.
|
||||
EXPECT_STRNE("hello", "world");
|
||||
// Expect equality.
|
||||
EXPECT_EQ(7 * 6, 42);
|
||||
}
|
||||
```
|
||||
|
||||
GoogleTest provides [assertions](primer.md#assertions) that you use to test the
|
||||
behavior of your code. The above sample includes the main GoogleTest header file
|
||||
and demonstrates some basic assertions.
|
||||
|
||||
To build the code, add the following to the end of your `CMakeLists.txt` file:
|
||||
|
||||
```cmake
|
||||
enable_testing()
|
||||
|
||||
add_executable(
|
||||
hello_test
|
||||
hello_test.cc
|
||||
)
|
||||
target_link_libraries(
|
||||
hello_test
|
||||
gtest_main
|
||||
)
|
||||
|
||||
include(GoogleTest)
|
||||
gtest_discover_tests(hello_test)
|
||||
```
|
||||
|
||||
The above configuration enables testing in CMake, declares the C++ test binary
|
||||
you want to build (`hello_test`), and links it to GoogleTest (`gtest_main`). The
|
||||
last two lines enable CMake's test runner to discover the tests included in the
|
||||
binary, using the
|
||||
[`GoogleTest` CMake module](https://cmake.org/cmake/help/git-stage/module/GoogleTest.html).
|
||||
|
||||
Now you can build and run your test:
|
||||
|
||||
<pre>
|
||||
<strong>my_project$ cmake -S . -B build</strong>
|
||||
-- The C compiler identification is GNU 10.2.1
|
||||
-- The CXX compiler identification is GNU 10.2.1
|
||||
...
|
||||
-- Build files have been written to: .../my_project/build
|
||||
|
||||
<strong>my_project$ cmake --build build</strong>
|
||||
Scanning dependencies of target gtest
|
||||
...
|
||||
[100%] Built target gmock_main
|
||||
|
||||
<strong>my_project$ cd build && ctest</strong>
|
||||
Test project .../my_project/build
|
||||
Start 1: HelloTest.BasicAssertions
|
||||
1/1 Test #1: HelloTest.BasicAssertions ........ Passed 0.00 sec
|
||||
|
||||
100% tests passed, 0 tests failed out of 1
|
||||
|
||||
Total Test time (real) = 0.01 sec
|
||||
</pre>
|
||||
|
||||
Congratulations! You've successfully built and run a test binary using
|
||||
GoogleTest.
|
||||
|
||||
## Next steps
|
||||
|
||||
* [Check out the Primer](primer.md) to start learning how to write simple
|
||||
tests.
|
||||
* [See the code samples](samples.md) for more examples showing how to use a
|
||||
variety of GoogleTest features.
|
||||
@ -0,0 +1,115 @@
|
||||
# Actions Reference
|
||||
|
||||
[**Actions**](../gmock_for_dummies.md#actions-what-should-it-do) specify what a
|
||||
mock function should do when invoked. This page lists the built-in actions
|
||||
provided by GoogleTest. All actions are defined in the `::testing` namespace.
|
||||
|
||||
## Returning a Value
|
||||
|
||||
| | |
|
||||
| :-------------------------------- | :-------------------------------------------- |
|
||||
| `Return()` | Return from a `void` mock function. |
|
||||
| `Return(value)` | Return `value`. If the type of `value` is different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed. |
|
||||
| `ReturnArg<N>()` | Return the `N`-th (0-based) argument. |
|
||||
| `ReturnNew<T>(a1, ..., ak)` | Return `new T(a1, ..., ak)`; a different object is created each time. |
|
||||
| `ReturnNull()` | Return a null pointer. |
|
||||
| `ReturnPointee(ptr)` | Return the value pointed to by `ptr`. |
|
||||
| `ReturnRef(variable)` | Return a reference to `variable`. |
|
||||
| `ReturnRefOfCopy(value)` | Return a reference to a copy of `value`; the copy lives as long as the action. |
|
||||
| `ReturnRoundRobin({a1, ..., ak})` | Each call will return the next `ai` in the list, starting at the beginning when the end of the list is reached. |
|
||||
|
||||
## Side Effects
|
||||
|
||||
| | |
|
||||
| :--------------------------------- | :-------------------------------------- |
|
||||
| `Assign(&variable, value)` | Assign `value` to variable. |
|
||||
| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. |
|
||||
| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. |
|
||||
| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. |
|
||||
| `SetArgReferee<N>(value)` | Assign `value` to the variable referenced by the `N`-th (0-based) argument. |
|
||||
| `SetArgPointee<N>(value)` | Assign `value` to the variable pointed by the `N`-th (0-based) argument. |
|
||||
| `SetArgumentPointee<N>(value)` | Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0. |
|
||||
| `SetArrayArgument<N>(first, last)` | Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range. |
|
||||
| `SetErrnoAndReturn(error, value)` | Set `errno` to `error` and return `value`. |
|
||||
| `Throw(exception)` | Throws the given exception, which can be any copyable value. Available since v1.1.0. |
|
||||
|
||||
## Using a Function, Functor, or Lambda as an Action
|
||||
|
||||
In the following, by "callable" we mean a free function, `std::function`,
|
||||
functor, or lambda.
|
||||
|
||||
| | |
|
||||
| :---------------------------------- | :------------------------------------- |
|
||||
| `f` | Invoke f with the arguments passed to the mock function, where f is a callable. |
|
||||
| `Invoke(f)` | Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor. |
|
||||
| `Invoke(object_pointer, &class::method)` | Invoke the method on the object with the arguments passed to the mock function. |
|
||||
| `InvokeWithoutArgs(f)` | Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. |
|
||||
| `InvokeWithoutArgs(object_pointer, &class::method)` | Invoke the method on the object, which takes no arguments. |
|
||||
| `InvokeArgument<N>(arg1, arg2, ..., argk)` | Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments. |
|
||||
|
||||
The return value of the invoked function is used as the return value of the
|
||||
action.
|
||||
|
||||
When defining a callable to be used with `Invoke*()`, you can declare any unused
|
||||
parameters as `Unused`:
|
||||
|
||||
```cpp
|
||||
using ::testing::Invoke;
|
||||
double Distance(Unused, double x, double y) { return sqrt(x*x + y*y); }
|
||||
...
|
||||
EXPECT_CALL(mock, Foo("Hi", _, _)).WillOnce(Invoke(Distance));
|
||||
```
|
||||
|
||||
`Invoke(callback)` and `InvokeWithoutArgs(callback)` take ownership of
|
||||
`callback`, which must be permanent. The type of `callback` must be a base
|
||||
callback type instead of a derived one, e.g.
|
||||
|
||||
```cpp
|
||||
BlockingClosure* done = new BlockingClosure;
|
||||
... Invoke(done) ...; // This won't compile!
|
||||
|
||||
Closure* done2 = new BlockingClosure;
|
||||
... Invoke(done2) ...; // This works.
|
||||
```
|
||||
|
||||
In `InvokeArgument<N>(...)`, if an argument needs to be passed by reference,
|
||||
wrap it inside `std::ref()`. For example,
|
||||
|
||||
```cpp
|
||||
using ::testing::InvokeArgument;
|
||||
...
|
||||
InvokeArgument<2>(5, string("Hi"), std::ref(foo))
|
||||
```
|
||||
|
||||
calls the mock function's #2 argument, passing to it `5` and `string("Hi")` by
|
||||
value, and `foo` by reference.
|
||||
|
||||
## Default Action
|
||||
|
||||
| Matcher | Description |
|
||||
| :------------ | :----------------------------------------------------- |
|
||||
| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). |
|
||||
|
||||
{: .callout .note}
|
||||
**Note:** due to technical reasons, `DoDefault()` cannot be used inside a
|
||||
composite action - trying to do so will result in a run-time error.
|
||||
|
||||
## Composite Actions
|
||||
|
||||
| | |
|
||||
| :----------------------------- | :------------------------------------------ |
|
||||
| `DoAll(a1, a2, ..., an)` | Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void and will receive a readonly view of the arguments. |
|
||||
| `IgnoreResult(a)` | Perform action `a` and ignore its result. `a` must not return void. |
|
||||
| `WithArg<N>(a)` | Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. |
|
||||
| `WithArgs<N1, N2, ..., Nk>(a)` | Pass the selected (0-based) arguments of the mock function to action `a` and perform it. |
|
||||
| `WithoutArgs(a)` | Perform action `a` without any arguments. |
|
||||
|
||||
## Defining Actions
|
||||
|
||||
| | |
|
||||
| :--------------------------------- | :-------------------------------------- |
|
||||
| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. |
|
||||
| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. |
|
||||
| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. |
|
||||
|
||||
The `ACTION*` macros cannot be used inside a function or class.
|
||||
@ -0,0 +1,633 @@
|
||||
# Assertions Reference
|
||||
|
||||
This page lists the assertion macros provided by GoogleTest for verifying code
|
||||
behavior. To use them, include the header `gtest/gtest.h`.
|
||||
|
||||
The majority of the macros listed below come as a pair with an `EXPECT_` variant
|
||||
and an `ASSERT_` variant. Upon failure, `EXPECT_` macros generate nonfatal
|
||||
failures and allow the current function to continue running, while `ASSERT_`
|
||||
macros generate fatal failures and abort the current function.
|
||||
|
||||
All assertion macros support streaming a custom failure message into them with
|
||||
the `<<` operator, for example:
|
||||
|
||||
```cpp
|
||||
EXPECT_TRUE(my_condition) << "My condition is not true";
|
||||
```
|
||||
|
||||
Anything that can be streamed to an `ostream` can be streamed to an assertion
|
||||
macro—in particular, C strings and string objects. If a wide string (`wchar_t*`,
|
||||
`TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is streamed to an
|
||||
assertion, it will be translated to UTF-8 when printed.
|
||||
|
||||
## Explicit Success and Failure {#success-failure}
|
||||
|
||||
The assertions in this section generate a success or failure directly instead of
|
||||
testing a value or expression. These are useful when control flow, rather than a
|
||||
Boolean expression, determines the test's success or failure, as shown by the
|
||||
following example:
|
||||
|
||||
```c++
|
||||
switch(expression) {
|
||||
case 1:
|
||||
... some checks ...
|
||||
case 2:
|
||||
... some other checks ...
|
||||
default:
|
||||
FAIL() << "We shouldn't get here.";
|
||||
}
|
||||
```
|
||||
|
||||
### SUCCEED {#SUCCEED}
|
||||
|
||||
`SUCCEED()`
|
||||
|
||||
Generates a success. This *does not* make the overall test succeed. A test is
|
||||
considered successful only if none of its assertions fail during its execution.
|
||||
|
||||
The `SUCCEED` assertion is purely documentary and currently doesn't generate any
|
||||
user-visible output. However, we may add `SUCCEED` messages to GoogleTest output
|
||||
in the future.
|
||||
|
||||
### FAIL {#FAIL}
|
||||
|
||||
`FAIL()`
|
||||
|
||||
Generates a fatal failure, which returns from the current function.
|
||||
|
||||
Can only be used in functions that return `void`. See
|
||||
[Assertion Placement](../advanced.md#assertion-placement) for more information.
|
||||
|
||||
### ADD_FAILURE {#ADD_FAILURE}
|
||||
|
||||
`ADD_FAILURE()`
|
||||
|
||||
Generates a nonfatal failure, which allows the current function to continue
|
||||
running.
|
||||
|
||||
### ADD_FAILURE_AT {#ADD_FAILURE_AT}
|
||||
|
||||
`ADD_FAILURE_AT(`*`file_path`*`,`*`line_number`*`)`
|
||||
|
||||
Generates a nonfatal failure at the file and line number specified.
|
||||
|
||||
## Generalized Assertion {#generalized}
|
||||
|
||||
The following assertion allows [matchers](matchers.md) to be used to verify
|
||||
values.
|
||||
|
||||
### EXPECT_THAT {#EXPECT_THAT}
|
||||
|
||||
`EXPECT_THAT(`*`value`*`,`*`matcher`*`)` \
|
||||
`ASSERT_THAT(`*`value`*`,`*`matcher`*`)`
|
||||
|
||||
Verifies that *`value`* matches the [matcher](matchers.md) *`matcher`*.
|
||||
|
||||
For example, the following code verifies that the string `value1` starts with
|
||||
`"Hello"`, `value2` matches a regular expression, and `value3` is between 5 and
|
||||
10:
|
||||
|
||||
```cpp
|
||||
#include "gmock/gmock.h"
|
||||
|
||||
using ::testing::AllOf;
|
||||
using ::testing::Gt;
|
||||
using ::testing::Lt;
|
||||
using ::testing::MatchesRegex;
|
||||
using ::testing::StartsWith;
|
||||
|
||||
...
|
||||
EXPECT_THAT(value1, StartsWith("Hello"));
|
||||
EXPECT_THAT(value2, MatchesRegex("Line \\d+"));
|
||||
ASSERT_THAT(value3, AllOf(Gt(5), Lt(10)));
|
||||
```
|
||||
|
||||
Matchers enable assertions of this form to read like English and generate
|
||||
informative failure messages. For example, if the above assertion on `value1`
|
||||
fails, the resulting message will be similar to the following:
|
||||
|
||||
```
|
||||
Value of: value1
|
||||
Actual: "Hi, world!"
|
||||
Expected: starts with "Hello"
|
||||
```
|
||||
|
||||
GoogleTest provides a built-in library of matchers—see the
|
||||
[Matchers Reference](matchers.md). It is also possible to write your own
|
||||
matchers—see [Writing New Matchers Quickly](../gmock_cook_book.md#NewMatchers).
|
||||
The use of matchers makes `EXPECT_THAT` a powerful, extensible assertion.
|
||||
|
||||
*The idea for this assertion was borrowed from Joe Walnes' Hamcrest project,
|
||||
which adds `assertThat()` to JUnit.*
|
||||
|
||||
## Boolean Conditions {#boolean}
|
||||
|
||||
The following assertions test Boolean conditions.
|
||||
|
||||
### EXPECT_TRUE {#EXPECT_TRUE}
|
||||
|
||||
`EXPECT_TRUE(`*`condition`*`)` \
|
||||
`ASSERT_TRUE(`*`condition`*`)`
|
||||
|
||||
Verifies that *`condition`* is true.
|
||||
|
||||
### EXPECT_FALSE {#EXPECT_FALSE}
|
||||
|
||||
`EXPECT_FALSE(`*`condition`*`)` \
|
||||
`ASSERT_FALSE(`*`condition`*`)`
|
||||
|
||||
Verifies that *`condition`* is false.
|
||||
|
||||
## Binary Comparison {#binary-comparison}
|
||||
|
||||
The following assertions compare two values. The value arguments must be
|
||||
comparable by the assertion's comparison operator, otherwise a compiler error
|
||||
will result.
|
||||
|
||||
If an argument supports the `<<` operator, it will be called to print the
|
||||
argument when the assertion fails. Otherwise, GoogleTest will attempt to print
|
||||
them in the best way it can—see
|
||||
[Teaching GoogleTest How to Print Your Values](../advanced.md#teaching-googletest-how-to-print-your-values).
|
||||
|
||||
Arguments are always evaluated exactly once, so it's OK for the arguments to
|
||||
have side effects. However, the argument evaluation order is undefined and
|
||||
programs should not depend on any particular argument evaluation order.
|
||||
|
||||
These assertions work with both narrow and wide string objects (`string` and
|
||||
`wstring`).
|
||||
|
||||
See also the [Floating-Point Comparison](#floating-point) assertions to compare
|
||||
floating-point numbers and avoid problems caused by rounding.
|
||||
|
||||
### EXPECT_EQ {#EXPECT_EQ}
|
||||
|
||||
`EXPECT_EQ(`*`val1`*`,`*`val2`*`)` \
|
||||
`ASSERT_EQ(`*`val1`*`,`*`val2`*`)`
|
||||
|
||||
Verifies that *`val1`*`==`*`val2`*.
|
||||
|
||||
Does pointer equality on pointers. If used on two C strings, it tests if they
|
||||
are in the same memory location, not if they have the same value. Use
|
||||
[`EXPECT_STREQ`](#EXPECT_STREQ) to compare C strings (e.g. `const char*`) by
|
||||
value.
|
||||
|
||||
When comparing a pointer to `NULL`, use `EXPECT_EQ(`*`ptr`*`, nullptr)` instead
|
||||
of `EXPECT_EQ(`*`ptr`*`, NULL)`.
|
||||
|
||||
### EXPECT_NE {#EXPECT_NE}
|
||||
|
||||
`EXPECT_NE(`*`val1`*`,`*`val2`*`)` \
|
||||
`ASSERT_NE(`*`val1`*`,`*`val2`*`)`
|
||||
|
||||
Verifies that *`val1`*`!=`*`val2`*.
|
||||
|
||||
Does pointer equality on pointers. If used on two C strings, it tests if they
|
||||
are in different memory locations, not if they have different values. Use
|
||||
[`EXPECT_STRNE`](#EXPECT_STRNE) to compare C strings (e.g. `const char*`) by
|
||||
value.
|
||||
|
||||
When comparing a pointer to `NULL`, use `EXPECT_NE(`*`ptr`*`, nullptr)` instead
|
||||
of `EXPECT_NE(`*`ptr`*`, NULL)`.
|
||||
|
||||
### EXPECT_LT {#EXPECT_LT}
|
||||
|
||||
`EXPECT_LT(`*`val1`*`,`*`val2`*`)` \
|
||||
`ASSERT_LT(`*`val1`*`,`*`val2`*`)`
|
||||
|
||||
Verifies that *`val1`*`<`*`val2`*.
|
||||
|
||||
### EXPECT_LE {#EXPECT_LE}
|
||||
|
||||
`EXPECT_LE(`*`val1`*`,`*`val2`*`)` \
|
||||
`ASSERT_LE(`*`val1`*`,`*`val2`*`)`
|
||||
|
||||
Verifies that *`val1`*`<=`*`val2`*.
|
||||
|
||||
### EXPECT_GT {#EXPECT_GT}
|
||||
|
||||
`EXPECT_GT(`*`val1`*`,`*`val2`*`)` \
|
||||
`ASSERT_GT(`*`val1`*`,`*`val2`*`)`
|
||||
|
||||
Verifies that *`val1`*`>`*`val2`*.
|
||||
|
||||
### EXPECT_GE {#EXPECT_GE}
|
||||
|
||||
`EXPECT_GE(`*`val1`*`,`*`val2`*`)` \
|
||||
`ASSERT_GE(`*`val1`*`,`*`val2`*`)`
|
||||
|
||||
Verifies that *`val1`*`>=`*`val2`*.
|
||||
|
||||
## String Comparison {#c-strings}
|
||||
|
||||
The following assertions compare two **C strings**. To compare two `string`
|
||||
objects, use [`EXPECT_EQ`](#EXPECT_EQ) or [`EXPECT_NE`](#EXPECT_NE) instead.
|
||||
|
||||
These assertions also accept wide C strings (`wchar_t*`). If a comparison of two
|
||||
wide strings fails, their values will be printed as UTF-8 narrow strings.
|
||||
|
||||
To compare a C string with `NULL`, use `EXPECT_EQ(`*`c_string`*`, nullptr)` or
|
||||
`EXPECT_NE(`*`c_string`*`, nullptr)`.
|
||||
|
||||
### EXPECT_STREQ {#EXPECT_STREQ}
|
||||
|
||||
`EXPECT_STREQ(`*`str1`*`,`*`str2`*`)` \
|
||||
`ASSERT_STREQ(`*`str1`*`,`*`str2`*`)`
|
||||
|
||||
Verifies that the two C strings *`str1`* and *`str2`* have the same contents.
|
||||
|
||||
### EXPECT_STRNE {#EXPECT_STRNE}
|
||||
|
||||
`EXPECT_STRNE(`*`str1`*`,`*`str2`*`)` \
|
||||
`ASSERT_STRNE(`*`str1`*`,`*`str2`*`)`
|
||||
|
||||
Verifies that the two C strings *`str1`* and *`str2`* have different contents.
|
||||
|
||||
### EXPECT_STRCASEEQ {#EXPECT_STRCASEEQ}
|
||||
|
||||
`EXPECT_STRCASEEQ(`*`str1`*`,`*`str2`*`)` \
|
||||
`ASSERT_STRCASEEQ(`*`str1`*`,`*`str2`*`)`
|
||||
|
||||
Verifies that the two C strings *`str1`* and *`str2`* have the same contents,
|
||||
ignoring case.
|
||||
|
||||
### EXPECT_STRCASENE {#EXPECT_STRCASENE}
|
||||
|
||||
`EXPECT_STRCASENE(`*`str1`*`,`*`str2`*`)` \
|
||||
`ASSERT_STRCASENE(`*`str1`*`,`*`str2`*`)`
|
||||
|
||||
Verifies that the two C strings *`str1`* and *`str2`* have different contents,
|
||||
ignoring case.
|
||||
|
||||
## Floating-Point Comparison {#floating-point}
|
||||
|
||||
The following assertions compare two floating-point values.
|
||||
|
||||
Due to rounding errors, it is very unlikely that two floating-point values will
|
||||
match exactly, so `EXPECT_EQ` is not suitable. In general, for floating-point
|
||||
comparison to make sense, the user needs to carefully choose the error bound.
|
||||
|
||||
GoogleTest also provides assertions that use a default error bound based on
|
||||
Units in the Last Place (ULPs). To learn more about ULPs, see the article
|
||||
[Comparing Floating Point Numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
|
||||
|
||||
### EXPECT_FLOAT_EQ {#EXPECT_FLOAT_EQ}
|
||||
|
||||
`EXPECT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)` \
|
||||
`ASSERT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)`
|
||||
|
||||
Verifies that the two `float` values *`val1`* and *`val2`* are approximately
|
||||
equal, to within 4 ULPs from each other.
|
||||
|
||||
### EXPECT_DOUBLE_EQ {#EXPECT_DOUBLE_EQ}
|
||||
|
||||
`EXPECT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)` \
|
||||
`ASSERT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)`
|
||||
|
||||
Verifies that the two `double` values *`val1`* and *`val2`* are approximately
|
||||
equal, to within 4 ULPs from each other.
|
||||
|
||||
### EXPECT_NEAR {#EXPECT_NEAR}
|
||||
|
||||
`EXPECT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)` \
|
||||
`ASSERT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)`
|
||||
|
||||
Verifies that the difference between *`val1`* and *`val2`* does not exceed the
|
||||
absolute error bound *`abs_error`*.
|
||||
|
||||
## Exception Assertions {#exceptions}
|
||||
|
||||
The following assertions verify that a piece of code throws, or does not throw,
|
||||
an exception. Usage requires exceptions to be enabled in the build environment.
|
||||
|
||||
Note that the piece of code under test can be a compound statement, for example:
|
||||
|
||||
```cpp
|
||||
EXPECT_NO_THROW({
|
||||
int n = 5;
|
||||
DoSomething(&n);
|
||||
});
|
||||
```
|
||||
|
||||
### EXPECT_THROW {#EXPECT_THROW}
|
||||
|
||||
`EXPECT_THROW(`*`statement`*`,`*`exception_type`*`)` \
|
||||
`ASSERT_THROW(`*`statement`*`,`*`exception_type`*`)`
|
||||
|
||||
Verifies that *`statement`* throws an exception of type *`exception_type`*.
|
||||
|
||||
### EXPECT_ANY_THROW {#EXPECT_ANY_THROW}
|
||||
|
||||
`EXPECT_ANY_THROW(`*`statement`*`)` \
|
||||
`ASSERT_ANY_THROW(`*`statement`*`)`
|
||||
|
||||
Verifies that *`statement`* throws an exception of any type.
|
||||
|
||||
### EXPECT_NO_THROW {#EXPECT_NO_THROW}
|
||||
|
||||
`EXPECT_NO_THROW(`*`statement`*`)` \
|
||||
`ASSERT_NO_THROW(`*`statement`*`)`
|
||||
|
||||
Verifies that *`statement`* does not throw any exception.
|
||||
|
||||
## Predicate Assertions {#predicates}
|
||||
|
||||
The following assertions enable more complex predicates to be verified while
|
||||
printing a more clear failure message than if `EXPECT_TRUE` were used alone.
|
||||
|
||||
### EXPECT_PRED* {#EXPECT_PRED}
|
||||
|
||||
`EXPECT_PRED1(`*`pred`*`,`*`val1`*`)` \
|
||||
`EXPECT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \
|
||||
`EXPECT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \
|
||||
`EXPECT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \
|
||||
`EXPECT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)`
|
||||
|
||||
`ASSERT_PRED1(`*`pred`*`,`*`val1`*`)` \
|
||||
`ASSERT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \
|
||||
`ASSERT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \
|
||||
`ASSERT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \
|
||||
`ASSERT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)`
|
||||
|
||||
Verifies that the predicate *`pred`* returns `true` when passed the given values
|
||||
as arguments.
|
||||
|
||||
The parameter *`pred`* is a function or functor that accepts as many arguments
|
||||
as the corresponding macro accepts values. If *`pred`* returns `true` for the
|
||||
given arguments, the assertion succeeds, otherwise the assertion fails.
|
||||
|
||||
When the assertion fails, it prints the value of each argument. Arguments are
|
||||
always evaluated exactly once.
|
||||
|
||||
As an example, see the following code:
|
||||
|
||||
```cpp
|
||||
// Returns true if m and n have no common divisors except 1.
|
||||
bool MutuallyPrime(int m, int n) { ... }
|
||||
...
|
||||
const int a = 3;
|
||||
const int b = 4;
|
||||
const int c = 10;
|
||||
...
|
||||
EXPECT_PRED2(MutuallyPrime, a, b); // Succeeds
|
||||
EXPECT_PRED2(MutuallyPrime, b, c); // Fails
|
||||
```
|
||||
|
||||
In the above example, the first assertion succeeds, and the second fails with
|
||||
the following message:
|
||||
|
||||
```
|
||||
MutuallyPrime(b, c) is false, where
|
||||
b is 4
|
||||
c is 10
|
||||
```
|
||||
|
||||
Note that if the given predicate is an overloaded function or a function
|
||||
template, the assertion macro might not be able to determine which version to
|
||||
use, and it might be necessary to explicitly specify the type of the function.
|
||||
For example, for a Boolean function `IsPositive()` overloaded to take either a
|
||||
single `int` or `double` argument, it would be necessary to write one of the
|
||||
following:
|
||||
|
||||
```cpp
|
||||
EXPECT_PRED1(static_cast<bool (*)(int)>(IsPositive), 5);
|
||||
EXPECT_PRED1(static_cast<bool (*)(double)>(IsPositive), 3.14);
|
||||
```
|
||||
|
||||
Writing simply `EXPECT_PRED1(IsPositive, 5);` would result in a compiler error.
|
||||
Similarly, to use a template function, specify the template arguments:
|
||||
|
||||
```cpp
|
||||
template <typename T>
|
||||
bool IsNegative(T x) {
|
||||
return x < 0;
|
||||
}
|
||||
...
|
||||
EXPECT_PRED1(IsNegative<int>, -5); // Must specify type for IsNegative
|
||||
```
|
||||
|
||||
If a template has multiple parameters, wrap the predicate in parentheses so the
|
||||
macro arguments are parsed correctly:
|
||||
|
||||
```cpp
|
||||
ASSERT_PRED2((MyPredicate<int, int>), 5, 0);
|
||||
```
|
||||
|
||||
### EXPECT_PRED_FORMAT* {#EXPECT_PRED_FORMAT}
|
||||
|
||||
`EXPECT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \
|
||||
`EXPECT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \
|
||||
`EXPECT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \
|
||||
`EXPECT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)`
|
||||
\
|
||||
`EXPECT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)`
|
||||
|
||||
`ASSERT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \
|
||||
`ASSERT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \
|
||||
`ASSERT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \
|
||||
`ASSERT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)`
|
||||
\
|
||||
`ASSERT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)`
|
||||
|
||||
Verifies that the predicate *`pred_formatter`* succeeds when passed the given
|
||||
values as arguments.
|
||||
|
||||
The parameter *`pred_formatter`* is a *predicate-formatter*, which is a function
|
||||
or functor with the signature:
|
||||
|
||||
```cpp
|
||||
testing::AssertionResult PredicateFormatter(const char* expr1,
|
||||
const char* expr2,
|
||||
...
|
||||
const char* exprn,
|
||||
T1 val1,
|
||||
T2 val2,
|
||||
...
|
||||
Tn valn);
|
||||
```
|
||||
|
||||
where *`val1`*, *`val2`*, ..., *`valn`* are the values of the predicate
|
||||
arguments, and *`expr1`*, *`expr2`*, ..., *`exprn`* are the corresponding
|
||||
expressions as they appear in the source code. The types `T1`, `T2`, ..., `Tn`
|
||||
can be either value types or reference types; if an argument has type `T`, it
|
||||
can be declared as either `T` or `const T&`, whichever is appropriate. For more
|
||||
about the return type `testing::AssertionResult`, see
|
||||
[Using a Function That Returns an AssertionResult](../advanced.md#using-a-function-that-returns-an-assertionresult).
|
||||
|
||||
As an example, see the following code:
|
||||
|
||||
```cpp
|
||||
// Returns the smallest prime common divisor of m and n,
|
||||
// or 1 when m and n are mutually prime.
|
||||
int SmallestPrimeCommonDivisor(int m, int n) { ... }
|
||||
|
||||
// Returns true if m and n have no common divisors except 1.
|
||||
bool MutuallyPrime(int m, int n) { ... }
|
||||
|
||||
// A predicate-formatter for asserting that two integers are mutually prime.
|
||||
testing::AssertionResult AssertMutuallyPrime(const char* m_expr,
|
||||
const char* n_expr,
|
||||
int m,
|
||||
int n) {
|
||||
if (MutuallyPrime(m, n)) return testing::AssertionSuccess();
|
||||
|
||||
return testing::AssertionFailure() << m_expr << " and " << n_expr
|
||||
<< " (" << m << " and " << n << ") are not mutually prime, "
|
||||
<< "as they have a common divisor " << SmallestPrimeCommonDivisor(m, n);
|
||||
}
|
||||
|
||||
...
|
||||
const int a = 3;
|
||||
const int b = 4;
|
||||
const int c = 10;
|
||||
...
|
||||
EXPECT_PRED_FORMAT2(AssertMutuallyPrime, a, b); // Succeeds
|
||||
EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c); // Fails
|
||||
```
|
||||
|
||||
In the above example, the final assertion fails and the predicate-formatter
|
||||
produces the following failure message:
|
||||
|
||||
```
|
||||
b and c (4 and 10) are not mutually prime, as they have a common divisor 2
|
||||
```
|
||||
|
||||
## Windows HRESULT Assertions {#HRESULT}
|
||||
|
||||
The following assertions test for `HRESULT` success or failure. For example:
|
||||
|
||||
```cpp
|
||||
CComPtr<IShellDispatch2> shell;
|
||||
ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L"Shell.Application"));
|
||||
CComVariant empty;
|
||||
ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty));
|
||||
```
|
||||
|
||||
The generated output contains the human-readable error message associated with
|
||||
the returned `HRESULT` code.
|
||||
|
||||
### EXPECT_HRESULT_SUCCEEDED {#EXPECT_HRESULT_SUCCEEDED}
|
||||
|
||||
`EXPECT_HRESULT_SUCCEEDED(`*`expression`*`)` \
|
||||
`ASSERT_HRESULT_SUCCEEDED(`*`expression`*`)`
|
||||
|
||||
Verifies that *`expression`* is a success `HRESULT`.
|
||||
|
||||
### EXPECT_HRESULT_FAILED {#EXPECT_HRESULT_FAILED}
|
||||
|
||||
`EXPECT_HRESULT_FAILED(`*`expression`*`)` \
|
||||
`EXPECT_HRESULT_FAILED(`*`expression`*`)`
|
||||
|
||||
Verifies that *`expression`* is a failure `HRESULT`.
|
||||
|
||||
## Death Assertions {#death}
|
||||
|
||||
The following assertions verify that a piece of code causes the process to
|
||||
terminate. For context, see [Death Tests](../advanced.md#death-tests).
|
||||
|
||||
These assertions spawn a new process and execute the code under test in that
|
||||
process. How that happens depends on the platform and the variable
|
||||
`::testing::GTEST_FLAG(death_test_style)`, which is initialized from the
|
||||
command-line flag `--gtest_death_test_style`.
|
||||
|
||||
* On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the
|
||||
child, after which:
|
||||
* If the variable's value is `"fast"`, the death test statement is
|
||||
immediately executed.
|
||||
* If the variable's value is `"threadsafe"`, the child process re-executes
|
||||
the unit test binary just as it was originally invoked, but with some
|
||||
extra flags to cause just the single death test under consideration to
|
||||
be run.
|
||||
* On Windows, the child is spawned using the `CreateProcess()` API, and
|
||||
re-executes the binary to cause just the single death test under
|
||||
consideration to be run - much like the `"threadsafe"` mode on POSIX.
|
||||
|
||||
Other values for the variable are illegal and will cause the death test to fail.
|
||||
Currently, the flag's default value is
|
||||
**`"fast"`**.
|
||||
|
||||
If the death test statement runs to completion without dying, the child process
|
||||
will nonetheless terminate, and the assertion fails.
|
||||
|
||||
Note that the piece of code under test can be a compound statement, for example:
|
||||
|
||||
```cpp
|
||||
EXPECT_DEATH({
|
||||
int n = 5;
|
||||
DoSomething(&n);
|
||||
}, "Error on line .* of DoSomething()");
|
||||
```
|
||||
|
||||
### EXPECT_DEATH {#EXPECT_DEATH}
|
||||
|
||||
`EXPECT_DEATH(`*`statement`*`,`*`matcher`*`)` \
|
||||
`ASSERT_DEATH(`*`statement`*`,`*`matcher`*`)`
|
||||
|
||||
Verifies that *`statement`* causes the process to terminate with a nonzero exit
|
||||
status and produces `stderr` output that matches *`matcher`*.
|
||||
|
||||
The parameter *`matcher`* is either a [matcher](matchers.md) for a `const
|
||||
std::string&`, or a regular expression (see
|
||||
[Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare
|
||||
string *`s`* (with no matcher) is treated as
|
||||
[`ContainsRegex(s)`](matchers.md#string-matchers), **not**
|
||||
[`Eq(s)`](matchers.md#generic-comparison).
|
||||
|
||||
For example, the following code verifies that calling `DoSomething(42)` causes
|
||||
the process to die with an error message that contains the text `My error`:
|
||||
|
||||
```cpp
|
||||
EXPECT_DEATH(DoSomething(42), "My error");
|
||||
```
|
||||
|
||||
### EXPECT_DEATH_IF_SUPPORTED {#EXPECT_DEATH_IF_SUPPORTED}
|
||||
|
||||
`EXPECT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)` \
|
||||
`ASSERT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)`
|
||||
|
||||
If death tests are supported, behaves the same as
|
||||
[`EXPECT_DEATH`](#EXPECT_DEATH). Otherwise, verifies nothing.
|
||||
|
||||
### EXPECT_DEBUG_DEATH {#EXPECT_DEBUG_DEATH}
|
||||
|
||||
`EXPECT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)` \
|
||||
`ASSERT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)`
|
||||
|
||||
In debug mode, behaves the same as [`EXPECT_DEATH`](#EXPECT_DEATH). When not in
|
||||
debug mode (i.e. `NDEBUG` is defined), just executes *`statement`*.
|
||||
|
||||
### EXPECT_EXIT {#EXPECT_EXIT}
|
||||
|
||||
`EXPECT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)` \
|
||||
`ASSERT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)`
|
||||
|
||||
Verifies that *`statement`* causes the process to terminate with an exit status
|
||||
that satisfies *`predicate`*, and produces `stderr` output that matches
|
||||
*`matcher`*.
|
||||
|
||||
The parameter *`predicate`* is a function or functor that accepts an `int` exit
|
||||
status and returns a `bool`. GoogleTest provides two predicates to handle common
|
||||
cases:
|
||||
|
||||
```cpp
|
||||
// Returns true if the program exited normally with the given exit status code.
|
||||
::testing::ExitedWithCode(exit_code);
|
||||
|
||||
// Returns true if the program was killed by the given signal.
|
||||
// Not available on Windows.
|
||||
::testing::KilledBySignal(signal_number);
|
||||
```
|
||||
|
||||
The parameter *`matcher`* is either a [matcher](matchers.md) for a `const
|
||||
std::string&`, or a regular expression (see
|
||||
[Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare
|
||||
string *`s`* (with no matcher) is treated as
|
||||
[`ContainsRegex(s)`](matchers.md#string-matchers), **not**
|
||||
[`Eq(s)`](matchers.md#generic-comparison).
|
||||
|
||||
For example, the following code verifies that calling `NormalExit()` causes the
|
||||
process to print a message containing the text `Success` to `stderr` and exit
|
||||
with exit status code 0:
|
||||
|
||||
```cpp
|
||||
EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), "Success");
|
||||
```
|
||||
@ -0,0 +1,283 @@
|
||||
# Matchers Reference
|
||||
|
||||
A **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or
|
||||
`EXPECT_CALL()`, or use it to validate a value directly using two macros:
|
||||
|
||||
| Macro | Description |
|
||||
| :----------------------------------- | :------------------------------------ |
|
||||
| `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `matcher`. |
|
||||
| `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. |
|
||||
|
||||
{: .callout .note}
|
||||
**Note:** Although equality matching via `EXPECT_THAT(actual_value,
|
||||
expected_value)` is supported, prefer to make the comparison explicit via
|
||||
`EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value,
|
||||
expected_value)`.
|
||||
|
||||
Built-in matchers (where `argument` is the function argument, e.g.
|
||||
`actual_value` in the example above, or when used in the context of
|
||||
`EXPECT_CALL(mock_object, method(matchers))`, the arguments of `method`) are
|
||||
divided into several categories. All matchers are defined in the `::testing`
|
||||
namespace unless otherwise noted.
|
||||
|
||||
## Wildcard
|
||||
|
||||
Matcher | Description
|
||||
:-------------------------- | :-----------------------------------------------
|
||||
`_` | `argument` can be any value of the correct type.
|
||||
`A<type>()` or `An<type>()` | `argument` can be any value of type `type`.
|
||||
|
||||
## Generic Comparison
|
||||
|
||||
| Matcher | Description |
|
||||
| :--------------------- | :-------------------------------------------------- |
|
||||
| `Eq(value)` or `value` | `argument == value` |
|
||||
| `Ge(value)` | `argument >= value` |
|
||||
| `Gt(value)` | `argument > value` |
|
||||
| `Le(value)` | `argument <= value` |
|
||||
| `Lt(value)` | `argument < value` |
|
||||
| `Ne(value)` | `argument != value` |
|
||||
| `IsFalse()` | `argument` evaluates to `false` in a Boolean context. |
|
||||
| `IsTrue()` | `argument` evaluates to `true` in a Boolean context. |
|
||||
| `IsNull()` | `argument` is a `NULL` pointer (raw or smart). |
|
||||
| `NotNull()` | `argument` is a non-null pointer (raw or smart). |
|
||||
| `Optional(m)` | `argument` is `optional<>` that contains a value matching `m`. (For testing whether an `optional<>` is set, check for equality with `nullopt`. You may need to use `Eq(nullopt)` if the inner type doesn't have `==`.)|
|
||||
| `VariantWith<T>(m)` | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. |
|
||||
| `Ref(variable)` | `argument` is a reference to `variable`. |
|
||||
| `TypedEq<type>(value)` | `argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded. |
|
||||
|
||||
Except `Ref()`, these matchers make a *copy* of `value` in case it's modified or
|
||||
destructed later. If the compiler complains that `value` doesn't have a public
|
||||
copy constructor, try wrap it in `std::ref()`, e.g.
|
||||
`Eq(std::ref(non_copyable_value))`. If you do that, make sure
|
||||
`non_copyable_value` is not changed afterwards, or the meaning of your matcher
|
||||
will be changed.
|
||||
|
||||
`IsTrue` and `IsFalse` are useful when you need to use a matcher, or for types
|
||||
that can be explicitly converted to Boolean, but are not implicitly converted to
|
||||
Boolean. In other cases, you can use the basic
|
||||
[`EXPECT_TRUE` and `EXPECT_FALSE`](assertions.md#boolean) assertions.
|
||||
|
||||
## Floating-Point Matchers {#FpMatchers}
|
||||
|
||||
| Matcher | Description |
|
||||
| :------------------------------- | :--------------------------------- |
|
||||
| `DoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal. |
|
||||
| `FloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. |
|
||||
| `NanSensitiveDoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. |
|
||||
| `NanSensitiveFloatEq(a_float)` | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. |
|
||||
| `IsNan()` | `argument` is any floating-point type with a NaN value. |
|
||||
|
||||
The above matchers use ULP-based comparison (the same as used in googletest).
|
||||
They automatically pick a reasonable error bound based on the absolute value of
|
||||
the expected value. `DoubleEq()` and `FloatEq()` conform to the IEEE standard,
|
||||
which requires comparing two NaNs for equality to return false. The
|
||||
`NanSensitive*` version instead treats two NaNs as equal, which is often what a
|
||||
user wants.
|
||||
|
||||
| Matcher | Description |
|
||||
| :------------------------------------------------ | :----------------------- |
|
||||
| `DoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal. |
|
||||
| `FloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. |
|
||||
| `NanSensitiveDoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. |
|
||||
| `NanSensitiveFloatNear(a_float, max_abs_error)` | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. |
|
||||
|
||||
## String Matchers
|
||||
|
||||
The `argument` can be either a C string or a C++ string object:
|
||||
|
||||
| Matcher | Description |
|
||||
| :---------------------- | :------------------------------------------------- |
|
||||
| `ContainsRegex(string)` | `argument` matches the given regular expression. |
|
||||
| `EndsWith(suffix)` | `argument` ends with string `suffix`. |
|
||||
| `HasSubstr(string)` | `argument` contains `string` as a sub-string. |
|
||||
| `IsEmpty()` | `argument` is an empty string. |
|
||||
| `MatchesRegex(string)` | `argument` matches the given regular expression with the match starting at the first character and ending at the last character. |
|
||||
| `StartsWith(prefix)` | `argument` starts with string `prefix`. |
|
||||
| `StrCaseEq(string)` | `argument` is equal to `string`, ignoring case. |
|
||||
| `StrCaseNe(string)` | `argument` is not equal to `string`, ignoring case. |
|
||||
| `StrEq(string)` | `argument` is equal to `string`. |
|
||||
| `StrNe(string)` | `argument` is not equal to `string`. |
|
||||
|
||||
`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They
|
||||
use the regular expression syntax defined
|
||||
[here](../advanced.md#regular-expression-syntax). All of these matchers, except
|
||||
`ContainsRegex()` and `MatchesRegex()` work for wide strings as well.
|
||||
|
||||
## Container Matchers
|
||||
|
||||
Most STL-style containers support `==`, so you can use `Eq(expected_container)`
|
||||
or simply `expected_container` to match a container exactly. If you want to
|
||||
write the elements in-line, match them more flexibly, or get more informative
|
||||
messages, you can use:
|
||||
|
||||
| Matcher | Description |
|
||||
| :---------------------------------------- | :------------------------------- |
|
||||
| `BeginEndDistanceIs(m)` | `argument` is a container whose `begin()` and `end()` iterators are separated by a number of increments matching `m`. E.g. `BeginEndDistanceIs(2)` or `BeginEndDistanceIs(Lt(2))`. For containers that define a `size()` method, `SizeIs(m)` may be more efficient. |
|
||||
| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. |
|
||||
| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. |
|
||||
| `Each(e)` | `argument` is a container where *every* element matches `e`, which can be either a value or a matcher. |
|
||||
| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the *i*-th element matches `ei`, which can be a value or a matcher. |
|
||||
| `ElementsAreArray({e0, e1, ..., en})`, `ElementsAreArray(a_container)`, `ElementsAreArray(begin, end)`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. |
|
||||
| `IsEmpty()` | `argument` is an empty container (`container.empty()`). |
|
||||
| `IsSubsetOf({e0, e1, ..., en})`, `IsSubsetOf(a_container)`, `IsSubsetOf(begin, end)`, `IsSubsetOf(array)`, or `IsSubsetOf(array, count)` | `argument` matches `UnorderedElementsAre(x0, x1, ..., xk)` for some subset `{x0, x1, ..., xk}` of the expected matchers. |
|
||||
| `IsSupersetOf({e0, e1, ..., en})`, `IsSupersetOf(a_container)`, `IsSupersetOf(begin, end)`, `IsSupersetOf(array)`, or `IsSupersetOf(array, count)` | Some subset of `argument` matches `UnorderedElementsAre(`expected matchers`)`. |
|
||||
| `Pointwise(m, container)`, `Pointwise(m, {e0, e1, ..., en})` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. |
|
||||
| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. |
|
||||
| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under *some* permutation of the elements, each element matches an `ei` (for a different `i`), which can be a value or a matcher. |
|
||||
| `UnorderedElementsAreArray({e0, e1, ..., en})`, `UnorderedElementsAreArray(a_container)`, `UnorderedElementsAreArray(begin, end)`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. |
|
||||
| `UnorderedPointwise(m, container)`, `UnorderedPointwise(m, {e0, e1, ..., en})` | Like `Pointwise(m, container)`, but ignores the order of elements. |
|
||||
| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(ElementsAre(1, 2, 3))` verifies that `argument` contains elements 1, 2, and 3, ignoring order. |
|
||||
| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater(), ElementsAre(3, 2, 1))`. |
|
||||
|
||||
**Notes:**
|
||||
|
||||
* These matchers can also match:
|
||||
1. a native array passed by reference (e.g. in `Foo(const int (&a)[5])`),
|
||||
and
|
||||
2. an array passed as a pointer and a count (e.g. in `Bar(const T* buffer,
|
||||
int len)` -- see [Multi-argument Matchers](#MultiArgMatchers)).
|
||||
* The array being matched may be multi-dimensional (i.e. its elements can be
|
||||
arrays).
|
||||
* `m` in `Pointwise(m, ...)` and `UnorderedPointwise(m, ...)` should be a
|
||||
matcher for `::std::tuple<T, U>` where `T` and `U` are the element type of
|
||||
the actual container and the expected container, respectively. For example,
|
||||
to compare two `Foo` containers where `Foo` doesn't support `operator==`,
|
||||
one might write:
|
||||
|
||||
```cpp
|
||||
using ::std::get;
|
||||
MATCHER(FooEq, "") {
|
||||
return std::get<0>(arg).Equals(std::get<1>(arg));
|
||||
}
|
||||
...
|
||||
EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos));
|
||||
```
|
||||
|
||||
## Member Matchers
|
||||
|
||||
| Matcher | Description |
|
||||
| :------------------------------ | :----------------------------------------- |
|
||||
| `Field(&class::field, m)` | `argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. |
|
||||
| `Field(field_name, &class::field, m)` | The same as the two-parameter version, but provides a better error message. |
|
||||
| `Key(e)` | `argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`. |
|
||||
| `Pair(m1, m2)` | `argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. |
|
||||
| `FieldsAre(m...)` | `argument` is a compatible object where each field matches piecewise with the matchers `m...`. A compatible object is any that supports the `std::tuple_size<Obj>`+`get<I>(obj)` protocol. In C++17 and up this also supports types compatible with structured bindings, like aggregates. |
|
||||
| `Property(&class::property, m)` | `argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. The method `property()` must take no argument and be declared as `const`. |
|
||||
| `Property(property_name, &class::property, m)` | The same as the two-parameter version, but provides a better error message.
|
||||
|
||||
**Notes:**
|
||||
|
||||
* You can use `FieldsAre()` to match any type that supports structured
|
||||
bindings, such as `std::tuple`, `std::pair`, `std::array`, and aggregate
|
||||
types. For example:
|
||||
|
||||
```cpp
|
||||
std::tuple<int, std::string> my_tuple{7, "hello world"};
|
||||
EXPECT_THAT(my_tuple, FieldsAre(Ge(0), HasSubstr("hello")));
|
||||
|
||||
struct MyStruct {
|
||||
int value = 42;
|
||||
std::string greeting = "aloha";
|
||||
};
|
||||
MyStruct s;
|
||||
EXPECT_THAT(s, FieldsAre(42, "aloha"));
|
||||
```
|
||||
|
||||
* Don't use `Property()` against member functions that you do not own, because
|
||||
taking addresses of functions is fragile and generally not part of the
|
||||
contract of the function.
|
||||
|
||||
## Matching the Result of a Function, Functor, or Callback
|
||||
|
||||
| Matcher | Description |
|
||||
| :--------------- | :------------------------------------------------ |
|
||||
| `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. |
|
||||
|
||||
## Pointer Matchers
|
||||
|
||||
| Matcher | Description |
|
||||
| :------------------------ | :---------------------------------------------- |
|
||||
| `Address(m)` | the result of `std::addressof(argument)` matches `m`. |
|
||||
| `Pointee(m)` | `argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`. |
|
||||
| `Pointer(m)` | `argument` (either a smart pointer or a raw pointer) contains a pointer that matches `m`. `m` will match against the raw pointer regardless of the type of `argument`. |
|
||||
| `WhenDynamicCastTo<T>(m)` | when `argument` is passed through `dynamic_cast<T>()`, it matches matcher `m`. |
|
||||
|
||||
## Multi-argument Matchers {#MultiArgMatchers}
|
||||
|
||||
Technically, all matchers match a *single* value. A "multi-argument" matcher is
|
||||
just one that matches a *tuple*. The following matchers can be used to match a
|
||||
tuple `(x, y)`:
|
||||
|
||||
Matcher | Description
|
||||
:------ | :----------
|
||||
`Eq()` | `x == y`
|
||||
`Ge()` | `x >= y`
|
||||
`Gt()` | `x > y`
|
||||
`Le()` | `x <= y`
|
||||
`Lt()` | `x < y`
|
||||
`Ne()` | `x != y`
|
||||
|
||||
You can use the following selectors to pick a subset of the arguments (or
|
||||
reorder them) to participate in the matching:
|
||||
|
||||
| Matcher | Description |
|
||||
| :------------------------- | :---------------------------------------------- |
|
||||
| `AllArgs(m)` | Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`. |
|
||||
| `Args<N1, N2, ..., Nk>(m)` | The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`. |
|
||||
|
||||
## Composite Matchers
|
||||
|
||||
You can make a matcher from one or more other matchers:
|
||||
|
||||
| Matcher | Description |
|
||||
| :------------------------------- | :-------------------------------------- |
|
||||
| `AllOf(m1, m2, ..., mn)` | `argument` matches all of the matchers `m1` to `mn`. |
|
||||
| `AllOfArray({m0, m1, ..., mn})`, `AllOfArray(a_container)`, `AllOfArray(begin, end)`, `AllOfArray(array)`, or `AllOfArray(array, count)` | The same as `AllOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. |
|
||||
| `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers `m1` to `mn`. |
|
||||
| `AnyOfArray({m0, m1, ..., mn})`, `AnyOfArray(a_container)`, `AnyOfArray(begin, end)`, `AnyOfArray(array)`, or `AnyOfArray(array, count)` | The same as `AnyOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. |
|
||||
| `Not(m)` | `argument` doesn't match matcher `m`. |
|
||||
|
||||
## Adapters for Matchers
|
||||
|
||||
| Matcher | Description |
|
||||
| :---------------------- | :------------------------------------ |
|
||||
| `MatcherCast<T>(m)` | casts matcher `m` to type `Matcher<T>`. |
|
||||
| `SafeMatcherCast<T>(m)` | [safely casts](../gmock_cook_book.md#SafeMatcherCast) matcher `m` to type `Matcher<T>`. |
|
||||
| `Truly(predicate)` | `predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor. |
|
||||
|
||||
`AddressSatisfies(callback)` and `Truly(callback)` take ownership of `callback`,
|
||||
which must be a permanent callback.
|
||||
|
||||
## Using Matchers as Predicates {#MatchersAsPredicatesCheat}
|
||||
|
||||
| Matcher | Description |
|
||||
| :---------------------------- | :------------------------------------------ |
|
||||
| `Matches(m)(value)` | evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor. |
|
||||
| `ExplainMatchResult(m, value, result_listener)` | evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. |
|
||||
| `Value(value, m)` | evaluates to `true` if `value` matches `m`. |
|
||||
|
||||
## Defining Matchers
|
||||
|
||||
| Matcher | Description |
|
||||
| :----------------------------------- | :------------------------------------ |
|
||||
| `MATCHER(IsEven, "") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. |
|
||||
| `MATCHER_P(IsDivisibleBy, n, "") { *result_listener << "where the remainder is " << (arg % n); return (arg % n) == 0; }` | Defines a matcher `IsDivisibleBy(n)` to match a number divisible by `n`. |
|
||||
| `MATCHER_P2(IsBetween, a, b, absl::StrCat(negation ? "isn't" : "is", " between ", PrintToString(a), " and ", PrintToString(b))) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. |
|
||||
|
||||
**Notes:**
|
||||
|
||||
1. The `MATCHER*` macros cannot be used inside a function or class.
|
||||
2. The matcher body must be *purely functional* (i.e. it cannot have any side
|
||||
effect, and the result must not depend on anything other than the value
|
||||
being matched and the matcher parameters).
|
||||
3. You can use `PrintToString(x)` to convert a value `x` of any type to a
|
||||
string.
|
||||
4. You can use `ExplainMatchResult()` in a custom matcher to wrap another
|
||||
matcher, for example:
|
||||
|
||||
```cpp
|
||||
MATCHER_P(NestedPropertyMatches, matcher, "") {
|
||||
return ExplainMatchResult(matcher, arg.nested().property(), result_listener);
|
||||
}
|
||||
```
|
||||
@ -0,0 +1,587 @@
|
||||
# Mocking Reference
|
||||
|
||||
This page lists the facilities provided by GoogleTest for creating and working
|
||||
with mock objects. To use them, include the header
|
||||
`gmock/gmock.h`.
|
||||
|
||||
## Macros {#macros}
|
||||
|
||||
GoogleTest defines the following macros for working with mocks.
|
||||
|
||||
### MOCK_METHOD {#MOCK_METHOD}
|
||||
|
||||
`MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`));` \
|
||||
`MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`),
|
||||
(`*`specs...`*`));`
|
||||
|
||||
Defines a mock method *`method_name`* with arguments `(`*`args...`*`)` and
|
||||
return type *`return_type`* within a mock class.
|
||||
|
||||
The parameters of `MOCK_METHOD` mirror the method declaration. The optional
|
||||
fourth parameter *`specs...`* is a comma-separated list of qualifiers. The
|
||||
following qualifiers are accepted:
|
||||
|
||||
| Qualifier | Meaning |
|
||||
| -------------------------- | -------------------------------------------- |
|
||||
| `const` | Makes the mocked method a `const` method. Required if overriding a `const` method. |
|
||||
| `override` | Marks the method with `override`. Recommended if overriding a `virtual` method. |
|
||||
| `noexcept` | Marks the method with `noexcept`. Required if overriding a `noexcept` method. |
|
||||
| `Calltype(`*`calltype`*`)` | Sets the call type for the method, for example `Calltype(STDMETHODCALLTYPE)`. Useful on Windows. |
|
||||
| `ref(`*`qualifier`*`)` | Marks the method with the given reference qualifier, for example `ref(&)` or `ref(&&)`. Required if overriding a method that has a reference qualifier. |
|
||||
|
||||
Note that commas in arguments prevent `MOCK_METHOD` from parsing the arguments
|
||||
correctly if they are not appropriately surrounded by parentheses. See the
|
||||
following example:
|
||||
|
||||
```cpp
|
||||
class MyMock {
|
||||
public:
|
||||
// The following 2 lines will not compile due to commas in the arguments:
|
||||
MOCK_METHOD(std::pair<bool, int>, GetPair, ()); // Error!
|
||||
MOCK_METHOD(bool, CheckMap, (std::map<int, double>, bool)); // Error!
|
||||
|
||||
// One solution - wrap arguments that contain commas in parentheses:
|
||||
MOCK_METHOD((std::pair<bool, int>), GetPair, ());
|
||||
MOCK_METHOD(bool, CheckMap, ((std::map<int, double>), bool));
|
||||
|
||||
// Another solution - use type aliases:
|
||||
using BoolAndInt = std::pair<bool, int>;
|
||||
MOCK_METHOD(BoolAndInt, GetPair, ());
|
||||
using MapIntDouble = std::map<int, double>;
|
||||
MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool));
|
||||
};
|
||||
```
|
||||
|
||||
`MOCK_METHOD` must be used in the `public:` section of a mock class definition,
|
||||
regardless of whether the method being mocked is `public`, `protected`, or
|
||||
`private` in the base class.
|
||||
|
||||
### EXPECT_CALL {#EXPECT_CALL}
|
||||
|
||||
`EXPECT_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))`
|
||||
|
||||
Creates an [expectation](../gmock_for_dummies.md#setting-expectations) that the
|
||||
method *`method_name`* of the object *`mock_object`* is called with arguments
|
||||
that match the given matchers *`matchers...`*. `EXPECT_CALL` must precede any
|
||||
code that exercises the mock object.
|
||||
|
||||
The parameter *`matchers...`* is a comma-separated list of
|
||||
[matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that
|
||||
correspond to each argument of the method *`method_name`*. The expectation will
|
||||
apply only to calls of *`method_name`* whose arguments match all of the
|
||||
matchers. If `(`*`matchers...`*`)` is omitted, the expectation behaves as if
|
||||
each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard).
|
||||
See the [Matchers Reference](matchers.md) for a list of all built-in matchers.
|
||||
|
||||
The following chainable clauses can be used to modify the expectation, and they
|
||||
must be used in the following order:
|
||||
|
||||
```cpp
|
||||
EXPECT_CALL(mock_object, method_name(matchers...))
|
||||
.With(multi_argument_matcher) // Can be used at most once
|
||||
.Times(cardinality) // Can be used at most once
|
||||
.InSequence(sequences...) // Can be used any number of times
|
||||
.After(expectations...) // Can be used any number of times
|
||||
.WillOnce(action) // Can be used any number of times
|
||||
.WillRepeatedly(action) // Can be used at most once
|
||||
.RetiresOnSaturation(); // Can be used at most once
|
||||
```
|
||||
|
||||
See details for each modifier clause below.
|
||||
|
||||
#### With {#EXPECT_CALL.With}
|
||||
|
||||
`.With(`*`multi_argument_matcher`*`)`
|
||||
|
||||
Restricts the expectation to apply only to mock function calls whose arguments
|
||||
as a whole match the multi-argument matcher *`multi_argument_matcher`*.
|
||||
|
||||
GoogleTest passes all of the arguments as one tuple into the matcher. The
|
||||
parameter *`multi_argument_matcher`* must thus be a matcher of type
|
||||
`Matcher<std::tuple<A1, ..., An>>`, where `A1, ..., An` are the types of the
|
||||
function arguments.
|
||||
|
||||
For example, the following code sets the expectation that
|
||||
`my_mock.SetPosition()` is called with any two arguments, the first argument
|
||||
being less than the second:
|
||||
|
||||
```cpp
|
||||
using ::testing::_;
|
||||
using ::testing::Lt;
|
||||
...
|
||||
EXPECT_CALL(my_mock, SetPosition(_, _))
|
||||
.With(Lt());
|
||||
```
|
||||
|
||||
GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()`
|
||||
matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers).
|
||||
|
||||
The `With` clause can be used at most once on an expectation and must be the
|
||||
first clause.
|
||||
|
||||
#### Times {#EXPECT_CALL.Times}
|
||||
|
||||
`.Times(`*`cardinality`*`)`
|
||||
|
||||
Specifies how many times the mock function call is expected.
|
||||
|
||||
The parameter *`cardinality`* represents the number of expected calls and can be
|
||||
one of the following, all defined in the `::testing` namespace:
|
||||
|
||||
| Cardinality | Meaning |
|
||||
| ------------------- | --------------------------------------------------- |
|
||||
| `AnyNumber()` | The function can be called any number of times. |
|
||||
| `AtLeast(n)` | The function call is expected at least *n* times. |
|
||||
| `AtMost(n)` | The function call is expected at most *n* times. |
|
||||
| `Between(m, n)` | The function call is expected between *m* and *n* times, inclusive. |
|
||||
| `Exactly(n)` or `n` | The function call is expected exactly *n* times. If *n* is 0, the call should never happen. |
|
||||
|
||||
If the `Times` clause is omitted, GoogleTest infers the cardinality as follows:
|
||||
|
||||
* If neither [`WillOnce`](#EXPECT_CALL.WillOnce) nor
|
||||
[`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) are specified, the inferred
|
||||
cardinality is `Times(1)`.
|
||||
* If there are *n* `WillOnce` clauses and no `WillRepeatedly` clause, where
|
||||
*n* >= 1, the inferred cardinality is `Times(n)`.
|
||||
* If there are *n* `WillOnce` clauses and one `WillRepeatedly` clause, where
|
||||
*n* >= 0, the inferred cardinality is `Times(AtLeast(n))`.
|
||||
|
||||
The `Times` clause can be used at most once on an expectation.
|
||||
|
||||
#### InSequence {#EXPECT_CALL.InSequence}
|
||||
|
||||
`.InSequence(`*`sequences...`*`)`
|
||||
|
||||
Specifies that the mock function call is expected in a certain sequence.
|
||||
|
||||
The parameter *`sequences...`* is any number of [`Sequence`](#Sequence) objects.
|
||||
Expected calls assigned to the same sequence are expected to occur in the order
|
||||
the expectations are declared.
|
||||
|
||||
For example, the following code sets the expectation that the `Reset()` method
|
||||
of `my_mock` is called before both `GetSize()` and `Describe()`, and `GetSize()`
|
||||
and `Describe()` can occur in any order relative to each other:
|
||||
|
||||
```cpp
|
||||
using ::testing::Sequence;
|
||||
Sequence s1, s2;
|
||||
...
|
||||
EXPECT_CALL(my_mock, Reset())
|
||||
.InSequence(s1, s2);
|
||||
EXPECT_CALL(my_mock, GetSize())
|
||||
.InSequence(s1);
|
||||
EXPECT_CALL(my_mock, Describe())
|
||||
.InSequence(s2);
|
||||
```
|
||||
|
||||
The `InSequence` clause can be used any number of times on an expectation.
|
||||
|
||||
See also the [`InSequence` class](#InSequence).
|
||||
|
||||
#### After {#EXPECT_CALL.After}
|
||||
|
||||
`.After(`*`expectations...`*`)`
|
||||
|
||||
Specifies that the mock function call is expected to occur after one or more
|
||||
other calls.
|
||||
|
||||
The parameter *`expectations...`* can be up to five
|
||||
[`Expectation`](#Expectation) or [`ExpectationSet`](#ExpectationSet) objects.
|
||||
The mock function call is expected to occur after all of the given expectations.
|
||||
|
||||
For example, the following code sets the expectation that the `Describe()`
|
||||
method of `my_mock` is called only after both `InitX()` and `InitY()` have been
|
||||
called.
|
||||
|
||||
```cpp
|
||||
using ::testing::Expectation;
|
||||
...
|
||||
Expectation init_x = EXPECT_CALL(my_mock, InitX());
|
||||
Expectation init_y = EXPECT_CALL(my_mock, InitY());
|
||||
EXPECT_CALL(my_mock, Describe())
|
||||
.After(init_x, init_y);
|
||||
```
|
||||
|
||||
The `ExpectationSet` object is helpful when the number of prerequisites for an
|
||||
expectation is large or variable, for example:
|
||||
|
||||
```cpp
|
||||
using ::testing::ExpectationSet;
|
||||
...
|
||||
ExpectationSet all_inits;
|
||||
// Collect all expectations of InitElement() calls
|
||||
for (int i = 0; i < element_count; i++) {
|
||||
all_inits += EXPECT_CALL(my_mock, InitElement(i));
|
||||
}
|
||||
EXPECT_CALL(my_mock, Describe())
|
||||
.After(all_inits); // Expect Describe() call after all InitElement() calls
|
||||
```
|
||||
|
||||
The `After` clause can be used any number of times on an expectation.
|
||||
|
||||
#### WillOnce {#EXPECT_CALL.WillOnce}
|
||||
|
||||
`.WillOnce(`*`action`*`)`
|
||||
|
||||
Specifies the mock function's actual behavior when invoked, for a single
|
||||
matching function call.
|
||||
|
||||
The parameter *`action`* represents the
|
||||
[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function
|
||||
call will perform. See the [Actions Reference](actions.md) for a list of
|
||||
built-in actions.
|
||||
|
||||
The use of `WillOnce` implicitly sets a cardinality on the expectation when
|
||||
`Times` is not specified. See [`Times`](#EXPECT_CALL.Times).
|
||||
|
||||
Each matching function call will perform the next action in the order declared.
|
||||
For example, the following code specifies that `my_mock.GetNumber()` is expected
|
||||
to be called exactly 3 times and will return `1`, `2`, and `3` respectively on
|
||||
the first, second, and third calls:
|
||||
|
||||
```cpp
|
||||
using ::testing::Return;
|
||||
...
|
||||
EXPECT_CALL(my_mock, GetNumber())
|
||||
.WillOnce(Return(1))
|
||||
.WillOnce(Return(2))
|
||||
.WillOnce(Return(3));
|
||||
```
|
||||
|
||||
The `WillOnce` clause can be used any number of times on an expectation.
|
||||
|
||||
#### WillRepeatedly {#EXPECT_CALL.WillRepeatedly}
|
||||
|
||||
`.WillRepeatedly(`*`action`*`)`
|
||||
|
||||
Specifies the mock function's actual behavior when invoked, for all subsequent
|
||||
matching function calls. Takes effect after the actions specified in the
|
||||
[`WillOnce`](#EXPECT_CALL.WillOnce) clauses, if any, have been performed.
|
||||
|
||||
The parameter *`action`* represents the
|
||||
[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function
|
||||
call will perform. See the [Actions Reference](actions.md) for a list of
|
||||
built-in actions.
|
||||
|
||||
The use of `WillRepeatedly` implicitly sets a cardinality on the expectation
|
||||
when `Times` is not specified. See [`Times`](#EXPECT_CALL.Times).
|
||||
|
||||
If any `WillOnce` clauses have been specified, matching function calls will
|
||||
perform those actions before the action specified by `WillRepeatedly`. See the
|
||||
following example:
|
||||
|
||||
```cpp
|
||||
using ::testing::Return;
|
||||
...
|
||||
EXPECT_CALL(my_mock, GetName())
|
||||
.WillRepeatedly(Return("John Doe")); // Return "John Doe" on all calls
|
||||
|
||||
EXPECT_CALL(my_mock, GetNumber())
|
||||
.WillOnce(Return(42)) // Return 42 on the first call
|
||||
.WillRepeatedly(Return(7)); // Return 7 on all subsequent calls
|
||||
```
|
||||
|
||||
The `WillRepeatedly` clause can be used at most once on an expectation.
|
||||
|
||||
#### RetiresOnSaturation {#EXPECT_CALL.RetiresOnSaturation}
|
||||
|
||||
`.RetiresOnSaturation()`
|
||||
|
||||
Indicates that the expectation will no longer be active after the expected
|
||||
number of matching function calls has been reached.
|
||||
|
||||
The `RetiresOnSaturation` clause is only meaningful for expectations with an
|
||||
upper-bounded cardinality. The expectation will *retire* (no longer match any
|
||||
function calls) after it has been *saturated* (the upper bound has been
|
||||
reached). See the following example:
|
||||
|
||||
```cpp
|
||||
using ::testing::_;
|
||||
using ::testing::AnyNumber;
|
||||
...
|
||||
EXPECT_CALL(my_mock, SetNumber(_)) // Expectation 1
|
||||
.Times(AnyNumber());
|
||||
EXPECT_CALL(my_mock, SetNumber(7)) // Expectation 2
|
||||
.Times(2)
|
||||
.RetiresOnSaturation();
|
||||
```
|
||||
|
||||
In the above example, the first two calls to `my_mock.SetNumber(7)` match
|
||||
expectation 2, which then becomes inactive and no longer matches any calls. A
|
||||
third call to `my_mock.SetNumber(7)` would then match expectation 1. Without
|
||||
`RetiresOnSaturation()` on expectation 2, a third call to `my_mock.SetNumber(7)`
|
||||
would match expectation 2 again, producing a failure since the limit of 2 calls
|
||||
was exceeded.
|
||||
|
||||
The `RetiresOnSaturation` clause can be used at most once on an expectation and
|
||||
must be the last clause.
|
||||
|
||||
### ON_CALL {#ON_CALL}
|
||||
|
||||
`ON_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))`
|
||||
|
||||
Defines what happens when the method *`method_name`* of the object
|
||||
*`mock_object`* is called with arguments that match the given matchers
|
||||
*`matchers...`*. Requires a modifier clause to specify the method's behavior.
|
||||
*Does not* set any expectations that the method will be called.
|
||||
|
||||
The parameter *`matchers...`* is a comma-separated list of
|
||||
[matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that
|
||||
correspond to each argument of the method *`method_name`*. The `ON_CALL`
|
||||
specification will apply only to calls of *`method_name`* whose arguments match
|
||||
all of the matchers. If `(`*`matchers...`*`)` is omitted, the behavior is as if
|
||||
each argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard).
|
||||
See the [Matchers Reference](matchers.md) for a list of all built-in matchers.
|
||||
|
||||
The following chainable clauses can be used to set the method's behavior, and
|
||||
they must be used in the following order:
|
||||
|
||||
```cpp
|
||||
ON_CALL(mock_object, method_name(matchers...))
|
||||
.With(multi_argument_matcher) // Can be used at most once
|
||||
.WillByDefault(action); // Required
|
||||
```
|
||||
|
||||
See details for each modifier clause below.
|
||||
|
||||
#### With {#ON_CALL.With}
|
||||
|
||||
`.With(`*`multi_argument_matcher`*`)`
|
||||
|
||||
Restricts the specification to only mock function calls whose arguments as a
|
||||
whole match the multi-argument matcher *`multi_argument_matcher`*.
|
||||
|
||||
GoogleTest passes all of the arguments as one tuple into the matcher. The
|
||||
parameter *`multi_argument_matcher`* must thus be a matcher of type
|
||||
`Matcher<std::tuple<A1, ..., An>>`, where `A1, ..., An` are the types of the
|
||||
function arguments.
|
||||
|
||||
For example, the following code sets the default behavior when
|
||||
`my_mock.SetPosition()` is called with any two arguments, the first argument
|
||||
being less than the second:
|
||||
|
||||
```cpp
|
||||
using ::testing::_;
|
||||
using ::testing::Lt;
|
||||
using ::testing::Return;
|
||||
...
|
||||
ON_CALL(my_mock, SetPosition(_, _))
|
||||
.With(Lt())
|
||||
.WillByDefault(Return(true));
|
||||
```
|
||||
|
||||
GoogleTest provides some built-in matchers for 2-tuples, including the `Lt()`
|
||||
matcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers).
|
||||
|
||||
The `With` clause can be used at most once with each `ON_CALL` statement.
|
||||
|
||||
#### WillByDefault {#ON_CALL.WillByDefault}
|
||||
|
||||
`.WillByDefault(`*`action`*`)`
|
||||
|
||||
Specifies the default behavior of a matching mock function call.
|
||||
|
||||
The parameter *`action`* represents the
|
||||
[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function
|
||||
call will perform. See the [Actions Reference](actions.md) for a list of
|
||||
built-in actions.
|
||||
|
||||
For example, the following code specifies that by default, a call to
|
||||
`my_mock.Greet()` will return `"hello"`:
|
||||
|
||||
```cpp
|
||||
using ::testing::Return;
|
||||
...
|
||||
ON_CALL(my_mock, Greet())
|
||||
.WillByDefault(Return("hello"));
|
||||
```
|
||||
|
||||
The action specified by `WillByDefault` is superseded by the actions specified
|
||||
on a matching `EXPECT_CALL` statement, if any. See the
|
||||
[`WillOnce`](#EXPECT_CALL.WillOnce) and
|
||||
[`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) clauses of `EXPECT_CALL`.
|
||||
|
||||
The `WillByDefault` clause must be used exactly once with each `ON_CALL`
|
||||
statement.
|
||||
|
||||
## Classes {#classes}
|
||||
|
||||
GoogleTest defines the following classes for working with mocks.
|
||||
|
||||
### DefaultValue {#DefaultValue}
|
||||
|
||||
`::testing::DefaultValue<T>`
|
||||
|
||||
Allows a user to specify the default value for a type `T` that is both copyable
|
||||
and publicly destructible (i.e. anything that can be used as a function return
|
||||
type). For mock functions with a return type of `T`, this default value is
|
||||
returned from function calls that do not specify an action.
|
||||
|
||||
Provides the static methods `Set()`, `SetFactory()`, and `Clear()` to manage the
|
||||
default value:
|
||||
|
||||
```cpp
|
||||
// Sets the default value to be returned. T must be copy constructible.
|
||||
DefaultValue<T>::Set(value);
|
||||
|
||||
// Sets a factory. Will be invoked on demand. T must be move constructible.
|
||||
T MakeT();
|
||||
DefaultValue<T>::SetFactory(&MakeT);
|
||||
|
||||
// Unsets the default value.
|
||||
DefaultValue<T>::Clear();
|
||||
```
|
||||
|
||||
### NiceMock {#NiceMock}
|
||||
|
||||
`::testing::NiceMock<T>`
|
||||
|
||||
Represents a mock object that suppresses warnings on
|
||||
[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The
|
||||
template parameter `T` is any mock class, except for another `NiceMock`,
|
||||
`NaggyMock`, or `StrictMock`.
|
||||
|
||||
Usage of `NiceMock<T>` is analogous to usage of `T`. `NiceMock<T>` is a subclass
|
||||
of `T`, so it can be used wherever an object of type `T` is accepted. In
|
||||
addition, `NiceMock<T>` can be constructed with any arguments that a constructor
|
||||
of `T` accepts.
|
||||
|
||||
For example, the following code suppresses warnings on the mock `my_mock` of
|
||||
type `MockClass` if a method other than `DoSomething()` is called:
|
||||
|
||||
```cpp
|
||||
using ::testing::NiceMock;
|
||||
...
|
||||
NiceMock<MockClass> my_mock("some", "args");
|
||||
EXPECT_CALL(my_mock, DoSomething());
|
||||
... code that uses my_mock ...
|
||||
```
|
||||
|
||||
`NiceMock<T>` only works for mock methods defined using the `MOCK_METHOD` macro
|
||||
directly in the definition of class `T`. If a mock method is defined in a base
|
||||
class of `T`, a warning might still be generated.
|
||||
|
||||
`NiceMock<T>` might not work correctly if the destructor of `T` is not virtual.
|
||||
|
||||
### NaggyMock {#NaggyMock}
|
||||
|
||||
`::testing::NaggyMock<T>`
|
||||
|
||||
Represents a mock object that generates warnings on
|
||||
[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The
|
||||
template parameter `T` is any mock class, except for another `NiceMock`,
|
||||
`NaggyMock`, or `StrictMock`.
|
||||
|
||||
Usage of `NaggyMock<T>` is analogous to usage of `T`. `NaggyMock<T>` is a
|
||||
subclass of `T`, so it can be used wherever an object of type `T` is accepted.
|
||||
In addition, `NaggyMock<T>` can be constructed with any arguments that a
|
||||
constructor of `T` accepts.
|
||||
|
||||
For example, the following code generates warnings on the mock `my_mock` of type
|
||||
`MockClass` if a method other than `DoSomething()` is called:
|
||||
|
||||
```cpp
|
||||
using ::testing::NaggyMock;
|
||||
...
|
||||
NaggyMock<MockClass> my_mock("some", "args");
|
||||
EXPECT_CALL(my_mock, DoSomething());
|
||||
... code that uses my_mock ...
|
||||
```
|
||||
|
||||
Mock objects of type `T` by default behave the same way as `NaggyMock<T>`.
|
||||
|
||||
### StrictMock {#StrictMock}
|
||||
|
||||
`::testing::StrictMock<T>`
|
||||
|
||||
Represents a mock object that generates test failures on
|
||||
[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The
|
||||
template parameter `T` is any mock class, except for another `NiceMock`,
|
||||
`NaggyMock`, or `StrictMock`.
|
||||
|
||||
Usage of `StrictMock<T>` is analogous to usage of `T`. `StrictMock<T>` is a
|
||||
subclass of `T`, so it can be used wherever an object of type `T` is accepted.
|
||||
In addition, `StrictMock<T>` can be constructed with any arguments that a
|
||||
constructor of `T` accepts.
|
||||
|
||||
For example, the following code generates a test failure on the mock `my_mock`
|
||||
of type `MockClass` if a method other than `DoSomething()` is called:
|
||||
|
||||
```cpp
|
||||
using ::testing::StrictMock;
|
||||
...
|
||||
StrictMock<MockClass> my_mock("some", "args");
|
||||
EXPECT_CALL(my_mock, DoSomething());
|
||||
... code that uses my_mock ...
|
||||
```
|
||||
|
||||
`StrictMock<T>` only works for mock methods defined using the `MOCK_METHOD`
|
||||
macro directly in the definition of class `T`. If a mock method is defined in a
|
||||
base class of `T`, a failure might not be generated.
|
||||
|
||||
`StrictMock<T>` might not work correctly if the destructor of `T` is not
|
||||
virtual.
|
||||
|
||||
### Sequence {#Sequence}
|
||||
|
||||
`::testing::Sequence`
|
||||
|
||||
Represents a chronological sequence of expectations. See the
|
||||
[`InSequence`](#EXPECT_CALL.InSequence) clause of `EXPECT_CALL` for usage.
|
||||
|
||||
### InSequence {#InSequence}
|
||||
|
||||
`::testing::InSequence`
|
||||
|
||||
An object of this type causes all expectations encountered in its scope to be
|
||||
put in an anonymous sequence.
|
||||
|
||||
This allows more convenient expression of multiple expectations in a single
|
||||
sequence:
|
||||
|
||||
```cpp
|
||||
using ::testing::InSequence;
|
||||
{
|
||||
InSequence seq;
|
||||
|
||||
// The following are expected to occur in the order declared.
|
||||
EXPECT_CALL(...);
|
||||
EXPECT_CALL(...);
|
||||
...
|
||||
EXPECT_CALL(...);
|
||||
}
|
||||
```
|
||||
|
||||
The name of the `InSequence` object does not matter.
|
||||
|
||||
### Expectation {#Expectation}
|
||||
|
||||
`::testing::Expectation`
|
||||
|
||||
Represents a mock function call expectation as created by
|
||||
[`EXPECT_CALL`](#EXPECT_CALL):
|
||||
|
||||
```cpp
|
||||
using ::testing::Expectation;
|
||||
Expectation my_expectation = EXPECT_CALL(...);
|
||||
```
|
||||
|
||||
Useful for specifying sequences of expectations; see the
|
||||
[`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`.
|
||||
|
||||
### ExpectationSet {#ExpectationSet}
|
||||
|
||||
`::testing::ExpectationSet`
|
||||
|
||||
Represents a set of mock function call expectations.
|
||||
|
||||
Use the `+=` operator to add [`Expectation`](#Expectation) objects to the set:
|
||||
|
||||
```cpp
|
||||
using ::testing::ExpectationSet;
|
||||
ExpectationSet my_expectations;
|
||||
my_expectations += EXPECT_CALL(...);
|
||||
```
|
||||
|
||||
Useful for specifying sequences of expectations; see the
|
||||
[`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`.
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,22 @@
|
||||
# Googletest Samples
|
||||
|
||||
If you're like us, you'd like to look at
|
||||
[googletest samples.](https://github.com/google/googletest/tree/master/googletest/samples)
|
||||
The sample directory has a number of well-commented samples showing how to use a
|
||||
variety of googletest features.
|
||||
|
||||
* Sample #1 shows the basic steps of using googletest to test C++ functions.
|
||||
* Sample #2 shows a more complex unit test for a class with multiple member
|
||||
functions.
|
||||
* Sample #3 uses a test fixture.
|
||||
* Sample #4 teaches you how to use googletest and `googletest.h` together to
|
||||
get the best of both libraries.
|
||||
* Sample #5 puts shared testing logic in a base test fixture, and reuses it in
|
||||
derived fixtures.
|
||||
* Sample #6 demonstrates type-parameterized tests.
|
||||
* Sample #7 teaches the basics of value-parameterized tests.
|
||||
* Sample #8 shows using `Combine()` in value-parameterized tests.
|
||||
* Sample #9 shows use of the listener API to modify Google Test's console
|
||||
output and the use of its reflection API to inspect test results.
|
||||
* Sample #10 shows use of the listener API to implement a primitive memory
|
||||
leak checker.
|
||||
@ -0,0 +1,218 @@
|
||||
########################################################################
|
||||
# Note: CMake support is community-based. The maintainers do not use CMake
|
||||
# internally.
|
||||
#
|
||||
# CMake build script for Google Mock.
|
||||
#
|
||||
# To run the tests for Google Mock itself on Linux, use 'make test' or
|
||||
# ctest. You can select which tests to run using 'ctest -R regex'.
|
||||
# For more options, run 'ctest --help'.
|
||||
|
||||
option(gmock_build_tests "Build all of Google Mock's own tests." OFF)
|
||||
|
||||
# A directory to find Google Test sources.
|
||||
if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/gtest/CMakeLists.txt")
|
||||
set(gtest_dir gtest)
|
||||
else()
|
||||
set(gtest_dir ../googletest)
|
||||
endif()
|
||||
|
||||
# Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build().
|
||||
include("${gtest_dir}/cmake/hermetic_build.cmake" OPTIONAL)
|
||||
|
||||
if (COMMAND pre_project_set_up_hermetic_build)
|
||||
# Google Test also calls hermetic setup functions from add_subdirectory,
|
||||
# although its changes will not affect things at the current scope.
|
||||
pre_project_set_up_hermetic_build()
|
||||
endif()
|
||||
|
||||
########################################################################
|
||||
#
|
||||
# Project-wide settings
|
||||
|
||||
# Name of the project.
|
||||
#
|
||||
# CMake files in this project can refer to the root source directory
|
||||
# as ${gmock_SOURCE_DIR} and to the root binary directory as
|
||||
# ${gmock_BINARY_DIR}.
|
||||
# Language "C" is required for find_package(Threads).
|
||||
if (CMAKE_VERSION VERSION_LESS 3.0)
|
||||
project(gmock CXX C)
|
||||
else()
|
||||
cmake_policy(SET CMP0048 NEW)
|
||||
project(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)
|
||||
endif()
|
||||
cmake_minimum_required(VERSION 2.8.12)
|
||||
|
||||
if (COMMAND set_up_hermetic_build)
|
||||
set_up_hermetic_build()
|
||||
endif()
|
||||
|
||||
# Instructs CMake to process Google Test's CMakeLists.txt and add its
|
||||
# targets to the current scope. We are placing Google Test's binary
|
||||
# directory in a subdirectory of our own as VC compilation may break
|
||||
# if they are the same (the default).
|
||||
add_subdirectory("${gtest_dir}" "${gmock_BINARY_DIR}/${gtest_dir}")
|
||||
|
||||
|
||||
# These commands only run if this is the main project
|
||||
if(CMAKE_PROJECT_NAME STREQUAL "gmock" OR CMAKE_PROJECT_NAME STREQUAL "googletest-distribution")
|
||||
# BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to
|
||||
# make it prominent in the GUI.
|
||||
option(BUILD_SHARED_LIBS "Build shared libraries (DLLs)." OFF)
|
||||
else()
|
||||
mark_as_advanced(gmock_build_tests)
|
||||
endif()
|
||||
|
||||
# Although Google Test's CMakeLists.txt calls this function, the
|
||||
# changes there don't affect the current scope. Therefore we have to
|
||||
# call it again here.
|
||||
config_compiler_and_linker() # from ${gtest_dir}/cmake/internal_utils.cmake
|
||||
|
||||
# Adds Google Mock's and Google Test's header directories to the search path.
|
||||
set(gmock_build_include_dirs
|
||||
"${gmock_SOURCE_DIR}/include"
|
||||
"${gmock_SOURCE_DIR}"
|
||||
"${gtest_SOURCE_DIR}/include"
|
||||
# This directory is needed to build directly from Google Test sources.
|
||||
"${gtest_SOURCE_DIR}")
|
||||
include_directories(${gmock_build_include_dirs})
|
||||
|
||||
########################################################################
|
||||
#
|
||||
# Defines the gmock & gmock_main libraries. User tests should link
|
||||
# with one of them.
|
||||
|
||||
# Google Mock libraries. We build them using more strict warnings than what
|
||||
# are used for other targets, to ensure that Google Mock can be compiled by
|
||||
# a user aggressive about warnings.
|
||||
if (MSVC)
|
||||
cxx_library(gmock
|
||||
"${cxx_strict}"
|
||||
"${gtest_dir}/src/gtest-all.cc"
|
||||
src/gmock-all.cc)
|
||||
|
||||
cxx_library(gmock_main
|
||||
"${cxx_strict}"
|
||||
"${gtest_dir}/src/gtest-all.cc"
|
||||
src/gmock-all.cc
|
||||
src/gmock_main.cc)
|
||||
else()
|
||||
cxx_library(gmock "${cxx_strict}" src/gmock-all.cc)
|
||||
target_link_libraries(gmock PUBLIC gtest)
|
||||
set_target_properties(gmock PROPERTIES VERSION ${GOOGLETEST_VERSION})
|
||||
cxx_library(gmock_main "${cxx_strict}" src/gmock_main.cc)
|
||||
target_link_libraries(gmock_main PUBLIC gmock)
|
||||
set_target_properties(gmock_main PROPERTIES VERSION ${GOOGLETEST_VERSION})
|
||||
endif()
|
||||
# If the CMake version supports it, attach header directory information
|
||||
# to the targets for when we are part of a parent build (ie being pulled
|
||||
# in via add_subdirectory() rather than being a standalone build).
|
||||
if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11")
|
||||
target_include_directories(gmock SYSTEM INTERFACE
|
||||
"$<BUILD_INTERFACE:${gmock_build_include_dirs}>"
|
||||
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
|
||||
target_include_directories(gmock_main SYSTEM INTERFACE
|
||||
"$<BUILD_INTERFACE:${gmock_build_include_dirs}>"
|
||||
"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>")
|
||||
endif()
|
||||
|
||||
########################################################################
|
||||
#
|
||||
# Install rules
|
||||
install_project(gmock gmock_main)
|
||||
|
||||
########################################################################
|
||||
#
|
||||
# Google Mock's own tests.
|
||||
#
|
||||
# You can skip this section if you aren't interested in testing
|
||||
# Google Mock itself.
|
||||
#
|
||||
# The tests are not built by default. To build them, set the
|
||||
# gmock_build_tests option to ON. You can do it by running ccmake
|
||||
# or specifying the -Dgmock_build_tests=ON flag when running cmake.
|
||||
|
||||
if (gmock_build_tests)
|
||||
# This must be set in the root directory for the tests to be run by
|
||||
# 'make test' or ctest.
|
||||
enable_testing()
|
||||
|
||||
if (MINGW OR CYGWIN)
|
||||
if (CMAKE_VERSION VERSION_LESS "2.8.12")
|
||||
add_compile_options("-Wa,-mbig-obj")
|
||||
else()
|
||||
add_definitions("-Wa,-mbig-obj")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
############################################################
|
||||
# C++ tests built with standard compiler flags.
|
||||
|
||||
cxx_test(gmock-actions_test gmock_main)
|
||||
cxx_test(gmock-cardinalities_test gmock_main)
|
||||
cxx_test(gmock_ex_test gmock_main)
|
||||
cxx_test(gmock-function-mocker_test gmock_main)
|
||||
cxx_test(gmock-internal-utils_test gmock_main)
|
||||
cxx_test(gmock-matchers_test gmock_main)
|
||||
cxx_test(gmock-more-actions_test gmock_main)
|
||||
cxx_test(gmock-nice-strict_test gmock_main)
|
||||
cxx_test(gmock-port_test gmock_main)
|
||||
cxx_test(gmock-spec-builders_test gmock_main)
|
||||
cxx_test(gmock_link_test gmock_main test/gmock_link2_test.cc)
|
||||
cxx_test(gmock_test gmock_main)
|
||||
|
||||
if (DEFINED GTEST_HAS_PTHREAD)
|
||||
cxx_test(gmock_stress_test gmock)
|
||||
endif()
|
||||
|
||||
# gmock_all_test is commented to save time building and running tests.
|
||||
# Uncomment if necessary.
|
||||
# cxx_test(gmock_all_test gmock_main)
|
||||
|
||||
############################################################
|
||||
# C++ tests built with non-standard compiler flags.
|
||||
|
||||
if (MSVC)
|
||||
cxx_library(gmock_main_no_exception "${cxx_no_exception}"
|
||||
"${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
|
||||
|
||||
cxx_library(gmock_main_no_rtti "${cxx_no_rtti}"
|
||||
"${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
|
||||
|
||||
else()
|
||||
cxx_library(gmock_main_no_exception "${cxx_no_exception}" src/gmock_main.cc)
|
||||
target_link_libraries(gmock_main_no_exception PUBLIC gmock)
|
||||
|
||||
cxx_library(gmock_main_no_rtti "${cxx_no_rtti}" src/gmock_main.cc)
|
||||
target_link_libraries(gmock_main_no_rtti PUBLIC gmock)
|
||||
endif()
|
||||
cxx_test_with_flags(gmock-more-actions_no_exception_test "${cxx_no_exception}"
|
||||
gmock_main_no_exception test/gmock-more-actions_test.cc)
|
||||
|
||||
cxx_test_with_flags(gmock_no_rtti_test "${cxx_no_rtti}"
|
||||
gmock_main_no_rtti test/gmock-spec-builders_test.cc)
|
||||
|
||||
cxx_shared_library(shared_gmock_main "${cxx_default}"
|
||||
"${gtest_dir}/src/gtest-all.cc" src/gmock-all.cc src/gmock_main.cc)
|
||||
|
||||
# Tests that a binary can be built with Google Mock as a shared library. On
|
||||
# some system configurations, it may not possible to run the binary without
|
||||
# knowing more details about the system configurations. We do not try to run
|
||||
# this binary. To get a more robust shared library coverage, configure with
|
||||
# -DBUILD_SHARED_LIBS=ON.
|
||||
cxx_executable_with_flags(shared_gmock_test_ "${cxx_default}"
|
||||
shared_gmock_main test/gmock-spec-builders_test.cc)
|
||||
set_target_properties(shared_gmock_test_
|
||||
PROPERTIES
|
||||
COMPILE_DEFINITIONS "GTEST_LINKED_AS_SHARED_LIBRARY=1")
|
||||
|
||||
############################################################
|
||||
# Python tests.
|
||||
|
||||
cxx_executable(gmock_leak_test_ test gmock_main)
|
||||
py_test(gmock_leak_test)
|
||||
|
||||
cxx_executable(gmock_output_test_ test gmock)
|
||||
py_test(gmock_output_test)
|
||||
endif()
|
||||
@ -0,0 +1,44 @@
|
||||
# Googletest Mocking (gMock) Framework
|
||||
|
||||
### Overview
|
||||
|
||||
Google's framework for writing and using C++ mock classes. It can help you
|
||||
derive better designs of your system and write better tests.
|
||||
|
||||
It is inspired by:
|
||||
|
||||
* [jMock](http://www.jmock.org/)
|
||||
* [EasyMock](http://www.easymock.org/)
|
||||
* [Hamcrest](http://code.google.com/p/hamcrest/)
|
||||
|
||||
It is designed with C++'s specifics in mind.
|
||||
|
||||
gMock:
|
||||
|
||||
- Provides a declarative syntax for defining mocks.
|
||||
- Can define partial (hybrid) mocks, which are a cross of real and mock
|
||||
objects.
|
||||
- Handles functions of arbitrary types and overloaded functions.
|
||||
- Comes with a rich set of matchers for validating function arguments.
|
||||
- Uses an intuitive syntax for controlling the behavior of a mock.
|
||||
- Does automatic verification of expectations (no record-and-replay needed).
|
||||
- Allows arbitrary (partial) ordering constraints on function calls to be
|
||||
expressed.
|
||||
- Lets a user extend it by defining new matchers and actions.
|
||||
- Does not use exceptions.
|
||||
- Is easy to learn and use.
|
||||
|
||||
Details and examples can be found here:
|
||||
|
||||
* [gMock for Dummies](https://google.github.io/googletest/gmock_for_dummies.html)
|
||||
* [Legacy gMock FAQ](https://google.github.io/googletest/gmock_faq.html)
|
||||
* [gMock Cookbook](https://google.github.io/googletest/gmock_cook_book.html)
|
||||
* [gMock Cheat Sheet](https://google.github.io/googletest/gmock_cheat_sheet.html)
|
||||
|
||||
Please note that code under scripts/generator/ is from the
|
||||
[cppclean project](http://code.google.com/p/cppclean/) and under the Apache
|
||||
License, which is different from GoogleMock's license.
|
||||
|
||||
GoogleMock is a part of
|
||||
[GoogleTest C++ testing framework](http://github.com/google/googletest/) and a
|
||||
subject to the same requirements.
|
||||
@ -0,0 +1,10 @@
|
||||
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
|
||||
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
|
||||
|
||||
Name: gmock
|
||||
Description: GoogleMock (without main() function)
|
||||
Version: @PROJECT_VERSION@
|
||||
URL: https://github.com/google/googletest
|
||||
Requires: gtest = @PROJECT_VERSION@
|
||||
Libs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@
|
||||
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@
|
||||
@ -0,0 +1,10 @@
|
||||
libdir=@CMAKE_INSTALL_FULL_LIBDIR@
|
||||
includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@
|
||||
|
||||
Name: gmock_main
|
||||
Description: GoogleMock (with main() function)
|
||||
Version: @PROJECT_VERSION@
|
||||
URL: https://github.com/google/googletest
|
||||
Requires: gmock = @PROJECT_VERSION@
|
||||
Libs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@
|
||||
Cflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@
|
||||
@ -0,0 +1,4 @@
|
||||
# Content Moved
|
||||
|
||||
We are working on updates to the GoogleTest documentation, which has moved to
|
||||
the top-level [docs](../../docs) directory.
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,157 @@
|
||||
// Copyright 2007, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
|
||||
// Google Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
// This file implements some commonly used cardinalities. More
|
||||
// cardinalities can be defined by the user implementing the
|
||||
// CardinalityInterface interface if necessary.
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
|
||||
#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
|
||||
|
||||
#include <limits.h>
|
||||
#include <memory>
|
||||
#include <ostream> // NOLINT
|
||||
#include "gmock/internal/gmock-port.h"
|
||||
#include "gtest/gtest.h"
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \
|
||||
/* class A needs to have dll-interface to be used by clients of class B */)
|
||||
|
||||
namespace testing {
|
||||
|
||||
// To implement a cardinality Foo, define:
|
||||
// 1. a class FooCardinality that implements the
|
||||
// CardinalityInterface interface, and
|
||||
// 2. a factory function that creates a Cardinality object from a
|
||||
// const FooCardinality*.
|
||||
//
|
||||
// The two-level delegation design follows that of Matcher, providing
|
||||
// consistency for extension developers. It also eases ownership
|
||||
// management as Cardinality objects can now be copied like plain values.
|
||||
|
||||
// The implementation of a cardinality.
|
||||
class CardinalityInterface {
|
||||
public:
|
||||
virtual ~CardinalityInterface() {}
|
||||
|
||||
// Conservative estimate on the lower/upper bound of the number of
|
||||
// calls allowed.
|
||||
virtual int ConservativeLowerBound() const { return 0; }
|
||||
virtual int ConservativeUpperBound() const { return INT_MAX; }
|
||||
|
||||
// Returns true if and only if call_count calls will satisfy this
|
||||
// cardinality.
|
||||
virtual bool IsSatisfiedByCallCount(int call_count) const = 0;
|
||||
|
||||
// Returns true if and only if call_count calls will saturate this
|
||||
// cardinality.
|
||||
virtual bool IsSaturatedByCallCount(int call_count) const = 0;
|
||||
|
||||
// Describes self to an ostream.
|
||||
virtual void DescribeTo(::std::ostream* os) const = 0;
|
||||
};
|
||||
|
||||
// A Cardinality is a copyable and IMMUTABLE (except by assignment)
|
||||
// object that specifies how many times a mock function is expected to
|
||||
// be called. The implementation of Cardinality is just a std::shared_ptr
|
||||
// to const CardinalityInterface. Don't inherit from Cardinality!
|
||||
class GTEST_API_ Cardinality {
|
||||
public:
|
||||
// Constructs a null cardinality. Needed for storing Cardinality
|
||||
// objects in STL containers.
|
||||
Cardinality() {}
|
||||
|
||||
// Constructs a Cardinality from its implementation.
|
||||
explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {}
|
||||
|
||||
// Conservative estimate on the lower/upper bound of the number of
|
||||
// calls allowed.
|
||||
int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); }
|
||||
int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); }
|
||||
|
||||
// Returns true if and only if call_count calls will satisfy this
|
||||
// cardinality.
|
||||
bool IsSatisfiedByCallCount(int call_count) const {
|
||||
return impl_->IsSatisfiedByCallCount(call_count);
|
||||
}
|
||||
|
||||
// Returns true if and only if call_count calls will saturate this
|
||||
// cardinality.
|
||||
bool IsSaturatedByCallCount(int call_count) const {
|
||||
return impl_->IsSaturatedByCallCount(call_count);
|
||||
}
|
||||
|
||||
// Returns true if and only if call_count calls will over-saturate this
|
||||
// cardinality, i.e. exceed the maximum number of allowed calls.
|
||||
bool IsOverSaturatedByCallCount(int call_count) const {
|
||||
return impl_->IsSaturatedByCallCount(call_count) &&
|
||||
!impl_->IsSatisfiedByCallCount(call_count);
|
||||
}
|
||||
|
||||
// Describes self to an ostream
|
||||
void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }
|
||||
|
||||
// Describes the given actual call count to an ostream.
|
||||
static void DescribeActualCallCountTo(int actual_call_count,
|
||||
::std::ostream* os);
|
||||
|
||||
private:
|
||||
std::shared_ptr<const CardinalityInterface> impl_;
|
||||
};
|
||||
|
||||
// Creates a cardinality that allows at least n calls.
|
||||
GTEST_API_ Cardinality AtLeast(int n);
|
||||
|
||||
// Creates a cardinality that allows at most n calls.
|
||||
GTEST_API_ Cardinality AtMost(int n);
|
||||
|
||||
// Creates a cardinality that allows any number of calls.
|
||||
GTEST_API_ Cardinality AnyNumber();
|
||||
|
||||
// Creates a cardinality that allows between min and max calls.
|
||||
GTEST_API_ Cardinality Between(int min, int max);
|
||||
|
||||
// Creates a cardinality that allows exactly n calls.
|
||||
GTEST_API_ Cardinality Exactly(int n);
|
||||
|
||||
// Creates a cardinality from its implementation.
|
||||
inline Cardinality MakeCardinality(const CardinalityInterface* c) {
|
||||
return Cardinality(c);
|
||||
}
|
||||
|
||||
} // namespace testing
|
||||
|
||||
GTEST_DISABLE_MSC_WARNINGS_POP_() // 4251
|
||||
|
||||
#endif // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_
|
||||
@ -0,0 +1,479 @@
|
||||
// Copyright 2007, Google Inc.
|
||||
// All rights reserved.
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
// Google Mock - a framework for writing C++ mock classes.
|
||||
//
|
||||
// This file implements MOCK_METHOD.
|
||||
|
||||
// GOOGLETEST_CM0002 DO NOT DELETE
|
||||
|
||||
#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
|
||||
#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_ // NOLINT
|
||||
|
||||
#include <type_traits> // IWYU pragma: keep
|
||||
#include <utility> // IWYU pragma: keep
|
||||
|
||||
#include "gmock/gmock-spec-builders.h"
|
||||
#include "gmock/internal/gmock-internal-utils.h"
|
||||
#include "gmock/internal/gmock-pp.h"
|
||||
|
||||
namespace testing {
|
||||
namespace internal {
|
||||
template <typename T>
|
||||
using identity_t = T;
|
||||
|
||||
template <typename Pattern>
|
||||
struct ThisRefAdjuster {
|
||||
template <typename T>
|
||||
using AdjustT = typename std::conditional<
|
||||
std::is_const<typename std::remove_reference<Pattern>::type>::value,
|
||||
typename std::conditional<std::is_lvalue_reference<Pattern>::value,
|
||||
const T&, const T&&>::type,
|
||||
typename std::conditional<std::is_lvalue_reference<Pattern>::value, T&,
|
||||
T&&>::type>::type;
|
||||
|
||||
template <typename MockType>
|
||||
static AdjustT<MockType> Adjust(const MockType& mock) {
|
||||
return static_cast<AdjustT<MockType>>(const_cast<MockType&>(mock));
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace internal
|
||||
|
||||
// The style guide prohibits "using" statements in a namespace scope
|
||||
// inside a header file. However, the FunctionMocker class template
|
||||
// is meant to be defined in the ::testing namespace. The following
|
||||
// line is just a trick for working around a bug in MSVC 8.0, which
|
||||
// cannot handle it if we define FunctionMocker in ::testing.
|
||||
using internal::FunctionMocker;
|
||||
} // namespace testing
|
||||
|
||||
#define MOCK_METHOD(...) \
|
||||
GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__)
|
||||
|
||||
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \
|
||||
GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
|
||||
|
||||
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_2(...) \
|
||||
GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
|
||||
|
||||
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \
|
||||
GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ())
|
||||
|
||||
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec) \
|
||||
GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args); \
|
||||
GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec); \
|
||||
GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
|
||||
GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)); \
|
||||
GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
|
||||
GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
|
||||
GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec), \
|
||||
GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \
|
||||
GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec), \
|
||||
GMOCK_INTERNAL_GET_CALLTYPE(_Spec), GMOCK_INTERNAL_GET_REF_SPEC(_Spec), \
|
||||
(GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)))
|
||||
|
||||
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \
|
||||
GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
|
||||
|
||||
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_6(...) \
|
||||
GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
|
||||
|
||||
#define GMOCK_INTERNAL_MOCK_METHOD_ARG_7(...) \
|
||||
GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)
|
||||
|
||||
#define GMOCK_INTERNAL_WRONG_ARITY(...) \
|
||||
static_assert( \
|
||||
false, \
|
||||
"MOCK_METHOD must be called with 3 or 4 arguments. _Ret, " \
|
||||
"_MethodName, _Args and optionally _Spec. _Args and _Spec must be " \
|
||||
"enclosed in parentheses. If _Ret is a type with unprotected commas, " \
|
||||
"it must also be enclosed in parentheses.")
|
||||
|
||||
#define GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Tuple) \
|
||||
static_assert( \
|
||||
GMOCK_PP_IS_ENCLOSED_PARENS(_Tuple), \
|
||||
GMOCK_PP_STRINGIZE(_Tuple) " should be enclosed in parentheses.")
|
||||
|
||||
#define GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(_N, ...) \
|
||||
static_assert( \
|
||||
std::is_function<__VA_ARGS__>::value, \
|
||||
"Signature must be a function type, maybe return type contains " \
|
||||
"unprotected comma."); \
|
||||
static_assert( \
|
||||
::testing::tuple_size<typename ::testing::internal::Function< \
|
||||
__VA_ARGS__>::ArgumentTuple>::value == _N, \
|
||||
"This method does not take " GMOCK_PP_STRINGIZE( \
|
||||
_N) " arguments. Parenthesize all types with unprotected commas.")
|
||||
|
||||
#define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \
|
||||
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec)
|
||||
|
||||
#define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness, \
|
||||
_Override, _Final, _NoexceptSpec, \
|
||||
_CallType, _RefSpec, _Signature) \
|
||||
typename ::testing::internal::Function<GMOCK_PP_REMOVE_PARENS( \
|
||||
_Signature)>::Result \
|
||||
GMOCK_INTERNAL_EXPAND(_CallType) \
|
||||
_MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N)) \
|
||||
GMOCK_PP_IF(_Constness, const, ) _RefSpec _NoexceptSpec \
|
||||
GMOCK_PP_IF(_Override, override, ) GMOCK_PP_IF(_Final, final, ) { \
|
||||
GMOCK_MOCKER_(_N, _Constness, _MethodName) \
|
||||
.SetOwnerAndName(this, #_MethodName); \
|
||||
return GMOCK_MOCKER_(_N, _Constness, _MethodName) \
|
||||
.Invoke(GMOCK_PP_REPEAT(GMOCK_INTERNAL_FORWARD_ARG, _Signature, _N)); \
|
||||
} \
|
||||
::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
|
||||
GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N)) \
|
||||
GMOCK_PP_IF(_Constness, const, ) _RefSpec { \
|
||||
GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this); \
|
||||
return GMOCK_MOCKER_(_N, _Constness, _MethodName) \
|
||||
.With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N)); \
|
||||
} \
|
||||
::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \
|
||||
const ::testing::internal::WithoutMatchers&, \
|
||||
GMOCK_PP_IF(_Constness, const, )::testing::internal::Function< \
|
||||
GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _RefSpec _NoexceptSpec { \
|
||||
return ::testing::internal::ThisRefAdjuster<GMOCK_PP_IF( \
|
||||
_Constness, const, ) int _RefSpec>::Adjust(*this) \
|
||||
.gmock_##_MethodName(GMOCK_PP_REPEAT( \
|
||||
GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N)); \
|
||||
} \
|
||||
mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)> \
|
||||
GMOCK_MOCKER_(_N, _Constness, _MethodName)
|
||||
|
||||
#define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__
|
||||
|
||||
// Five Valid modifiers.
|
||||
#define GMOCK_INTERNAL_HAS_CONST(_Tuple) \
|
||||
GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple))
|
||||
|
||||
#define GMOCK_INTERNAL_HAS_OVERRIDE(_Tuple) \
|
||||
GMOCK_PP_HAS_COMMA( \
|
||||
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_OVERRIDE, ~, _Tuple))
|
||||
|
||||
#define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \
|
||||
GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple))
|
||||
|
||||
#define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \
|
||||
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple)
|
||||
|
||||
#define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem) \
|
||||
GMOCK_PP_IF( \
|
||||
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \
|
||||
_elem, )
|
||||
|
||||
#define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \
|
||||
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple)
|
||||
|
||||
#define GMOCK_INTERNAL_REF_SPEC_IF_REF(_i, _, _elem) \
|
||||
GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \
|
||||
GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), )
|
||||
|
||||
#define GMOCK_INTERNAL_GET_CALLTYPE(_Tuple) \
|
||||
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_CALLTYPE_IMPL, ~, _Tuple)
|
||||
|
||||
#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \
|
||||
static_assert( \
|
||||
(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) + \
|
||||
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) + \
|
||||
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) + \
|
||||
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) + \
|
||||
GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) + \
|
||||
GMOCK_INTERNAL_IS_CALLTYPE(_elem)) == 1, \
|
||||
GMOCK_PP_STRINGIZE( \
|
||||
_elem) " cannot be recognized as a valid specification modifier.");
|
||||
|
||||
// Modifiers implementation.
|
||||
#define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \
|
||||
GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CONST_I_, _elem)
|
||||
|
||||
#define GMOCK_INTERNAL_DETECT_CONST_I_const ,
|
||||
|
||||
#define GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem) \
|
||||
GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_OVERRIDE_I_, _elem)
|
||||
|
||||
#define GMOCK_INTERNAL_DETECT_OVERRIDE_I_override ,
|
||||
|
||||
#define GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem) \
|
||||
GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_FINAL_I_, _elem)
|
||||
|
||||
#define GMOCK_INTERNAL_DETECT_FINAL_I_final ,
|
||||
|
||||
#define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \
|
||||
GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem)
|
||||
|
||||
#define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept ,
|
||||
|
||||
#define GMOCK_INTERNAL_DETECT_REF(_i, _, _elem) \
|
||||
GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_REF_I_, _elem)
|
||||
|
||||
#define GMOCK_INTERNAL_DETECT_REF_I_ref ,
|
||||
|
||||
#define GMOCK_INTERNAL_UNPACK_ref(x) x
|
||||
|
||||
#define GMOCK_INTERNAL_GET_CALLTYPE_IMPL(_i, _, _elem) \
|
||||
GMOCK_PP_IF(GMOCK_INTERNAL_IS_CALLTYPE(_elem), \
|
||||
GMOCK_INTERNAL_GET_VALUE_CALLTYPE, GMOCK_PP_EMPTY) \
|
||||
(_elem)
|
||||
|
||||
// TODO(iserna): GMOCK_INTERNAL_IS_CALLTYPE and
|
||||
// GMOCK_INTERNAL_GET_VALUE_CALLTYPE needed more expansions to work on windows
|
||||
// maybe they can be simplified somehow.
|
||||
#define GMOCK_INTERNAL_IS_CALLTYPE(_arg) \
|
||||
GMOCK_INTERNAL_IS_CALLTYPE_I( \
|
||||
GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg))
|
||||
#define GMOCK_INTERNAL_IS_CALLTYPE_I(_arg) GMOCK_PP_IS_ENCLOSED_PARENS(_arg)
|
||||
|
||||
#define GMOCK_INTERNAL_GET_VALUE_CALLTYPE(_arg) \
|
||||
GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I( \
|
||||
GMOCK_PP_CAT(GMOCK_INTERNAL_IS_CALLTYPE_HELPER_, _arg))
|
||||
#define GMOCK_INTERNAL_GET_VALUE_CALLTYPE_I(_arg) \
|
||||
GMOCK_PP_IDENTITY _arg
|
||||
|
||||
#define GMOCK_INTERNAL_IS_CALLTYPE_HELPER_Calltype
|
||||
|
||||
// Note: The use of `identity_t` here allows _Ret to represent return types that
|
||||
// would normally need to be specified in a different way. For example, a method
|
||||
// returning a function pointer must be written as
|
||||
//
|
||||
// fn_ptr_return_t (*method(method_args_t...))(fn_ptr_args_t...)
|
||||
//
|
||||
// But we only support placing the return type at the beginning. To handle this,
|
||||
// we wrap all calls in identity_t, so that a declaration will be expanded to
|
||||
//
|
||||
// identity_t<fn_ptr_return_t (*)(fn_ptr_args_t...)> method(method_args_t...)
|
||||
//
|
||||
// This allows us to work around the syntactic oddities of function/method
|
||||
// types.
|
||||
#define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args) \
|
||||
::testing::internal::identity_t<GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_Ret), \
|
||||
GMOCK_PP_REMOVE_PARENS, \
|
||||
GMOCK_PP_IDENTITY)(_Ret)>( \
|
||||
GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args))
|
||||
|
||||
#define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem) \
|
||||
GMOCK_PP_COMMA_IF(_i) \
|
||||
GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_elem), GMOCK_PP_REMOVE_PARENS, \
|
||||
GMOCK_PP_IDENTITY) \
|
||||
(_elem)
|
||||
|
||||
#define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _) \
|
||||
GMOCK_PP_COMMA_IF(_i) \
|
||||
GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
|
||||
gmock_a##_i
|
||||
|
||||
#define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \
|
||||
GMOCK_PP_COMMA_IF(_i) \
|
||||
::std::forward<GMOCK_INTERNAL_ARG_O( \
|
||||
_i, GMOCK_PP_REMOVE_PARENS(_Signature))>(gmock_a##_i)
|
||||
|
||||
#define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _) \
|
||||
GMOCK_PP_COMMA_IF(_i) \
|
||||
GMOCK_INTERNAL_MATCHER_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \
|
||||
gmock_a##_i
|
||||
|
||||
#define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \
|
||||
GMOCK_PP_COMMA_IF(_i) \
|
||||
gmock_a##_i
|
||||
|
||||
#define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \
|
||||
GMOCK_PP_COMMA_IF(_i) \
|
||||
::testing::A<GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature))>()
|
||||
|
||||
#define GMOCK_INTERNAL_ARG_O(_i, ...) \
|
||||
typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type
|
||||
|
||||
#define GMOCK_INTERNAL_MATCHER_O(_i, ...) \
|
||||
const ::testing::Matcher<typename ::testing::internal::Function< \
|
||||
__VA_ARGS__>::template Arg<_i>::type>&
|
||||
|
||||
#define MOCK_METHOD0(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 0, __VA_ARGS__)
|
||||
#define MOCK_METHOD1(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 1, __VA_ARGS__)
|
||||
#define MOCK_METHOD2(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 2, __VA_ARGS__)
|
||||
#define MOCK_METHOD3(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 3, __VA_ARGS__)
|
||||
#define MOCK_METHOD4(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 4, __VA_ARGS__)
|
||||
#define MOCK_METHOD5(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 5, __VA_ARGS__)
|
||||
#define MOCK_METHOD6(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 6, __VA_ARGS__)
|
||||
#define MOCK_METHOD7(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 7, __VA_ARGS__)
|
||||
#define MOCK_METHOD8(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 8, __VA_ARGS__)
|
||||
#define MOCK_METHOD9(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 9, __VA_ARGS__)
|
||||
#define MOCK_METHOD10(m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(, , m, 10, __VA_ARGS__)
|
||||
|
||||
#define MOCK_CONST_METHOD0(m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 0, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD1(m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 1, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD2(m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 2, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD3(m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 3, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD4(m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 4, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD5(m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 5, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD6(m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 6, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD7(m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 7, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD8(m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 8, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD9(m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 9, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD10(m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, , m, 10, __VA_ARGS__)
|
||||
|
||||
#define MOCK_METHOD0_T(m, ...) MOCK_METHOD0(m, __VA_ARGS__)
|
||||
#define MOCK_METHOD1_T(m, ...) MOCK_METHOD1(m, __VA_ARGS__)
|
||||
#define MOCK_METHOD2_T(m, ...) MOCK_METHOD2(m, __VA_ARGS__)
|
||||
#define MOCK_METHOD3_T(m, ...) MOCK_METHOD3(m, __VA_ARGS__)
|
||||
#define MOCK_METHOD4_T(m, ...) MOCK_METHOD4(m, __VA_ARGS__)
|
||||
#define MOCK_METHOD5_T(m, ...) MOCK_METHOD5(m, __VA_ARGS__)
|
||||
#define MOCK_METHOD6_T(m, ...) MOCK_METHOD6(m, __VA_ARGS__)
|
||||
#define MOCK_METHOD7_T(m, ...) MOCK_METHOD7(m, __VA_ARGS__)
|
||||
#define MOCK_METHOD8_T(m, ...) MOCK_METHOD8(m, __VA_ARGS__)
|
||||
#define MOCK_METHOD9_T(m, ...) MOCK_METHOD9(m, __VA_ARGS__)
|
||||
#define MOCK_METHOD10_T(m, ...) MOCK_METHOD10(m, __VA_ARGS__)
|
||||
|
||||
#define MOCK_CONST_METHOD0_T(m, ...) MOCK_CONST_METHOD0(m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD1_T(m, ...) MOCK_CONST_METHOD1(m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD2_T(m, ...) MOCK_CONST_METHOD2(m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD3_T(m, ...) MOCK_CONST_METHOD3(m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD4_T(m, ...) MOCK_CONST_METHOD4(m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD5_T(m, ...) MOCK_CONST_METHOD5(m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD6_T(m, ...) MOCK_CONST_METHOD6(m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD7_T(m, ...) MOCK_CONST_METHOD7(m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD8_T(m, ...) MOCK_CONST_METHOD8(m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD9_T(m, ...) MOCK_CONST_METHOD9(m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD10_T(m, ...) MOCK_CONST_METHOD10(m, __VA_ARGS__)
|
||||
|
||||
#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 0, __VA_ARGS__)
|
||||
#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 1, __VA_ARGS__)
|
||||
#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 2, __VA_ARGS__)
|
||||
#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 3, __VA_ARGS__)
|
||||
#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 4, __VA_ARGS__)
|
||||
#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 5, __VA_ARGS__)
|
||||
#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 6, __VA_ARGS__)
|
||||
#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 7, __VA_ARGS__)
|
||||
#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 8, __VA_ARGS__)
|
||||
#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 9, __VA_ARGS__)
|
||||
#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 10, __VA_ARGS__)
|
||||
|
||||
#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 0, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 1, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 2, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 3, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 4, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 5, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 6, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 7, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 8, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 9, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \
|
||||
GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 10, __VA_ARGS__)
|
||||
|
||||
#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
|
||||
#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \
|
||||
MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)
|
||||
|
||||
#define GMOCK_INTERNAL_MOCK_METHODN(constness, ct, Method, args_num, ...) \
|
||||
GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE( \
|
||||
args_num, ::testing::internal::identity_t<__VA_ARGS__>); \
|
||||
GMOCK_INTERNAL_MOCK_METHOD_IMPL( \
|
||||
args_num, Method, GMOCK_PP_NARG0(constness), 0, 0, , ct, , \
|
||||
(::testing::internal::identity_t<__VA_ARGS__>))
|
||||
|
||||
#define GMOCK_MOCKER_(arity, constness, Method) \
|
||||
GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)
|
||||
|
||||
#endif // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user